JQuery syntax bug on an auto-fill listener and keyup trigger while looping and looking for sequentially named inputs

StackOverflow https://stackoverflow.com/questions/16869581

Question

So, I am working with (playing with, as I am not an employed developer) many different inputs on a web form. The end game is that they will be posted and saved as a CSV file.

But the immediate question I have is regarding the syntax to loop through names and activate a autofill for adjacent cells

Here is an example code of a single event that works:

$(".className").keyup(function(){
    var dataPoint = $(this).val();
    if(!$('[name="this_row_1"]') ==''){
        $('[name="that_row_1"]').val(dataPoint);
    }
});

So, when the input with ".className" is altered, if "this_row_1" is not empty, then "that_row_1" will be filled with the value of ".className".

The code works, but I have many inputs with sequentially named rows; "this_row_1" - "this_row_150" etc.

What is the correct syntax to incorporate a loop in the '[name=" type structure?

I have tried variants of this with no success:

$(".className").keyup(function(){
    var dataPoint = $(this).val();
    for(var i = 1; i < 151; i++)
    if(!$('[name="this_row_"[i]]') ==''){
        $('[name="that_row_"[i]]').val(dataPoint);
    }
});

I am not sure if you can even loop through '[name=". And if you can, certainly I have issues placing the loop variable.

Thanks in advance

Updated:

Here is an abbreviated, example HTML form code which illustrates the idea a little better:

<input class="className" />
<table>
    <tr>
        <td><input name="this_row_1" /><input name="that_row_1" /></td>
    </tr>
    <tr>
        <td><input name="this_row_2" /><input name="that_row_2" /></td>
    </tr>
    <tr>
        <td><input name="this_row_3" /><input name="that_row_3" /></td>
    </tr>
    <!-- ( . . . ) -->
    <tr>
        <td><input name="this_row_150" /><input name="that_row_150" /></td>
    </tr>
</table>
Était-ce utile?

La solution

Try this:

$(".className").keyup(function() {
    var dataPoint = $(this).val();
    for (var i = 1; i < 151; i++) {
      if ($('[name="this_row_' + i + '"]').val() != '') {
        $('[name="this_row_' + i + '"]').val(dataPoint);
      }
    }
});

There were a few issues:

  1. with your string concatenation '[name="this_row_' + i + '"]'
  2. your if statement equality check !=
  3. checking the .val() of $('[name="this_row_' + i + '"]')

See Javascript String documentation for more information.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top