Get values of all selected checkboxes in multiple forms - javascript

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);
}

Related

Checkbox check event is not getting prevented

I have a set of set of checkboxes on which I want to restrict to check maximum of one. If the choice needs to be changed then first checked ones need to be unchecked but maximum limit needs to be one.
Here is the jquery code.
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var checkedReportValues = $('#ReportRow input:checkbox:checked').map(function () {
return this.value;
}).get();
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
alert(checkedReportValues);
})
);
Here, the above code is restricting only one checkbox to be checked but when I am trying to check other, they first are being checked and then unchecked. Where I am doing wrong ?
Here is the dynamically created HTML.
//Add Code to Create CheckBox dynamically by accessing data from Ajax for the application selected above
var Reports = " User, Admin, Detail, Summary";
var arrReportscheckBoxItems = Reports.split(',');
var reportscheckBoxhtml = ''
for (var i = 0; i < arrReportscheckBoxItems.length; i++) {
reportscheckBoxhtml += ' <label style="font-weight: 600; color: #00467f !important;"><input type="checkbox" value=' + arrReportscheckBoxItems[i] + '>' + arrReportscheckBoxItems[i] + '</label>';
}
//Add Submit button here
reportscheckBoxhtml += ' <button type="button" id="SubmitReport" class="btn btn-primary">Submit</button>';
$('#ReportRow').html(reportscheckBoxhtml);
Try this: uncheck all other checkboxes except clicked one inside click event handler, like below
$('#ReportRow').on('click', 'input[type="checkbox"]',function(){
$('#ReportRow input[type="checkbox"]').not(this).prop("checked",false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ReportRow">
<input type="checkbox">one
<input type="checkbox">Two
<input type="checkbox">Three
<input type="checkbox">Four
</div>
This line:
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
is saying you want to uncheck the checkbox. It's doing exactly what you tell it to do. Just a comment: Users may be confused since checkboxes are meant to check multiple selections. Radio buttons are designed for being able to select only one option.
you are returning false from the function when there is a checkbox already selected, which is preventing the checkbox selection.
if ($("#ReportRow input:checkbox:checked").length > 1) {
return false;
}
Do something like this:
$('#ReportRow').on('click', 'input[type="checkbox"]', (function (event) {
alert("Hi");
var curCheckBox = this;
$('#ReportRow').find('input[type="checkbox"]').each(function() {
if(this === curCheckBox)
$(this).attr("checked",true);
else
$(this).attr("checked",false);
});
alert(checkedReportValues);
});

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.

Get check box values with JS

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(",");
}

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.

how to read the value of checkbox in jquery?

<li>
<input type= "checkbox" name="paradigm" id="id_1" value="3"/>
<label for="name_3">foo</label>
</li>
<li>
<input type= "checkbox" name="paradigm" id="id_2" value="4"/>
<label for="name_4">bar</label>
</li>
Here is two checkbox. If I checked checkbox id_1, using jquery I want to read the label foo. If I checked both then it should be ['foo','bar'].
$("input:checkbox:checked").map(function(){
return $(this).next().text();
}).get();
See a working demo
As long as the <label> elements immediately follow their <input> elements, then you can do something like this:
var a = [ ];
$('input[name=paradigm]:checked').next('label').each(function() {
a.push($(this).text());
});
A better solution would be to set proper for attributes on your label elements (i.e. make sure they match up with the id attributes on their checkboxes) and then:
var a = [ ];
$('input[name=paradigm]:checked').each(function() {
a.push($('label[for=' + this.id + ']').text());
});
var checkedLabels = [];
$(':checkbox').each(function() {
if (this.checked) {
var label = $('label[for="' + this.id + '"]').text();
checkedLabels.push(label);
}
});
Try this one:
var vSring = "";
$("input:checkbox[name='paradigm']").click(function(){
if($("input:checkbox[name='paradigm']").filter(":checked").length==2)
{
vSring="";
$("input:checkbox[name='paradigm']").each(function(){
var vText = $(this).next().text();
if(vSring=="")
vSring = vText+",";
else
vSring = vSring+vText+",";
});
alert(vSring);
}
else
{
if($(this).is(":checked"))
{
vSring="";
vSring=$(this).next().text();
alert(vSring);
}
}
});
CLICK HERE TO SEE THE DEMO

Categories