Get value and text of selected checkboxes - javascript

I am trying to get an array of selected checkboxes values and text on button click
<input type="checkbox" name="checkbox[]" value="1" /><label>text1</label>
<input type="checkbox" name="checkbox[]" value="2" /><label>text2</label>
<input type="checkbox" name="checkbox[]" value="3" /><label>text3</label>
<input type="checkbox" name="checkbox[]" value="4" /><label>text4</label>
I'm getting values of the checkboxes but how to get text also in array
var checkboxes = document.getElementsByName('checkbox[]');
var vals = 0;
for (var i=0, n=checkboxes.length;i<n;i++) {
if (checkboxes[i].checked) {
vals += ","+checkboxes[i].value;
}
}
Thank you!

You can use map() to create an array of the values you require:
var labelValues = $(':checkbox:checked').map(function() {
return [ $(this).next('label').text(), this.value ];
}).get();
However given your desired output it would make more sense to create an object with the labels as the properties, something like this:
var obj = {};
$(':checkbox:checked').each(function() {
obj[$(this).next('label').text()] = this.value;
});
-- 2021 Update --
You can now simplify the map() call using an ES6 arrow function. In addition you could combine the checkbox value and label text in to an array of objects, like this:
$(':checkbox').on('change', () => {
let labelValues = $(':checkbox:checked').map((i, el) => ({
value: el.value,
text: el.nextElementSibling.textContent
})).get();
console.log(labelValues);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox[]" value="1" /><label>text1</label>
<input type="checkbox" name="checkbox[]" value="2" /><label>text2</label>
<input type="checkbox" name="checkbox[]" value="3" /><label>text3</label>
<input type="checkbox" name="checkbox[]" value="4" /><label>text4</label>

#Rory's answers is good to return both value and text into a single array. But as the OP is asking to return value and text into separate arrays, I would propose the following way to do that.
All you have to do is to use 2 arrays to get separate values from text.
Working JSFiddle here.
Run the below snippet to see the output in the console.
This example will return:
Selected checkbox Values in an array
Selected checkbox texts in an array
Selected checkbox in an array (In case if you want it)
var selectedCheckBoxValue = [];
var selectedCheckBoxText = [];
var selectedCheckBox = $(':checkbox:checked').map(function(i) {
selectedCheckBoxValue[i] = this.value;
selectedCheckBoxText[i] = $(this).next('label').text();
return this;
}).get();
//Selected Checkboxes Value in a seperate Array
console.log(selectedCheckBoxValue);
//Selected Checkboxes Text in a seperate Array
console.log(selectedCheckBoxText);
//Selected Checkboxes element in a seperate Array
console.log(selectedCheckBox);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" name="checkbox[]" value="1" checked="true" />
<label>text1</label>
<input type="checkbox" name="checkbox[]" value="2" checked="true" />
<label>text2</label>
<input type="checkbox" name="checkbox[]" value="3" />
<label>text3</label>
<input type="checkbox" name="checkbox[]" value="4" checked="true" />
<label>text4</label>

Related

How to check all checkbox when check on one checkbox and click on a button and get the values?

for single id i did like this but how to get all id on click of button when check the universal checkbox for all the columns
My Html File:-
<td><input type="checkbox" name="option" value="{{item.customerid}} " required ></td>
<input type="button" value="Transfer" (click)="getclickedevent($event)">
My Javascript file:-
getclickedevent(event) {
let id = $("input:checkbox[name=option]:checked").val();
console.log("The Required checkbox checked is "+ id)
}
make all the id's children of one master id
then use this
var div = // getElementById, etc
var children = div.childNodes;
var elements = [];
for (var i=0; i<div.childNodes.length; i++) {
var child = div.childNodes[i];
if (child.nodeType == 1) {
elements.push(child)
}
}
I hope you don't mind but I took the approach of refactoring your code.
Here is the HTML:
<td>
<input type="checkbox" name="option" value="{{item.customerid}}" required >
</td>
<input type="button" value="Transfer">
<div id='options'>
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
<br><input name='options' type="checkbox">
</div>
And here is the jQuery. I used jQuery because you missed native javascript and jQuery in your code:
$('input[type="button"][value="Transfer"]').click( function() {
let id = $("input:checkbox[name=option]").is(':checked');
$('input[name="options"]').each(function() {
this.checked = id;
});
});
You can see it all working here.
You can get all checked checkboxes values inside button click event handler using jquery .map() method like:
var ids = $("input:checkbox[name=option]:checked").map(function(){
return $(this).val();
}).get();
console.log(ids) //==> ['xxx', 'xxx', 'xxx', ...]
This will give a basic array containing all checked checkboxes values.
DEMO:
$("#checkAll").click(function() {
$("input:checkbox[name=option]").prop('checked', this.checked);
var ids = $("input:checkbox[name=option]:checked").map(function() {
return $(this).val();
}).get();
console.log(ids)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkAll">Check All
<hr />
<input type="checkbox" name="option" value="1">Item 1
<input type="checkbox" name="option" value="2">Item 2
<input type="checkbox" name="option" value="3">Item3
This should work for you. ↓↓
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<input type="checkbox" onclick="$('input[name*=\'customer_store\']').prop('checked', this.checked);"/> Select / Deselect<br>
<input type="checkbox" name="customer_store[]" value="xyz"/>xyz<br>
<input type="checkbox" name="customer_store[]" value="abc"/>abc<br>
Add ID to your button inputs and call on them as selectors for .click().
Add a function to get the click on the select all button and set all inputs to checked used an added class of option for to select the input elements that are check boxes.
Define an empty array to hold your values. Run your checked values through .each() loop and assign them to the array.
Those values will now live in the options array.
$(document).ready(function() {
$('#selectall').click(function(){
$('.option').prop("checked", true);
});
$('#transfer').click(function() {
var options = [];
$.each($("input[type='checkbox']:checked"), function() {
options .push($(this).val());
});
console.log(options);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input class="option" type="checkbox" name="option" value="{{item.customerid}}">
<input type="button" id="transfer" value="Transfer">
<input type="button" id="selectall" value="Select All">

Check seleted radio with value

Is it possible to count all selected radio to a certain value?
I have done this:
if($('.giornal:checked').val() == 'option1'.length == 1) {
// something
}
You can get all radio buttons checked as you shared in your question then filter array matching specific value(here "1") and get length
var res = $("input[type=radio]:checked").filter(function(){
return "1"==$(this).val()
})
console.log(res.length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" checked value="1"/>
<input type="radio" checked value="1"/>
<input type="radio" checked value="3"/>
<input type="radio" value="4"/>

Creating an Associative Array using JQuery

I am trying to create an associative array using JQuery. I would like it to be filled with the values of the checkboxes a user has selected from the UI.
I was creating the array like this at first:
$contentArray = [];
$('.content-filter :checked').each(function(){
$contentArray.push(this.value);
})
but the problem with this is that when I pass it to a php script via Ajax it was making it very difficult to get values from it. I'd rather be able to get the values from the array based on the key associated with it.
So I decided to modify my code to this:
$contentArray = new Array(); //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter :checked').each(function(){
$contentArray[this.value] = this.value;
})
however now when I perform console.log I am being told the contents of my array contains nothing.
Can anyone advise me on how to fix this issue and show me where I am going wrong?
Your filter is wrong - you need to remove the space before :checked, otherwise it will look for an element inside the checkbox which is checked, which obviously doesn't exist:
$contentArray = new Array(); //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter:checked').each(function(){
$contentArray[this.value] = this.value;
})
console.log($contentArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="content-filter" value="1" />
<input type="checkbox" class="content-filter" value="2" checked="checked" />
<input type="checkbox" class="content-filter" value="3" checked="checked" />
<input type="checkbox" class="content-filter" value="4" />
<input type="checkbox" class="content-filter" value="5" />
However, as mentioned, this just creates a fragmented array. If you want truly associative keys, you should create an object (tho I don't see this being easier to process in php):
$contentObject = {}; //Hold checked "content" filters
//Content Filter - cycle through each filter and add value of checked ones to array
$('.content-filter:checked').each(function(){
$contentObject[this.value] = this.value;
})
console.log($contentObject);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" class="content-filter" value="1" />
<input type="checkbox" class="content-filter" value="2" checked="checked" />
<input type="checkbox" class="content-filter" value="3" checked="checked" />
<input type="checkbox" class="content-filter" value="4" />
<input type="checkbox" class="content-filter" value="5" />

jquery - twitter bootstrap - get value of check-box when cheked

I have a div with 3 checkboxes inside div. I want to get all of them to string with jQuery.
Im using this theme http://almsaeedstudio.com/preview/
the checkbox in forms --> general elements.
its changes the HTML of checkbook for the design,
div:
<div id="some_id">
<input type="checkbox" value="1">
<input type="checkbox" value="2">
<input type="checkbox" value="3">
</div>
Jquery:
$("#some_div input[type='checkbox']").on('ifChecked', function(event){
arr='';
$('div[aria-checked="true"]').find("input").each(function(){
arr=arr+","+$(this).val();
});
console.log(arr);
});
The script works, but I have 2 problems:
It doesn't get the value of check-box that just been checked. For example:
if I check 1, arr will be empty.
if I check 1 and 2, arr will be ",1".
if I check 1 2 3, arr will be ",1,2".
How could I run this script when "unchecked"?
I tried:
$("#some_div input[type='checkbox']").on('click', function(event){
It doesn't work on bootstarp checkboxes. This is only a issue in bootstrap, in regular html there is no problem to get values with "click".
thanks.
First: Change - -> =
<input type="checkbox" value="1">
Second: Change name inside the input field
<input type="checkbox" value="1" name="checkgroup">
<input type="checkbox" value="2" name="checkgroup">
<input type="checkbox" value-"3" name="checkgroup">
Third: you can give it some ID for easy access:
<input type="checkbox" id="checkbox1" value="1" name="checkgroup">
Forth: Use jquery to do with it as you will:
$("#checkbox1").click('click', function(){.. /*do something*/ .. });
when dealing with checkboxes, it might be better to use the onChange. Here is a demo
try something like that:
<div id="some_id">
<input type="checkbox" value="1" name="checkgroup" />
<input type="checkbox" value="2" name="checkgroup" />
<input type="checkbox" value="3" name="checkgroup" />
</div>
JS:
$(document).ready(function () {
$('input[type="checkbox"]', '#some_id').on('change', function () {
var arr = '';
$('input[type="checkbox"]:checked', '#some_id').each(function (i, ele) {
if (arr.length > 0) {
arr += ', ';
}
arr += $(ele).val();
});
console.log(arr);
});
});

How to change input type dynamically using jquery or javascript

Below is the my html code:
<input type="checkbox" id="multiOptions" />IsForMultioptions
<input type="radio" value="1" name="option">option1
<input type="radio" value="2" name="option">option2
If I select checkbox i.e. multiOptions then all radio buttons should be convert into checkboxes.
and If I uncheck the checkbox i.e. multiOptions then all checkboxes should convert in radio buttons.
thanks in advance.
You'll need to actually remove and recreate the elements, because IE doesn't let you change the type of an input after it's created.
jQuery makes this fairly easy with replaceWith:
$("selector for the input to change").replaceWith('<input type="checkbox">');
So for instance:
$('input[type="radio"][name="option"]').each(function() {
$(this).replaceWith('<input type="checkbox" name="option" value="' + this.value + '">');
});
Or if the values may contain characters requiring entities:
$('input[type="radio"][name="option"]').each(function() {
var rep = $('<input type="checkbox" name="option">');
rep.attr("value", this.value);
$(this).replaceWith(rep);
});
Instead of replacing the elements you can have two groups of which one is hidden depending on the checkbox:
HTML
<input type="checkbox" id="multiOptions">IsForMultioptions</input>
<div id="radios">
<input type="radio" value="1" name="option">option1</input>
<input type="radio" value="2" name="option">option2</input>
</div>
<div id="checkboxes">
<input type="checkbox" value="1" name="option">option1</input>
<input type="checkbox" value="2" name="option">option2</input>
</div>
jQuery
$(document).ready(function() {
$('#checkboxes').hide();
$('#multiOptions').on('click', function() {
if ($(this).is(':checked')) {
$('#radios').hide();
$('#checkboxes').show();
}
else {
$('#radios').show();
$('#checkboxes').hide();
}
});
});
jsFiddle example.

Categories