NinjaCode NinjaCode - 8 days ago 5
Javascript Question

Jquery change hidden input value in for loop

I try to change each hidden input value if checkbox is checked using jquery

I need to using for loop because html input field is generate by php loop from db too. so here is generated html code look like :

Html :

<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="" type="hidden">

<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="" type="hidden">

<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="" type="hidden">


Jquery :

var tot = <?php echo $tot; ?>;

jQuery(function($){
for (var i = 0; i< tot; i++ ){
var chk = '#gift' + i;

var val = '#gift-true' + i;
$(chk).change(function(e) {
for (var a = 0; a<= jml; a++ ){
$(val).val(($(this).is(':checked')) ? "yes" : "no");
}
console.log(e);
});
}
});


but this code didn't work.

P.S :

code to generate html input is look like this :

<?php
for ($i=0; $i<$total; $i++){
echo "<input type='checkbox' id='gift$i' name='exm$i' value='1'> <br>
<input type='hidden' id='gift-true$i' value=''></td> <br><br>";
}

Answer

You can do this by using next() function as all the inputs are next to the checkbox. please replace var tot = 3; with var tot = <?php echo $tot; ?>; and type="text" with type="hidden"

var tot = 3;

   jQuery(function($){
     for (var i = 0; i< tot; i++ ){
       $('#gift' + i).on('change', function(e) {
         $(this).next().val(($(this).is(':checked')) ? "yes" : "no");
       });
     }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="gift0" value="1" type="checkbox">
<input id="gift-true0" value="no" type="text">

<input id="gift1" value="1" type="checkbox">
<input id="gift-true1" value="no" type="text">

<input id="gift2" value="1" type="checkbox">
<input id="gift-true2" value="no" type="text">