javascript - Add checkbox value to another hidden input field if first hidden field has content -


i have group of 4 checkboxes.

when 2 have been checked have values copied 2 hidden input fields.

the first checked checkbox value goes first input id="checkedbox1"

how second checked checkbox value go second hidden input field id="checkedbox2"

i have used javascript function below place values each input individual checkboxes can't figure out how iterate through list of 4 checkboxes , place 2 checked ones each separate input field.

checkboxes:

<input type="checkbox" value="test1" id="a" name="one"><label>test11</label> <input type="checkbox" value="test2" id="b" name="one"><label>test12</label> <input type="checkbox" value="test3" id="c" name="one"><label>test13</label> <input type="checkbox" value="test4" id="d" name="one"><label>test14</label>    <input type="hidden" value="" id="checkedbox1">   <input type="hidden" value="" id="checkedbox2">  <script> function populate() {   var checkboxes = document.getelementsbyname('one');   var ip1 = document.getelementbyid('checkedbox1');   var ip2 = document.getelementbyid('checkedbox2');    // clear current values   ip1.value = ip2.value = '';    var first = false;   var second = false;    // loop on checkboxes,stop when found 2 checked   (var i=0,ilen=checkboxes.length; i<ilen || !(first && second); i++) {    if (checkboxes[i].checked) {    if (!first) {     ip1.value = checkboxes[i].value;     first = true;    } else if (!second) {     ip2.value = checkboxes[i].value;     second = true;   }   }   }   }   $('input[type="checkbox"]').on('change', function() {  populate();  }).change();  </script> 

you try plain js, though use form property access rather getelementsbyname or getelementbyid:

function populate() {   var checkboxes = document.getelementsbyname('one');   var ip1 = document.getelementbyid('checkedbox1');   var ip2 = document.getelementbyid('checkedbox2');    // clear current values   ip1.value = ip2.value = '';    var first = false;   var second = false;    // loop on checkboxes,stop when found 2 checked   (var i=0,ilen=checkboxes.length; i<ilen || !(first && second); i++) {      if (checkboxes[i].checked) {        if (!first) {         ip1.value = checkboxes[i].value;         first = true;        } else if (!second) {         ip2.value = checkboxes[i].value;         second = true;       }     }   } } 

edit

thanks mal, added line clear values of hidden inputs each time.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -