0

I have HTML table with JQuery..i want to change values on the same cell after i inputting some numbers..

This is what i tried so far..

<table>
 <thead>
  <tr>
    <th>Numbers</th>
    <th>Text</th>
  </tr>
 <thead>
 <tbody>
   <tr>
    <td><input type="number" name="result[]" id='result_1'></td>
    <td id="condition_1"></td>
  </tr>
  <tr>
    <td><input type="number" name="result[]" id='result_2'></td>
    <td id="condition_2"></td>
  </tr>
 <tbody>
</table>

<script>
  $(document).ready(function(){
    var i;
    for(i = 1; i < 3; i++){
      $('#result_'+i).keyup(function(){
        $('#condition_'+i).text($(this).val());
        console.log(i);
      })
    }
  })
</script>

When i console log the i variable,it prints 3 instead of the array numbers.
This one will help for the rest of code for my future work. Any kind of help will be appriciated. And this is the fiddle.
https://jsfiddle.net/1o7x5dwy/1/

Bakti Wijaya
  • 447
  • 1
  • 6
  • 21
  • `$('#result_'+i).keyup(function(e){` inside this function, you can use e.target.. e.target will give you the DOM node of the input this event was fired on.. – Ankur Mittal Jul 25 '19 at 04:30
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – JHEUNG Jul 25 '19 at 04:44

1 Answers1

1

Try this, https://jsfiddle.net/yzfomqpc/

$(document).ready(function(){
   var i;
   for(i = 1; i < 6; i++){
     $('#result_'+i).keyup(function(){        
          $(this).parent().next()[0].innerText = $(this).val();
     })
  }
})

You can even remove for loop, https://jsfiddle.net/yzfomqpc/1/

$(document).ready(function(){    
   $('[id^=result_]').keyup(function(){        
        $(this).parent().next()[0].innerText = $(this).val();
   })    
})
Murali Nepalli
  • 1,588
  • 8
  • 17