list of checkbox-ids in javascript [duplicate] - javascript

How to create a list of checkbox and retrieve selected checkbox value in javascript

Presuming a structure like:
<form name="test">
<input type="checkbox" name="colors" value="red"/>
<input type="checkbox" name="colors" value="orange"/>
<input type="checkbox" name="colors" value="yellow"/>
<input type="checkbox" name="colors" value="blue"/>
</form>
Then use something like this to retrieve the value:
var values = [];
var cbs = document.forms['test'].elements['colors'];
for(var i=0,cbLen=cbs.length;i<cbLen;i++){
if(cbs[i].checked){
values.push(cbs[i].value);
}
}
alert('You selected: ' + values.join(', '));

To create an element in DOM, use document.createElement. To retrieve selected checkbox value, use element.checked and/or element.value. To learn more about HTML DOM, start here.
You may want to consider using jQuery to ease all the DOM manipulation and traversing work.

More modern answer
document.querySelector("[name=test]").addEventListener("click",
e => {
let tgt = e.target;
if (tgt.name==="colors") {
let checked = [...e.currentTarget.querySelectorAll(`[name=${tgt.name}]:checked`)];
document.getElementById("res").innerHTML = checked.map(inp => inp.value).join(", ")
}
})
<form name="test">
<input type="checkbox" name="colors" value="red"/>
<input type="checkbox" name="colors" value="orange"/>
<input type="checkbox" name="colors" value="yellow"/>
<input type="checkbox" name="colors" value="blue"/>
</form>
<span id="res"></span>

Related

jQuery, collecting checkboxes and put selected ones to array, is that possible?

I want to collect checked checkboxes (values) with a classname and put them into an array. Just like that one:
var a = new Array();
$('.categoriesCb').each(function(i, item) {
if ($(item).prop('checked'))
{
a.push($(item).val());
}
alert(JSON.stringify(a));
});
my problem is its a bit big. Cant it be done with one-line?11
You can use .map() function along with .get(). You can also eliminate paramete item and use context this:
var a = $('.categoriesCb:checked').map(function(){
return $(this).val();
}).get();
Use jQuery.map()
$('.categoriesCb:checked').map(function() {
return this.value;
}).get();
another way is to use jQuery.makeArray() with .map():
var arr = jQuery.makeArray($(':checked').map(function(){ return this.value; }));
$('pre').html(JSON.stringify(arr));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />
<br>
<pre></pre>
Just a pure JS single liner. Note that node list to array conversion with the spread operator works fine in Firefox but with Chrome it's only possible with v51 on. Otherwise you will have to go with the good old Array.prototype.map.call(document.querySelectorAll("input[type=checkbox][checked]"), e => e.value) method.
var arr = [...document.querySelectorAll("input[type=checkbox][checked]")].map(e => e.value);
console.log(JSON.stringify(arr));
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />

Accessing the radio button value

Html Code: -
<input type="radio" name="radio" id="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio" value="2" onclick="validate()"> For Users</input>
</p>
And JavaScript Code : -
function validate()
{
var btn_value=document.getElementById("radio").value;
if(btn_value==true)
{
alert(btn_value);
}
}
Now, whenever I am trying to print the value of radio button. It is always printing value as 1.
So, Now I don't understand what exactly am I missing here...
Thanx in advance for your help.
Elements ID should be unique. I modified your HTML and JS part and check below
Try this
HTML
<p>
<input type="radio" name="radio" id="radio1" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio2" value="2" onclick="validate(this)"> For Users</input>
</p>
JavaScrpit
function validate(obj)
{
var btn_value=obj.value;
if(btn_value==true)
{
alert(btn_value);
}
}
first of all never use a DOMID twice in your html!
remove them.... only use dublicated names!
<input type="radio" name="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" value="2" onclick="validate()"> For Users</input>
</p>
with the js check every element with the name attribute!
function validate() {
var elements = document.getElementsByName("radio");
for(var n = 0; n < elements.length; n++) {
if(elements[n].checked === true) {
alert(elements[n].value);
}
}
}
if you use your validate method ONLY in the onclick you can pass the domelement in the validate methode like this:
<input type="radio" name="radio" value="1" onclick="validate(this)"> For Yourself</input> </p>
and your js:
function validate(domElement) {
if(domElement.checked === true) {
alert(elements[n].value);
}
}
try this
<input type="radio" name="radio" id="radio" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio" value="2" onclick="validate(this)"> For Users</input>
</p>​
function validate(ele)
{
alert(ele.value);
}​
IDs MUST be unique, it's a mistake to give it the same id.
You can give the IDs a running number (- radio1,radio2 etc) and loop through them to check which one was selected.

Pass all checkboxes values as an array in Javascript

I have the below checkboxes and I need to get them as an array values.
<input type="checkbox" id="contact_id" value="4" />
<input type="checkbox" id="contact_id" value="3" />
<input type="checkbox" id="contact_id" value="1" />
<input type="checkbox" id="contact_id" value="5" />
I need to pass them to one ajax request as array as below:
xmlHttp.open("POST","?action=contact&contact_id=" +contacts,true);
I am using this function to get the values but not able to pass them to the function as array, the passed like this 4,3,1,5. I need them to be passed like this
contact_id[]=4&contact_id[]=3&contact_id[]=1&contact_id[]=5
I have done this as follows
function getContacts(){
var contacts = document.myform.contact_id, ids = [];
for (var i = 0; i < contacts.length; i += 1){
if (contacts[i].checked)
ids.push(contacts[i].value);
}
return ids;
}
http://jsfiddle.net/xQezt/
Does this fiddle do what you want? The serialization is naive, but you could find a proper way to do that exact thing elsewhere or by using a framework like Zepto, jQuery or YUI.
First I made a way to "submit" the data. The output goes to the console, so open your firebug. Could go anywhere, though.
//submit event registration
submitButton.onclick = function () {
var contactArray = inputsToArray(contacts.children);
var data = serializeArray(contactArray, 'contact_id[]');
console.log(data);
}
Then I made your method "getContacts" more generic:
function inputsToArray (inputs) {
var arr = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
arr.push(inputs[i].value);
}
return arr;
}
Here is the naive serialization function. I do not expect this to work well in all cases, so you should do some research in where to get a good serialization algo from:
function serializeArray (array, name) {
var serialized = '';
for(var i = 0, j = array.length; i < j; i++) {
if(i>0) serialized += '&';
serialized += name + '=' + array[i];
}
return serialized;
}
I also slightly modified your HTML:
<div id="contacts">
<input type="checkbox" value="4" />
<input type="checkbox" value="3" />
<input type="checkbox" value="1" />
<input type="checkbox" value="5" />
</div>
<button id="submit">Submit</button>
Which let me query the DOM like this:
var d=document;
var submitButton = d.getElementById('submit');
var contacts = d.getElementById('contacts');
Your input's id are duplicate. so I recommend you to use name instead of id
For Example, Your HTML will look like this :
<form id='contactform'>
<input type="checkbox" name="contact[]" value="4" />
<input type="checkbox" name="contact[]" value="3" />
<input type="checkbox" name="contact[]" value="1" />
<input type="checkbox" name="contact[]" value="5" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Then if you want to get the value to querystring then use the JQuery Serialize
$('#contactform').serialize();
// this will take some thing like this, Example check the second and the fourth
// contact%5B%5D=3&contact%5B%5D=5
jsFiddle : http://jsfiddle.net/Eqb7f/
$(document).ready(function() {
$("#submit").click(function(){
var favorite = [];
$.each($("input[class='check']:checked"), function(){
favorite.push($(this).val());
});
document.getElementById('fav').value = favorite.join(", ");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cd-form-list">
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="A">
<label for="cd-checkbox-1">A for Apple</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="B">
<label for="cd-checkbox-2">B for Ball</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-3" class="check" value="C">
<label for="cd-checkbox-3">C for Cat</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-4" class="check" value="D">
<label for="cd-checkbox-4">D for Dog</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-5" class="check" value="E">
<label for="cd-checkbox-5">E for Ear</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-6" class="check" value="F">
<label for="cd-checkbox-6">F for Fish</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-7" class="check" value="G">
<label for="cd-checkbox-7">G for God</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-8" class="check" value="H">
<label for="cd-checkbox-8">H for Hen</label>
</div>
</div>
<div>
<input type="submit" value="Submit" id="submit">
</div>
<input name="services" id="fav">

How can I make a group of checkboxes mutually exclusive?

I have to make mutually exculsive checkboxes. I have come across numerous examples that do it giving example of one checkbox group.
One example is at http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html.
In my case, I have many checkbox groups on the same page, so I want it to work like this example.
An asp.net codebehind example is here, but I want to do it in client side code.
How can I do this in JavaScript?
i have decided to use the ajax mutually exclusive checkbox extender.
The solutions given so far are basically based on radio buttons.
This link really helped me..http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender
Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows
HTML
<div>
Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="checkbox">
Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="checkbox">
Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="checkbox">
</div>
<div>
Mango: <input id="chkRed" name="chkMango" type="checkbox" value="Mango" class="checkbox">
Orange: <input id="chkBlue" name="chkOrange" type="checkbox" value="Orange" class="checkbox">
Banana: <input id="chkGreen" name="chkBanana" type="checkbox" value="Banana" class="checkbox">
</div>
Jquery
$('div .checkbox').click(function () {
checkedState = $(this).attr('checked');
$(this).parent('div').children('.checkbox:checked').each(function () {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
And here is fiddle
Like I said in my comment, you should really use <radio> elements for this. Give them the same name and they work almost the same way:
<label><input type="radio" name="option" value="Option 1">Option 1</label>
<label><input type="radio" name="option" value="Option 2">Option 2</label>
The only significant difference is that, once one of them is selected, at least one of them has to be on (ie, you can't uncheck them again).
If you really feel the need to do it with check boxes, remind yourself that users with JavaScript disabled will be able to select all the options if they like. If you still feel the need to do it, then you'll need to give each checkbox group a unique class name. Then, handle the change event of each checkbox element and uncheck all the other elements matching the same class name as the clicked element.
I hope this one will work
HTML
A <input type="checkbox" class="alpha" value="A" /> |
B <input type="checkbox" class="alpha" value="B" /> |
C <input type="checkbox" class="alpha" value="C" />
<br />
1 <input type="checkbox" class="num" value="1" /> |
2 <input type="checkbox" class="num" value="2" /> |
3 <input type="checkbox" class="num" value="3" />
JavaScript
// include jQuery library
var enforeMutualExcludedCheckBox = function(group){
return function() {
var isChecked= $(this).prop("checked");
$(group).prop("checked", false);
$(this).prop("checked", isChecked);
}
};
$(".alpha").click(enforeMutualExcludedCheckBox(".alpha"));
$(".num").click(enforeMutualExcludedCheckBox(".num"));
well, radio button should be the one to be used in mutually excluded options, though I've encountered a scenario where the client preferred to have zero to one selected item, and the javaScript'ed checkbox works well.
Update
Looking at my answer, I realized it's redundant to refer to the css class twice. I updated my code to convert it into a jquery plugin, and created two solutions, depending on ones preference
Get all checkboxes whose check is mutually excluded
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this; // refers to selected checkboxes
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// more elegant, just invoke the plugin
$("[name=alpha]").mutuallyExcludedCheckBoxes();
$("[name=num]").mutuallyExcludedCheckBoxes();
HTML
A <input type="checkbox" name="alpha" value="A" /> |
B <input type="checkbox" name="alpha" value="B" /> |
C <input type="checkbox" name="alpha" value="C" />
<br />
1 <input type="checkbox" name="num" value="1" /> |
2 <input type="checkbox" name="num" value="2" /> |
3 <input type="checkbox" name="num" value="3" />
sample code
Group all mutually excluded checkboxes in a containing element
JavaScript
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this.find("input[type=checkbox]");
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// select the containing element, then trigger the plugin
// to set all checkboxes in the containing element mutually
// excluded
$(".alpha").mutuallyExcludedCheckBoxes();
$(".num").mutuallyExcludedCheckBoxes();
HTML
<div class="alpha">
A <input type="checkbox" value="A" /> |
B <input type="checkbox" value="B" /> |
C <input type="checkbox" value="C" />
</div>
<div class="num">
1 <input type="checkbox" value="1" /> |
2 <input type="checkbox" value="2" /> |
3 <input type="checkbox" value="3" />
</div>
sample code
Enjoy :-)
Try this:
HTML
<div>
Car: <input id="chkVehicleCar" name="chkVehicle" type="checkbox" value="Car" class="radiocheckbox">
Moto: <input id="chkVehicleMoto" name="chkVehicle" type="checkbox" value="Moto" class="radiocheckbox">
Byke: <input id="chkVehicleByke" name="chkVehicle" type="checkbox" value="Byke" class="radiocheckbox">
Feet: <input id="chkVehicleFeet" name="chkVehicle" type="checkbox" value="Feet">
</div>
<span>
Red: <input id="chkColorRed" name="chkColor" type="checkbox" value="Red" class="radiocheckbox">
Blue: <input id="chkColorBlue" name="chkColor" type="checkbox" value="Blue" class="radiocheckbox">
Green: <input id="chkColorGreen" name="chkColor" type="checkbox" value="Green" class="radiocheckbox">
Mango: <input id="chkFruitMango" name="chkFruit" type="checkbox" value="Mango" class="radiocheckbox">
Orange: <input id="chkFruitOrange" name="chkFruit" type="checkbox" value="Orange" class="radiocheckbox">
Banana: <input id="chkFruitBanana" name="chkFruit" type="checkbox" value="Banana" class="radiocheckbox">
</span>
​JavaScript/jQuery
$(':checkbox.radiocheckbox').click(function() {
this.checked
&& $(this).siblings('input[name="' + this.name + '"]:checked.' + this.className)
.prop('checked', false);
});​
Mutually exclusive checkboxes are grouped by container+name+classname.
You can use different groups in same container and also mix exclusive with non-exclusive checkbox with same name.
JavaScript code is highly optimized. You can see a working example.
No matter where the check box is located on your page, you just need to specify the group and here you go!
<input type='checkbox' data-group='orderState'> pending
<input type='checkbox' data-group='orderState'> solved
<input type='checkbox' data-group='orderState'> timed out
<input type='checkbox' data-group='sex'> male
<input type='checkbox' data-group='sex'> female
<input type='checkbox'> Isolated
<script>
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var state = $(this)[0].checked,
g = $(this).data('group');
$(this).siblings()
.each(function () {
$(this)[0].checked = g==$(this).data('group')&&state ? false : $(this)[0].checked;
});
});
})</script>
I guess this is what you want.
Consider the HTML below:
<form action="">
My favourite colors are:<br />
<br />
<input type="checkbox" value="red" name="color" /> Red<br />
<input type="checkbox" value="yellow" name="color" /> Yellow<br />
<input type="checkbox" value="blue" name="color" /> Blue<br />
<input type="checkbox" value="orange" name="color1" /> Orange<br />
<input type="checkbox" value="green" name="color1" /> Green<br />
<input type="checkbox" value="purple" name="color1" /> Purple
</form>
Note that there's two names for color groups: red, yellow, blue and orage, green, purple
And this JavaScript noted below will work generically to all checkbox on the page.
jQuery("input[type=checkbox]").unbind("click");
jQuery("input[type=checkbox]").each(function(index, value) {
var checkbox = jQuery(value);
checkbox.bind("click", function () {
var check = checkbox.attr("checked");
jQuery("input[name=" + checkbox.attr('name') + "]").prop("checked", false);
checkbox.attr("checked", check);
});
});
Take a look at this LIVE example

How to create list of checkboxes

How to create a list of checkbox and retrieve selected checkbox value in javascript
Presuming a structure like:
<form name="test">
<input type="checkbox" name="colors" value="red"/>
<input type="checkbox" name="colors" value="orange"/>
<input type="checkbox" name="colors" value="yellow"/>
<input type="checkbox" name="colors" value="blue"/>
</form>
Then use something like this to retrieve the value:
var values = [];
var cbs = document.forms['test'].elements['colors'];
for(var i=0,cbLen=cbs.length;i<cbLen;i++){
if(cbs[i].checked){
values.push(cbs[i].value);
}
}
alert('You selected: ' + values.join(', '));
To create an element in DOM, use document.createElement. To retrieve selected checkbox value, use element.checked and/or element.value. To learn more about HTML DOM, start here.
You may want to consider using jQuery to ease all the DOM manipulation and traversing work.
More modern answer
document.querySelector("[name=test]").addEventListener("click",
e => {
let tgt = e.target;
if (tgt.name==="colors") {
let checked = [...e.currentTarget.querySelectorAll(`[name=${tgt.name}]:checked`)];
document.getElementById("res").innerHTML = checked.map(inp => inp.value).join(", ")
}
})
<form name="test">
<input type="checkbox" name="colors" value="red"/>
<input type="checkbox" name="colors" value="orange"/>
<input type="checkbox" name="colors" value="yellow"/>
<input type="checkbox" name="colors" value="blue"/>
</form>
<span id="res"></span>

Categories

Resources