How to change the value of subsequent inputs?

4

In a form there are N occurrences of values for the same product, to facilitate I'm wanting to apply the same value for the subsequent inputs.

For example, using the structure below:

<input class="valor partida" type="text" name="novo_valor_partida-1" value="11,11" data-produto="0101000" data-id="1">

<input class="valor partida" type="text" name="novo_valor_partida-2" value="11,11" data-produto="0101000" data-id="2">

<input class="valor partida" type="text" name="novo_valor_partida-3" value="11,11" data-produto="0101000" data-id="3">

When you change the value in input 1, 2 and 3 will also receive the value. If input 2 is changed, only 3 receives the value and so on.

Since there are N fields, I will use the data-produto attribute to select the inputs.

    
asked by anonymous 18.05.2016 / 21:50

2 answers

7

You can do this:

$('input').on('change', function() {
    $(this).nextAll('input').val(this.value);
});

jsFiddle: link

nextAll() will fetch all the next siblings of the element, in this case with the selector input .

I used the event change but you can also use keyup and this happens at the time of writing. You may want to use both to make sure it works even though the content has been placed by copy / paste.

    
18.05.2016 / 22:05
0

I made an example in jQuery.

  • I select all inputs that data-produto is 0101000
  • Add to all of them a listen for events change and keyup
  • Except the value of the input that called the event
  • I assign the new value to all inputs

var $todosInputs = $('input[data-produto=\'0101000\']');
$todosInputs.on('change keyup', function() {
  $(this).nextAll($todosInputs).val($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputclass="valor partida" type="text" name="novo_valor_partida-1" value="11,11" data-produto="0101000" data-id="1">
<input class="valor partida" type="text" name="novo_valor_partida-2" value="11,11" data-produto="0101000" data-id="2">
<input class="valor partida" type="text" name="novo_valor_partida-3" value="11,11" data-produto="0101000" data-id="3">
    
18.05.2016 / 22:42