I have a form with checkboxes. The javascript function allPosPlayersCheckboxes utilizes a "Check All" Checkbox that controls the others. The other functions (getPosAllFilterOptions & getPosPlayersFilterOptions) push the "name" properties into an array. This all is triggered when anything is changed on the form.
Suppose that all checkboxes are unchecked. If the user checks the "nonP_all" checkbox, it will automatically check the other checkboxes with class="nonP". Unfortunately, when the "name" properties are pushed into the array, it will not include any with class="nonP".
I"m unsure why they are not included in the array. Are the functions (getPosAllFilterOptions & getPosPlayersFilterOptions) not waiting for allPosPlayersCheckboxes to complete? Is there a way to have the secondary checkboxes included in the arrays? Thanks for any help!
<form id="formFilter">
<h2>Filter options</h2>
<div>
<input type="checkbox" id="nonP_all" class="Pos_all" name="nonP" checked="checked">
<label for="nonP">Position Players</label>
<input type="checkbox" id="C" class="nonP" checked="checked" name="C">
<label for="C">C</label>
<input type="checkbox" id="1B" class="nonP" checked="checked" name="1B">
<label for="1B">1B</label>
<input type="checkbox" id="2B" class="nonP" checked="checked" name="2B">
<label for="2B">2B</label>
<input type="checkbox" id="3B" class="nonP" checked="checked" name="3B">
<label for="3B">3B</label>
<input type="checkbox" id="SS" class="nonP" checked="checked" name="SS">
<label for="SS">SS</label>
<input type="checkbox" id="LF" class="nonP" checked="checked" name="LF">
<label for="LF">LF</label>
<input type="checkbox" id="CF" class="nonP" checked="checked" name="CF">
<label for="CF">CF</label>
<input type="checkbox" id="RF" class="nonP" checked="checked" name="RF">
<label for="RF">RF</label>
<input type="checkbox" id="DH" class="nonP" checked="checked" name="DH">
<label for="DH">DH</label>
</div>
function allPosPlayersCheckboxes(){
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
};
function getPosAllFilterOptions(){
var pos_all_opts = new Array();
$(".Pos_all:checked").each(function(){
pos_all_opts.push($(this).attr('name')); // places names into array
});
return pos_all_opts;
}
function getPosPlayersFilterOptions(){
var nonP_opts = new Array();
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
return nonP_opts;
}
var $formFilter = $("#formFilter");
$formFilter.change(function(){
allPosPlayersCheckboxes();
var pos_all_opts = getPosAllFilterOptions();
var nonP_opts = getPosPlayersFilterOptions();
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
The reason that you are having an issue is because the checking of the boxes event is being caught at the form change event handler, and the code that checks and unchecks all of the other boxes hasn't executed yet. As a result when you call your functions, the count for checked boxes is 0. This also happens when you uncheck one of the position checkboxes, eventually the pos_all_opts variable gets out of sync and is incorrect as well.
These click handlers don't need to be in a function. They are handlers that are hooked into the behavior of your checkboxes.
$("#nonP_all").click(function(){ // When it is clicked....
$('.nonP').prop('checked', this.checked); // Sets all to reflect "All"
});
$(".nonP").click(function(){ // When any are clicked....
if($(".nonP").length == $(".nonP:checked").length){ // If all are checked...
$("#nonP_all").prop("checked", true); // Sets "All" to "checked"
}else{
$("#nonP_all").prop("checked", false); // Sets "All" to "unchecked"
}
});
This is probably a little less than ideal, but it works. The code that was in the functions to build the arrays has been moved into the change handler for the form.
$("#formFilter").change(function(event){
var pos_all_opts = [];
var nonP_opts = [];
if(event.target === $("#nonP_all")[0] && event.target.checked) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else if(event.target === $("#nonP_all")[0] && !event.target.checked) {
pos_all_opts = [];
nonP_opts = [];
} else if(event.target !== $("#nonP_all")[0] && $(".nonP:checked").length === 9) {
pos_all_opts = 'nonP';
$(".nonP").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
} else {
pos_all_opts = [];
$(".nonP:checked").each(function(){
nonP_opts.push($(this).attr('name')); // places names into array
});
}
console.log("pos_all_opts = " + pos_all_opts);
console.log("nonP_opts = " + nonP_opts);
updateQuery(pos_all_opts, nonP_opts);
});
updateQuery();
Fiddle for reference
Related
I am trying to show div if one of the two checkboxes is checked. I found it in some article but with the same name, I am using a different name for each checkbox to store it into mysql. My current javascript code is
document.addEventListener('change', function(jj) {
function jj() {
if ((document.getElementById('jj1_ikk').checked) || (document.getElementById('jj2_ikk').checked)) {
document.getElementById('jsa').style.display="block";
} else {
document.getElementById('jsa').style.display="none";
}
}
})
the input fields are
<input type="checkbox" id="jj1_ikk" name="jj1_ikk" /><label for="jj1_ikk">A</label>
<input type="checkbox" id="jj2_ikk" name="jj2_ikk" /><label for="jj2_ikk">B</label>
where jj1_ikk and jj2_ikk are the checkboxes id, and jsa is the div that I want to do show/hide.
I hope my description is clear, thank you.
You can put two check box in span and check changes onclick span like this
HTML
<span onclick="CheckChanges()">
<input type="checkbox" id="jj1_ikk" name="jj1_ikk" /><label for="jj1_ikk">A</label>
<input type="checkbox" id="jj2_ikk" name="jj2_ikk" /><label for="jj2_ikk">B</label>
</span>
<div id="jsa">This is the element that will be shown if both checkboxes aren't checked</div>
JavaScript
var aCheckBox = document.getElementById("jj1_ikk")
var bCheckBox = document.getElementById("jj2_ikk")
function CheckChanges() {
if (aCheckBox.checked == true || bCheckBox.checked == true) {
document.getElementById("jsa").style.display = "block"
} else {
document.getElementById("jsa").style.display = "none"
}
}
You did a mistake when adding the handler for the change event defining two nested functions. Plus I added the event handler only once the document was loaded. You can test the code in this snippet:
//when the document has been loaded, adds the event handlers to the checkboxes
document.addEventListener("DOMContentLoaded", () => {
document.addEventListener('change', () => addHandlers());
});
/**
* Adds handler for the change event on both checkboxes
*/
function addHandlers(){
let jj1 = document.getElementById('jj1_ikk');
let jj2 = document.getElementById('jj2_ikk');
jj1.addEventListener('change', updateMsgVisibility);
jj2.addEventListener('change', updateMsgVisibility);
}
/**
* Show/Hide #jsa based on checkboxes status
*/
function updateMsgVisibility(){
let jj1 = document.getElementById('jj1_ikk');
let jj2 = document.getElementById('jj2_ikk');
if ( (jj1 && (jj1.checked)) || (jj2 && (jj2.checked)) ) {
document.getElementById('jsa').style.display="block";
} else {
document.getElementById('jsa').style.display="none";
}
}
<input type="checkbox" id="jj1_ikk" name="jj1_ikk" /><label for="jj1_ikk">A</label>
<input type="checkbox" id="jj2_ikk" name="jj2_ikk" /><label for="jj2_ikk">B</label>
<div id="jsa" style="display:none;">This is the element that will be shown if both checkboxes aren't checked</div>
I have 4 checkboxes. I add values of them to an array on check. It looks like this.
Here are the four checkboxes I have.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
Once I check all four of them, the array becomes,
["degree", "pgd", "hnd", "advdip"]
When I uncheck a checkbox, I need to remove the value of it from the array according to its correct index number. I used splice() but it always removes the first index which is degree. I need to remove the value from the array according to its index number no matter which checkbox I unselect. Hope someone helps. Below is the code. Thanks in advance!
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = $(this).index();
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
You used the wrong way to find index in your code. If you used element index, it will avoid real index in your array and gives the wrong output. Check below code, it may be work for you requirement.
<input type="checkbox" value="degree">
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
<script src="https://code.jquery.com/jquery-3.5.0.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script>
function getLevels() {
// get reference to container div of checkboxes
var con = document.getElementById('course-levels');
// get reference to input elements in course-levels container
var inp = document.getElementsByTagName('input');
// create array to hold checkbox values
var selectedValues = [];
// collect each input value on click
for (var i = 0; i < inp.length; i++) {
// if input is checkbox
if (inp[i].type === 'checkbox') {
// on each checkbox click
inp[i].onclick = function() {
if ($(this).prop("checked") == true) {
selectedValues.push(this.value);
console.log(selectedValues);
}
else if ($(this).prop("checked") == false) {
// get index number
var index = selectedValues.indexOf(this.value);
selectedValues.splice(index, 1);
console.log(selectedValues);
}
}
}
}
}
getLevels();
</script>
Add change handler to the inputs and use jQuery map to get the values of the checked inputs.
var levels
$('#checkArray input').on('change', function () {
levels = $('#checkArray input:checked').map(function () {
return this.value
}).get()
console.log(levels)
}).eq(0).change()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
my approach was to add an event handler that reads all checked values when any of those inputs is clicked and empty the array before loging the response. no need to add any dependencies with this one
Hope this is what you are looking for
function getLevels() {
let checkboxContainer = document.getElementById("checkboxContainer");
let inputs = checkboxContainer.querySelectorAll("input");
let checked = [];
inputs.forEach( (input) => {
checked = [];
input.addEventListener( 'click', () => {
checked = [];
inputs.forEach( (e) => {
e.checked ? checked.push(e.value) : null;
})
console.log(checked);
});
});
}
getLevels();
<div id="checkboxContainer">
<input type="checkbox" value="degree" >
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</div>
I don't know if this is what you need, to show an array of the selected values, if you want you can call the function that calculates on the check.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<fieldset id="checkArray">
<input type="checkbox" value="degree" checked>
<input type="checkbox" value="pgd">
<input type="checkbox" value="hnd">
<input type="checkbox" value="advdip">
</fieldset>
<button onclick="getLevels()">getLevels</button>
<script>
function getLevels() {
var levels = [];
$.each($("input:checked"), function() {
levels.push(($(this).val()));
});
console.log(levels);
}
getLevels();
</script>
I want to pass values of a checkbox array to 3 inputs, if I check in a value that sends to the first input, then the second checkbox to the second input and then the third checkbox to the third input, then if I choose another value of the checkbox that does not overwrite without first uncheck the checked checkbox value
It could be put an addeventlistener
<form action="#" method="post" class="demoForm" id="demoForm">
<fieldset>
<label><input type="checkbox" name="sports[]" value="cycling" /> cycling</label>
<label><input type="checkbox" name="sports[]" value="running" /> running</label>
<label><input type="checkbox" name="sports[]" value="visit gym" /> visit gym</label>
<label><input type="checkbox" name="sports[]" value="swimming" /> swimming</label>
<label><input type="checkbox" name="sports[]" value="team sports" /> team sport(s)</label>
<label><input type="checkbox" name="sports[]" value="other" /> other</label>
</fieldset>
</form>
<script type="text/javascript">
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
for (var i=0, len=sports.length; i<len; i++) {
sports[i].onclick = doSomething;
}
function doSomething() {
y=document.getElementById("chk1");
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
if ( this.checked) {
y.value=this.value;
} else {
y.value="";
}
}
</script>
<input type="text" name="chk1" id="chk1">
<input type="text" name="chk2" id="chk2">
<input type="text" name="chk3" id="chk3">
I hope to see the solution.
I created a set of conditional code which will work for you as i understood your question, and it's explained with comments along the way.
var sports = document.forms['demoForm'].elements[ 'sports[]' ];
for (var i=0, len=sports.length; i<len; i++) {
sports[i].onclick = doSomething;
}
function doSomething() {
x = document.getElementById("chk1");
y = document.getElementById("chk2");
z = document.getElementById("chk3");
/*if a checkbox is checked and the first input is empty, then put the checkbox
value in the first input */
if ( this.checked && x.value =="") {
x.value = this.value;
/*now if the first input is filled already, check if the second is empty and put
the checkbox value into the second*/
} else if (this.checked && y.value =="") {
y.value = this.value ;
/*now if the second input is filled already, check if the third is empty and
put the checkbox value into the third*/
} else if (this.checked && z.value ==""){
z.value = this.value ;
/* if a checkbox is checked and all 3 inputs are filled already so it gets to
this condition, then alert the user and make the checkbox shouldn't be checked*/
}else if (this.checked) {
alert("First un-check another box to check this box");
this.checked = false;
/* if the user unchecked a checkbox, then check in which input the value of this
checkbox was displayed and empty this input */
} else if (!this.checked){
switch(this.value){
case y.value:
y.value="";
break;
case x.value:
x.value="";
break;
case z.value:
z.value="";
}
}
}
I've tried almost all the methods mentioned here and in other websites but still I'm stuck so that's why I'm asking it here.
I've created a form (with out <form></form> tags) in this form I'm creating 4 radios buttons using a while loop data is being pulled from a database.
To send data I'm using a JavaScript(Ajax) which is bound to a button click event.
Now I want to keep the submit button disabled until all the filed's are filled the last filed's are the radio buttons I'm tried to use many other ways to do this but nothing happened so any way below is code I'm using.
function checkUrole() {
var roles = document.getElementById("userRoles"),
btn = document.getElementById("submit"),
len = roles.length,
sel = null;
for(var i=0; i < len; i++){
if (roles.checked){
sel = roles[i].value;
}
}
if (sel === null){
document.getElementById("msgID").innerHTML = "9";
btn.disabled = true;
}else{
btn.disabled = false;
}
}
And this is my HTML
<label for="userRoles">User Role:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" id="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" onmousedown="checkUrole()"><?php echo $row["userRole"]; }?>
<label id="msgID" hidden></label>
<div id="msg"></div>
Basically the HTML will create something like this,
<input type="radio" id="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
<input type="radio" id="userRoles" name="userRoles" value="2" onmousedown="checkUrole()">Manager
<input type="radio" id="userRoles" name="userRoles" value="3" onmousedown="checkUrole()">Team Leader
<input type="radio" id="userRoles" name="userRoles" value="4" onmousedown="checkUrole()">User
I don't like write a code like this,
if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}
above I think makes the program a bit less dynamic 'cos if a new user role is added I've add a new IF to the loop.
So is there any way I solve this and I like to use JavaScript if can.
UPDATE: Thanks to #zer00ne I solved this problem and below is the finale working code hope this helps any one in the future as well.
My HTML:
<script language="JavaScript" type="text/javascript" src="../jScripts/userCreatFunctions.js">
<div id="userRoles">
<input type="radio" name="userRoles" value="1" checked>Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
My JaveScript:
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man.
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
Use the $(document).ready(function () {}) other wise the script get loaded before the DOM which leads to a NULL value making the script none functional.
Firstly, you don't need the id's on every input element. You can get an array of the button element by name using getElementsByName, here is an example of how you would do "something" based on one of those being checked:
JS (Using ES6)
const getRadioValue = (name) => {
const radios = document.getElementsByName(name);
let val;
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
val = radios[i].value;
}
});
return val;
}
document.getElementById('form').addEventListener('change', (e) => {
getRadioValue('userRoles'); // value of checked radio button.
});
HTML
<div id="form">
<input type="radio" name="userRoles" value="1">Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
JsFiddle Example
UPDATE - improved
A more efficient method would be using the Array.prototype.find() method, this is better because:
The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.
In other words, it doesn't need to iterate the entire Array, once we find what we want it returns.
Note: Use the below snippets within the change event mentioned above to retrieve the checked value.
JS (Using ES6)
const getCheckedRadioValue = (name) => {
const radios = document.getElementsByName(name);
try {
// calling .value without a "checked" property will throw an exception.
return Array.from(radios).find((r, i) => radios[i].checked).value
} catch(e) { }
}
getCheckedRadioValue('userRoles');
JsFiddle Example
JS (Without ES6)
function getCheckedRadioValue(name) {
var radios = document.getElementsByName(name);
var val;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
return val; // return value of checked radio or undefined if none checked
}
getCheckedRadioValue('userRoles');
JsFiddle Example
References
Array.prototype.forEach()
Array.from()
Array.prototype.find()
Not exactly sure what you are trying to do, so here is what I'm guessing:
Need to determine the value of a checked radio input
Need to enable a submit button that's determined by a checked radio
Need to effectively call upon other functions, run additional interactions, etc. depending on what was specifically checked.
Details are commented in Snippet
SNIPPET
// Reference #roles
var form = document.getElementById('roles');
/* Register the change element to #roles
|| When clicked...
*/
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Find the textNode next to target
var label = target.nextSibling;
// Reference the #display
var display = document.getElementById('display');
// Display the <label>s text and radio value
display.value = label.textContent + ' - Rank: ' + target.value;
// Reference the submit button
var btn = document.querySelector('[type=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
function roleDist(rank) {
switch (rank) {
case '4':
alert('Rank 4 - Limited Access');
// Take user to landing page
break;
case '3':
alert('Rank 3 - Basic Access');
// Take user to dashboard
break;
case '2':
alert('Rank 2 - Advanced Access');
// Take user to database
break;
case '1':
alert('Rank 1 - Full Access');
// Take user to admin panel
break;
}
}
input,
output,
[type=submit] {
font: inherit;
cursor: pointer;
}
[type=submit] {
float: right;
}
<form id='roles'>
<input type="radio" name="role" value="1">Admin
<input type="radio" name="role" value="2">Manager
<input type="radio" name="role" value="3">Team Leader
<input type="radio" name="role" value="4">User
</form>
<br/>
<label for='display'>Role: </label>
<!--
Since #display and submit button are outside of
the <form>, using the form attribute and the
<form>'s #id as the value establishes an
association between them and <form>
-->
<output id='display' form='roles'></output>
<br/>
<input type='submit' form='roles' disabled>
There is very basic mistake in your markup you should not use elements with same id's in
You can use class instead of id (give class to radioboxes)
document.getElementsByClassName("userRoles")
<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
Rest of your code seems ok
I want to do JavaScript validation for Checkbox
If Value from Checkbox is not selected, it should get alert "Please Select Languages You Know"
But if user select 2 Languages from list of checkbox. I need that 2 languages should get alert using JavaScript.
I know to do with single checkbox, but not getting how to do using array.
Here is my Code...
<script type="text/javascript">
function myFunction(form){
var i,
chks = document.getElementsByName('lang[]');
for (i = 0; i < chks.length; i++){
if (chks[i].checked){
//Here how i should alert selected values
return true;
}else{
alert('No item selected');
return false;
}
}
}
</script>
<form name="registration" id="registration_form_id" action="" method="post" onsubmit="return myFunction(this)">
<div id="languageId"><label>Language : </label>
<input type="checkbox" name="lang[]" value="english" >English</input>
<input type="checkbox" name="lang[]" value="marathi">Marathi</input>
<input type="checkbox" name="lang[]" value="hindi">Hindi</input>
</div>
<div id="submit1"><button type="submit">Submit</button></div><br/>
</form>
Thank You,
Rahul
If you want to get the list of selected checkbox values.. you can use this..
$('#someButton').click(function() {
var values= [];
$('#MyDiv input:checked').each(function() {
values.push(this.val);
});
// now values contains all of the values of checked checkboxes
// do something with it
});
If you only need one selected value, it's easier to use a radio input type. With it, you can find the selected value using a querySelector (see MDN). For multiple languages, you can also use querySelectorAll, convert its results to an Array and use Array.map (see MDN) to map the results into an Array of the values of the checked checkboxes.
Here's your snippet rewritten for both cases (without a form):
(function (d, w, undefined) {
d.querySelector('#languageId button').addEventListener('click', doSubmit);
d.querySelector('#multiLanguageId button').addEventListener('click', doSubmitMulti);
var languageSelectorContainer = d.querySelector('#languageId');
var multiLanguageSelectorContainer = d.querySelector('#multiLanguageId');
function doSubmit() {
var languageChecked = languageSelectorContainer
.querySelector('[type=radio]:checked');
d.querySelector('#result').innerHTML =
'your selected language: <b>'+
(languageChecked
? languageChecked.value
: 'not yet selected') +
'</b>';
}
function doSubmitMulti() {
var languagesChecked = [].slice.call(
multiLanguageSelectorContainer
.querySelectorAll('[type=checkbox]:checked') )
.map(function (v){
return v.value;
});
d.querySelector('#result').innerHTML =
'you selected these language(s): <b>'+
(languagesChecked.length
? languagesChecked.join(', ')
: 'none yet selected') +
'</b>';
}
}(document, window))
<div id="languageId">Pick your language:
<input type="radio" name="lang[]" value="english">English
<input type="radio" name="lang[]" value="marathi">Marathi
<input type="radio" name="lang[]" value="hindi">Hindi
<button>Submit</button>
</div>
<div id="multiLanguageId">Pick the languages you know:
<input type="checkbox" name="mlang[]" value="english">English
<input type="checkbox" name="mlang[]" value="marathi">Marathi
<input type="checkbox" name="mlang[]" value="hindi">Hindi
<button>Submit</button>
</div>
<div id="result"></div>