0

I am working on a plugin for MyBB, and there I have to collect values of all checked "checkboxes" every checkbox has diffrent name/ID & unfortunatly these checkboxes are not placed under any form tag so how can I do this ??? Look at code below this code works fine if I place form tag at first row but it doesn't return anything if I place form tag below all checkbox (actually this is exactly how I have to handle checkboxes in MyBB) Thanks,

<input type="checkbox" name="chb1" value="html" />HTML<br/>
<input type="checkbox" name="chb2" value="css" />CSS<br/>
<input type="checkbox" name="chb3" value="javascript" />JavaScript<br/>
<input type="checkbox" name="chb4" value="php" />php<br/>
<input type="checkbox" name="chb5" value="python" />Python<br/>
<input type="checkbox" name="chb6" value="net" />Net<br/>

<form action="script.php" method="post">
  <input type="button" value="Click" id="btntest" />
</form>

<script type="text/javascript"><!--
function getSelectedChbox(frm) {
  var selchbox = [];        
  var inpfields = frm.getElementsByTagName('input');
  var nr_inpfields = inpfields.length;
   for(var i=0; i<nr_inpfields; i++) {
    if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true)    selchbox.push(inpfields[i].value);
  }
  return selchbox;
}


document.getElementById('btntest').onclick = function(){
  var selchb = getSelectedChbox(this.form);   
  alert(selchb);
}
//-->

</script>
2
  • It would be simplest to either select by type (using jQuery) or add a class to all the checkboxes and then use frm.getElementsByClassName('<class name>'); Commented Jul 15, 2014 at 18:50
  • 1) Why are you hiding your JavaScript with <!-- //-->? 2) If you're not using a form tag, get rid of this.form in your click event. Commented Jul 15, 2014 at 18:50

1 Answer 1

2

>>>Test the Fiddle<<<

Well... with pure JavaScript:

function getCheckboxesValues(){
    return [].slice.apply(document.querySelectorAll("input[type=checkbox]"))
           .filter(function(c){ return c.checked; })
           .map(function(c){ return c.value; });
}

document.getElementById("btntest").addEventListener("click", function(){
    console.log(getCheckboxesValues());
});
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.