How can round multiple inputs with the same id?

2.2k Views Asked by At

I did a script using JQUERY 1.6 to round input, so when I type a long number my script will automatically round 2 decimals.

But is only working with the first input and is not working with other inputs with the same input ID

Here is the live demo

<script>
jQuery("#round_inputs").live("change", function(){
 input_values = parseFloat(jQuery("#round_inputs").val());
 if (isNaN(input_values)) input_values = "";
 jQuery("#round_inputs").val(input_values.toFixed(2));  
});  
</script>

<input id="round_inputs" size="20" style="text-align:right" type="text"/><br/>
<input id="round_inputs" size="20" style="text-align:right" type="text"/><br/>
<input id="round_inputs" size="20" style="text-align:right" type="text"/><br/>

Please somebody can help me?

3

There are 3 best solutions below

1
On BEST ANSWER

As was pointed out in the comments, ID must be unique, so use classes instead. And you need to refer to each input with jQuery(this), otherwise you're just referring to the first element with the class:

jQuery(".round_inputs").live("change", function () {
    input_values = parseFloat(jQuery(this).val());
    if (isNaN(input_values)) input_values = "";
    jQuery(this).val(input_values.toFixed(2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<input class="round_inputs" size="20" style="text-align:right" type="text" />
<br/>
<input class="round_inputs" size="20" style="text-align:right" type="text" />
<br/>
<input class="round_inputs" size="20" style="text-align:right" type="text" />

Also, as of jQuery 1.7 .live() has been deprecated in favor of .on(), so consider updating your code accordingly.

2
On

When using ID Selectors, jQuery will only ever return the first instance. You should use a classname selector for this:

 <input id="round_input1" class="round-input" size="20" style="text-align:right" type="text"/><br/>

And change your jQuery selector to: jQuery('.round-input')

https://api.jquery.com/id-selector/

0
On

First off. ID's in a HTML page is supposed to be unique.

Use classes instead.

  • Avoid inline styles , use CSS to keep your HTML clean.
  • Inside the change handler use $(this) to target the element that triggered the event.
  • Use on instead of live which is now deprecated.

JS

$(".round_inputs").on("change", function () {
    var input_values = parseFloat($(this).val());
    if (isNaN(input_values)) input_values = "";
    $(this).val(input_values.toFixed(2));
});

HTML

<input class="round_inputs" size="20" type="text" />
<br/>
<input class="round_inputs" size="20" type="text" />
<br/>
<input class="round_inputs" size="20" type="text" />
<br/>

CSS

.round_inputs {
    text-align:right
}

Check Fiddle