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/

2
  • $('#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.. Commented Jul 25, 2019 at 4:30
  • Possible duplicate of JavaScript closure inside loops – simple practical example Commented Jul 25, 2019 at 4:44

1 Answer 1

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();
   })    
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.