0

I'd like to change the value of a HTML input dynamically. The code is next:

for ( var i = 0; i < num_years; i++ ) {

    $( '#Edit-ano' + i ).on( "input", function() {

        var element = document.getElementById( 'Edit-ano' + i );
        element.value = addCommas( $(this).val() );

    });
}

But I'm receiving the next message:

Uncaught TypeError: Cannot set property 'value' of null

I've tried too passing "'Edit-ano' + i" as parameter, and using jQuery, as follow:

for ( var i = 0; i < num_years; i++ ) {

    $( '#Edit-ano' + i ).on( "input", function() {

        var paramater = "Edit-ano" + i;
        var element = document.getElementById( paramater );
        element.value = addCommas( $(this).val() );

    });
}

Or:

for ( var i = 0; i < num_years; i++ ) {

    $( '#Edit-ano' + i ).on( "input", function() {

        var paramater = "#Edit-ano" + i;
        var element = $( paramater )[0]; //also using: var element = $( "#Edit-ano" + i )[0]
        element.value = addCommas( $(this).val() );

    });
}

and in all the cases, I'm receiving the same error.

The code is being used in a jTable, inside the "formCreated" event.

The surprise is that if I pass the argument directly as "Edit-ano0", for example, it works perfectly! But then, I loss the dynamic behavior :(

My ideas are over, so, I hope for your answers!

Thanks in advance!

Tecnólogo
  • 13
  • 5
  • `i` has no scope here so it will be whatever the last value of `i` was after the loop finished. Also why reselect the input? Are you just trying to update the value `this`? If so why not just do `$(this).val(addCommas( $(this).val() ));`? – AtheistP3ace Dec 22 '15 at 20:31
  • Just use a common class. `$(".commonClass").on("click", function () { this.value = addCommas( this.value ); } );` – epascarello Dec 22 '15 at 20:37
  • It works perfectly! I'm adding thousands separators automatically, that are commas (`,`), but I don't allow to input commas. That is the reason because I need to modify the value `this` after a new input. Thank you very much for your answers!!! – Tecnólogo Dec 22 '15 at 20:51
  • Use a common class is a good idea too! Could I simultaneously reference to a several classes that have the same root? For example: "Edit-ano0", "Edit-ano1", "Edit-ano1", etc. This is because the HTML is being created by other plugin (jTable)... Thank you very much again! – Tecnólogo Dec 22 '15 at 21:02

1 Answers1

2

Try this. You simply need to delegate 'input' or 'keyup' event during DOM load and append the value with comma.

$(document).ready(function(){
var num_years = 4;
for ( var i = 0; i < num_years; i++ ) {

    $( '#Edit-ano' + i ).on( "input", function() {
        $(this).val($(this).val() + ',');
    });
}
});

Example : https://jsfiddle.net/DinoMyte/r9pffj2s/1/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26