我有一个标有'campaign_value'的选择框,其中包含美元值。它们看起来像这样($ 1,$ 2,$ 3,......)。我有另一个选择框,需要在更改时从“campaign_value”获取更新后的值。以下是我到目前为止......
HTML
<select id="campaign_value" name="campaign_value">
<option value="1">$1</option>
<option value="2">$2</option>
<option value="3">$3</option>
</select>
<select id="campaign_subject" name="campaign_subject">
<option value="You received $1 for food!">You received $1 for food!</option>
</select>
JS
$('#campaign_value').change(function(){
var replacement = $(this).val();
var regex = /\$?((\d{1,3}(,\d{3})*)|(\d+))(\.\d{2})?$/;
$('#campaign_subject option').each(function() {
this.text = this.text.replace(regex, replacement);
this.value = this.value.replace(regex, replacement);
});
});
我错过了什么?我的正则表达式是否正确设置了金额?
答案 0 :(得分:1)
这样的事情:
$('#campaign_value').change(function(){
var replacement = $(this).val();
var regex = /\d+/;
$('#campaign_subject option').each(function() {
var r = $(this).text().replace(regex,replacement);
$(this).text(r).val(r);
});
});
简单的正则表达式,没什么特别的。
答案 1 :(得分:0)
尝试@ http://jsfiddle.net/Am6Te/3/
$(document).ready(function(){
$('#campaign_value').change(function(){
var replacement = '$\$'+$(this).val();
var regex = /\$(\d)/;
$('#campaign_subject option').each(function() {
$(this).text($(this).text().replace(regex ,replacement));
$(this).val($(this).val().replace(regex ,replacement)); });
});
})
答案 2 :(得分:0)
尝试使用下一个regexp:
// for replace all entries of $123 or $123.4 or $123.45
// (maximum three digits before dot (if exist)
// and maximum two digits after dot (if exist)
var regex = /\$\d{1,3}(\.\d{1,2})?/g;
// same as above but no maximum digits before dot
var regex = /\$\d+(\.\d{1,2})?/g;
// or without /g to replace only first occurence
var regex = /\$\d{1,3}(\.\d{1,2})?/;
// or
var regex = /\$\d+(\.\d{1,2})?/;
更换:
this.text = this.text.replace(regex, "$"+replacement); // because replacement does not contain "$" sign
this.value = this.value.replace(regex, "$"+replacement);