开发者

How do I update the text of a select box using javascript and regular expressions?

I have a select box labeled 'campaign_value' with dollar values in it. They look like this ($1, $2, $3, ...). I have another select box that needs to get the updated value from 'campaign_value' when it is changed. Below is what I have so far...

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);
       开发者_如何学JAVA this.value = this.value.replace(regex, replacement);
    });
});

What am I missing? Is my regex set correctly for dollar amounts?


Something like this:

$('#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);
    });
});

Simple regex, nothing special.


Try @ 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));              });
    });
})


Try to use next 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})?/;

Replacing:

this.text = this.text.replace(regex, "$"+replacement); // because replacement does not contain "$" sign
this.value = this.value.replace(regex, "$"+replacement);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜