Last active
December 17, 2015 00:19
-
-
Save achudars/5520391 to your computer and use it in GitHub Desktop.
Get the value of the selected /checked check-boxes in a form using JavaScript and HTML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Check the web site programming language you know: | |
<form action="script.php" method="post"> | |
<input type="checkbox" name="chb[]" value="html" />HTML<br/> | |
<input type="checkbox" name="chb[]" value="css" />CSS<br/> | |
<input type="checkbox" name="chb[]" value="javascript" />JavaScript<br/> | |
<input type="checkbox" name="chb[]" value="php" />php<br/> | |
<input type="checkbox" name="chb[]" value="python" />Python<br/> | |
<input type="checkbox" name="chb[]" value="net" />Net<br/> | |
<input type="button" value="Click" id="btntest" /> | |
</form> | |
<script type="text/javascript"><!-- | |
// Returns an array with values of the selected (checked) checkboxes in "frm" | |
function getSelectedChbox(frm) { | |
// JavaScript & jQuery Course - http://coursesweb.net/javascript/ | |
var selchbox = []; // array that will store the value of selected checkboxes | |
// gets all the input tags in frm, and their number | |
var inpfields = frm.getElementsByTagName('input'); | |
var nr_inpfields = inpfields.length; | |
// traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox | |
for(var i=0; i<nr_inpfields; i++) { | |
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value); | |
} | |
return selchbox; | |
} | |
/* Test this function */ | |
// When click on #btntest, alert the selected values | |
document.getElementById('btntest').onclick = function(){ | |
var selchb = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox() | |
alert(selchb); | |
} | |
//--> | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment