Get check box values with JS - javascript

So i have 2 categories of checkboxes.
<input type="checkbox" name="foo" value="val1" />
<input type="checkbox" name="foo" value="val2" />
<input type="checkbox" name="bar" value="val1" />
<input type="checkbox" name="bar" value="val2" />
When a box is checked I want to run a jQuery function that will assign two variables
var foo = //the values of the checked boxes with the foo name
var bar = //the values of the checked boxes with the bar name
So lets say only the first check box was checked in the foo group where as both were checked in the bar group. The groups values would be as follows
var foo = val1;
var bar = val1,val2;
What is the best way to search through all checkboxes that share the same name/class Look to see if they are checked and if so add their value to a string?

You can try something like
var foo = $("input:checkbox[name='foo']:checked").map(function(){
return this.value;
}).get().join(',');
var bar = $("input:checkbox[name='bar']:checked").map(function(){
return this.value;
}).get().join(',');
See a working demo

Get all checked checkboxes :
$(':checkbox').is(':checked').each(function() {
if ($(this).value) {
//get values here
}
});
Get all checkboxes :
$(':checkbox').each(function() {
if ($(this).value) {
//get values here
}
});

jQuery :checked selector to the rescue.

Give your checkboxes a common class, then:
$('.classofcheckbox').each(function() {
if ($(this).val()) {
// do stuff...
}
});
Or more directly
$('.classofcheckbox:checked').each(function() {
// do stuff...
});

function checkedBoxesToString(name) {
var checked = [];
$('[name=' + name + ']:checked').each(function (a, b) {
checked.push($(b).val());
});
return checked.join(",");
}

Related

trying to get all checkboxes from full page

I am trying to get all checked chckboxes value of a full page.
the full has all sort of html tags defined.
There is another piece to it which is div which has a parent class of "syllabus". except that class div and any checkboxes inside it will be ignored when the other checkboxes of complete page is checked
I am trying some like this:
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
Maybe something like this:
var checkedValues = [];
$('input[type=checkbox]:checked').each(function(){
checkedValues.push($(this).val());
});
console.log(checkedValues);
Or (using .map() and .get())
var checkedValues = $("input[type=checkbox]:checked").map(function() {
return $(this).val();
}).get();
console.log(checkedValues);
More info
Here you go with a solution
var sThisVal = [];
$('input[type=checkbox]').each(function () {
sThisVal.push((this.checked ? $(this).val() : ""));
});
console.log(sThisVal);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked value="1">Checkbox 1
<input type="checkbox" value="2">Checkbox 2
<input type="checkbox" checked value="3">Checkbox 3
<input type="checkbox"value="4">Checkbox 4
Hope this will help you.

How to make key value pair array when chekbox checked using jquery?

I have multiple checkbox, when i check a checkbox two key value pair will generate.
Like this : Object {id: "101", name: "example"}
This will generate for every checkbox checked and i want for multiple checkbox checked array. look like this :
[{id:"id1",name:"name1"},{id:"id2",name:"name2"}]
What I have done
$('.chkCompare').click(function(event) {
var value = [],
projectName = {},
span = $(this).attr('id'),
value = $('.chkCompare:checked').map(function() {
$('#span' + span).text('ADDED').css({
"color": "green"
});
projectName['id'] = $(this).attr('id');
projectName['name'] = $(this).attr('title');
return value.push(projectName);
}).get();
});
When I uncheck checkbox they will be remove from array and want to prevent check maximum 3 checkbox if >3 then show an alert box.
You can check the length property of :checked checkbox's. Based on your condition and use event.preventDefault() to cancel the default action.
$('.chkCompare').click(function(event) {
var checkedElemets = $('.chkCompare:checked');
if (checkedElemets.length > 3) {
event.preventDefault();
alert('Only 3 checkbox can be checked');
}
var values = checkedElemets.map(function() {
return {
id: this.id,
name: this.title
};
}).get();
console.log(values)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="chkCompare" title='t1' id='i1' />
<input type="checkbox" class="chkCompare" title='t2' id='i2'/>
<input type="checkbox" class="chkCompare" title='t3' id='i3'/>
<input type="checkbox" class="chkCompare" title='t4' id='i4'/>
<input type="checkbox" class="chkCompare" title='t5' id='i5'/>
$("input[type='checkbox']").change(function(){
var arr = {};
var count = 0;
$.each($("input[type='checkbox']:checked"), function(){
if(count++<3){
arr[this.id] =this.name;
}else{
$(this).prop('checked', false);
}
});
console.log(JSON.stringify(arr));
});

Get values of all selected checkboxes in multiple forms

I have a series of checkbox lists, and I want to alert the values of all selected checkboxes on click of a global button. Additionally, if there is a more "proper" way to do this rather than using inputs, or maybe using a form or series of forms, let me know.
HTML:
<input type="checkbox" class="A" value="0">0</input>
<input type="checkbox" class="A" value="1">1</input>
<input type="checkbox" class="B" value="0">0</input>
<button onclick='return selectedvalues();'>GO!</button>
javascript:
function selected values(){
//alert all selected values of checkboxes of classes A and B
}
function selectedValues(){
//alert all selected values of checkboxes of classes A and B
var $checkboxes = $("input[type='checkbox']:checked");
$checkboxes.each(function(){
alert($(this).attr("class") + " " + $(this).val());
});
}
This function will do the trick.
While you've already accepted an answer, I had a few moments and thought I'd offer this interpretation:
function findChecked() {
var group = document.getElementsByName(this.name),
checked = [].map.call(group, function(a){
a.nextElementSibling.style.color = a.checked ? 'limegreen' : '#000';
if (a.checked) {
return a;
}
}).filter(function(a){
return 'undefined' !== typeof a;
});
return checked;
}
[].forEach.call(document.querySelectorAll('input[type="checkbox"]'), function(a){
a.addEventListener('change', findChecked);
});
JS Fiddle demo.
References:
Array.prototype.filter().
Array.prototype.forEach().
Array.prototype.map().
Function.prototype.call().
This should do it
function selected_values() {
var messages = "";
$("form input[type='checkbox']:checked").each(function(){
// Go through all checkboxes that are checked
messages += $(this).val() + "\n";
});
alert(messages);
}

Get the value of checked checkbox?

So I've got code that looks like this:
<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">
I just need Javascript to get the value of whatever checkbox is currently checked.
EDIT: To add, there will only be ONE checked box.
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
For modern browsers:
var checkedValue = document.querySelector('.messageCheckbox:checked').value;
By using jQuery:
var checkedValue = $('.messageCheckbox:checked').val();
Pure javascript without jQuery:
var checkedValue = null;
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
break;
}
}
I am using this in my code.Try this
var x=$("#checkbox").is(":checked");
If the checkbox is checked x will be true otherwise it will be false.
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
This does not directly answer the question, but may help future visitors.
If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.
This can be done in the HTML:
<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>
or with JavaScript:
cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
$(document).ready(function() {
var ckbox = $("input[name='ips']");
var chkId = '';
$('input').on('click', function() {
if (ckbox.is(':checked')) {
$("input[name='ips']:checked").each ( function() {
chkId = $(this).val() + ",";
chkId = chkId.slice(0, -1);
});
alert ( $(this).val() ); // return all values of checkboxes checked
alert(chkId); // return value of checkbox checked
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
Use this:
alert($(".messageCheckbox").is(":checked").val())
This assumes the checkboxes to check have the class "messageCheckbox", otherwise you would have to do a check if the input is the checkbox type, etc.
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" onchange="getValue(this.value)" value="1" name="mailId[]">
function getValue(value){
alert(value);
}
None of the above worked for me without throwing errors in the console when the box wasn't checked so I did something along these lines instead (onclick and the checkbox function are only being used for demo purposes, in my use case it's part of a much bigger form submission function):
function checkbox() {
var checked = false;
if (document.querySelector('#opt1:checked')) {
checked = true;
}
document.getElementById('msg').innerText = checked;
}
<input type="checkbox" onclick="checkbox()" id="opt1"> <span id="msg">Click The Box</span>
If you're using Semantic UI React, data is passed as the second parameter to the onChange event.
You can therefore access the checked property as follows:
<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
Surprised to see no working vanilla JavaScript solutions here (the top voted answer does not work when you follow best practices and use different IDs for each HTML element). However, this did the job for me:
Array.prototype.slice.call(document.querySelectorAll("[name='mailId']:checked"),0).map(function(v,i,a) {
return v.value;
});
If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.
$(document).on("change", ".messageCheckbox", function(evnt){
var data = $(".messageCheckbox");
data.each(function(){
console.log(this.defaultValue, this.checked);
// Do something...
});
}); /* END LISTENER messageCheckbox */
pure javascript and modern browsers
// for boolean
document.querySelector(`#isDebugMode`).checked
// checked means specific values
document.querySelector(`#size:checked`)?.value ?? defaultSize
Example
<form>
<input type="checkbox" id="isDebugMode"><br>
<input type="checkbox" value="3" id="size"><br>
<input type="submit">
</form>
<script>
document.querySelector(`form`).onsubmit = () => {
const isDebugMode = document.querySelector(`#isDebugMode`).checked
const defaultSize = "10"
const size = document.querySelector(`#size:checked`)?.value ?? defaultSize
// 👇 for defaultSize is undefined or null
// const size = document.querySelector(`#size:checked`)?.value
console.log({isDebugMode, size})
return false
}
</script>
Optional_chaining (?.)
You could use following ways via jQuery or JavaScript to check whether checkbox is clicked.
$('.messageCheckbox').is(":checked"); // jQuery
document.getElementById(".messageCheckbox").checked //JavaScript
To obtain the value checked in jQuery:
$(".messageCheckbox").is(":checked").val();
In my project, I usually use this snippets:
var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
type[i] = $(this).val();
});
And it works well.

Javascript checkbox onChange

I have a checkbox in a form and I'd like it to work according to following scenario:
if someone checks it, the value of a textfield (totalCost) should be set to 10.
then, if I go back and uncheck it, a function calculate() sets the value of totalCost according to other parameters in the form.
So basically, I need the part where, when I check the checkbox I do one thing and when I uncheck it, I do another.
Pure javascript:
const checkbox = document.getElementById('myCheckbox')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
alert('checked');
} else {
alert('not checked');
}
})
My Checkbox: <input id="myCheckbox" type="checkbox" />
function calc()
{
if (document.getElementById('xxx').checked)
{
document.getElementById('totalCost').value = 10;
} else {
calculate();
}
}
HTML
<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>
If you are using jQuery.. then I can suggest the following:
NOTE: I made some assumption here
$('#my_checkbox').click(function(){
if($(this).is(':checked')){
$('input[name="totalCost"]').val(10);
} else {
calculate();
}
});
Use an onclick event, because every click on a checkbox actually changes it.
The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.
const checkbox = $("#checkboxId");
checkbox.change(function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
});
HTML:
<input type="checkbox" onchange="handleChange(event)">
JS:
function handleChange(e) {
const {checked} = e.target;
}
Reference the checkbox by it's id and not with the #
Assign the function to the onclick attribute rather than using the change attribute
var checkbox = $("save_" + fieldName);
checkbox.onclick = function(event) {
var checkbox = event.target;
if (checkbox.checked) {
//Checkbox has been checked
} else {
//Checkbox has been unchecked
}
};
Javascript
// on toggle method
// to check status of checkbox
function onToggle() {
// check if checkbox is checked
if (document.querySelector('#my-checkbox').checked) {
// if checked
console.log('checked');
} else {
// if unchecked
console.log('unchecked');
}
}
HTML
<input id="my-checkbox" type="checkbox" onclick="onToggle()">
try
totalCost.value = checkbox.checked ? 10 : calculate();
function change(checkbox) {
totalCost.value = checkbox.checked ? 10 : calculate();
}
function calculate() {
return other.value*2;
}
input { display: block}
Checkbox: <input type="checkbox" onclick="change(this)"/>
Total cost: <input id="totalCost" type="number" value=5 />
Other: <input id="other" type="number" value=7 />
I know this seems like noob answer but I'm putting it here so that it can help others in the future.
Suppose you are building a table with a foreach loop. And at the same time adding checkboxes at the end.
<!-- Begin Loop-->
<tr>
<td><?=$criteria?></td>
<td><?=$indicator?></td>
<td><?=$target?></td>
<td>
<div class="form-check">
<input type="checkbox" class="form-check-input" name="active" value="<?=$id?>" <?=$status?'checked':''?>>
<!-- mark as 'checked' if checkbox was selected on a previous save -->
</div>
</td>
</tr>
<!-- End of Loop -->
You place a button below the table with a hidden input:
<form method="post" action="/goalobj-review" id="goalobj">
<!-- we retrieve saved checkboxes & concatenate them into a string separated by commas.i.e. $saved_data = "1,2,3"; -->
<input type="hidden" name="result" id="selected" value="<?= $saved_data ?>>
<button type="submit" class="btn btn-info" form="goalobj">Submit Changes</button>
</form>
You can write your script like so:
<script type="text/javascript">
var checkboxes = document.getElementsByClassName('form-check-input');
var i;
var tid = setInterval(function () {
if (document.readyState !== "complete") {
return;
}
clearInterval(tid);
for(i=0;i<checkboxes.length;i++){
checkboxes[i].addEventListener('click',checkBoxValue);
}
},100);
function checkBoxValue(event) {
var selected = document.querySelector("input[id=selected]");
var result = 0;
if(this.checked) {
if(selected.value.length > 0) {
result = selected.value + "," + this.value;
document.querySelector("input[id=selected]").value = result;
} else {
result = this.value;
document.querySelector("input[id=selected]").value = result;
}
}
if(! this.checked) {
// trigger if unchecked. if checkbox is marked as 'checked' from a previous saved is deselected, this will also remove its corresponding value from our hidden input.
var compact = selected.value.split(","); // split string into array
var index = compact.indexOf(this.value); // return index of our selected checkbox
compact.splice(index,1); // removes 1 item at specified index
var newValue = compact.join(",") // returns a new string
document.querySelector("input[id=selected]").value = newValue;
}
}
</script>
The ids of your checkboxes will be submitted as a string "1,2" within the result variable. You can then break it up at the controller level however you want.

Categories