thegodth
thegodth

Reputation: 55

How to jquery input array with auto decimal (each)

I have some input box fields loop from database records counts look like this..

<input name="price[]" id="price_1" />
<input name="price[]" id="price_2" />
<input name="price[]" id="price_3" />

And I also have a javascript for automatic decimal look like this... (This script will auto fill 2 decimal 0.00 into the value.

function autoDecimal(el){
$(el).blur(function(){
    var myNumeric = parseFloat($(this).val());
    if (!myNumeric) {
        $(this).val('0.00');
    } else {
        $(this).val(myNumeric.toFixed(2));
    }
});
}

This script work perfectly only 1 element id like

autoDecimal('#a');

but I need to improve it to check all input box with array names. like this or somthing better than this code below.

$('input['price']).each(function(){
// do auto matic add decimal each input box
});

If you have an idea please share.

Thanks (I'm not advanced in javascript or jquery)

Upvotes: 0

Views: 847

Answers (3)

benzonico
benzonico

Reputation: 10833

You can reuse the function 'autodecimal' but simply pass to it a right jquery selector like the one suggested by slash197 :

autoDecimal('input[name~="price"]');

This should work.

Upvotes: 0

coder
coder

Reputation: 13248

DEMO

$("input:text").on("keyup", function(e) {
    var myNumeric = parseFloat($(this).val());
    if (!myNumeric) 
    {
        $(this).val('0.00');
    } 
    else 
    {
        $(this).val(myNumeric.toFixed(2));
    }
});

Upvotes: 0

slash197
slash197

Reputation: 9034

$('input[name~="price"]').blur(function(){
    var myNumeric = parseFloat($(this).val());
    if (!myNumeric) 
    {
        $(this).val('0.00');
    } 
    else 
    {
        $(this).val(myNumeric.toFixed(2));
    }
});

Upvotes: 1

Related Questions