views:

1256

answers:

2

Need to take a SELECT drop down list options and find if any of the values are whole numbers, then append a .00 to the list value option. need to change the value as well.

<select>
  <option value="1">1</option>
  <option value="1.99">1.99</option>
  <option value="2.99">2.99</option>
  <option value="4">4</option>
</select>

Thanks in advance for any help on this

+5  A: 

Not quite sure if this is the best way, but it works:

$('option', '#myselect').each(function() {
    if($(this).val() == parseInt($(this).val(), 10)) {
         var x = $(this).val() + '.00';
         $(this).val(x).text(x);
    }
});

Demo.

On second thought, you could also do this using toFixed, which is cleaner:

$('option', '#myselect').each(function() {
    var x = Number($(this).val()).toFixed(2);
    $(this).val(x).text(x);
});

Demo.

Paolo Bergantino
+1 for the demo
TStamper
I like the first solution but not working on page reload when values are populated from database
Phill Pafford
Got it thanks :)
Phill Pafford
BTW I looked into your second solution and it seems to round up the number. Just wanted to clarify if that's the case?
Phill Pafford
I Used the first solution. again thank you
Phill Pafford
How do I use this for two and three digit numbers? 10 needs to be 10.00 and 100 needs to be 100.00
Phill Pafford
I think the second solution solved my problem thanks again.
Phill Pafford
+1  A: 

If you plan on using string formatting a lot, i recommend getting the plugin:

http://code.google.com/p/jquery-utils/wiki/StringFormat

It would then be as easy as: $.format('{a:.2f}', {a:'1'})

Russ Bradberry