How to check checkbox checked or not using javascript? - javascript

How to check checkbox checked or not using javascript ?
I have a lot of checkbox (dynamic data) . I want to know how can i check when checked chekcbox >= '1' using javascript ?
<input type="checkbox" id="1" name="test[]" onclick="test_fn()"/>
<input type="checkbox" id="2" name="test[]" onclick="test_fn()"/>
<input type="checkbox" id="3" name="test[]" onclick="test_fn()"/>
<input type="checkbox" id="4" name="test[]" onclick="test_fn()"/>
<script>
function test_fn() {
// check it's have checked checkbox or not ? //
}
</script>

Try to pass this in your inline handler,
<input type="checkbox" id="1" name="test[]" onclick="test_fn(this)"/>
And use this.checked to find out whether it is checked or not,
function test_fn(elem) {
alert(elem.checked);
}
DEMO
To check, if the the checked check box greater than or equal to 1, then just do
function test_fn(elem) {
if (document.querySelectorAll("input[name='test[]']:checked").length >= 1) {
alert("yes it is greater than or equal to 1")
}
}
DEMO

function test_fn()
{
if (this.checked) return true;
else return false;
}
Edit:
this reference won't work in this case, thanks to #RajaprabhuAravindasamy for pointing this out, read the comments or check this SO question for more information.
You need to pass a reference explicitly to the checkbox element:
function test_fn (el)
{
if (el.checked) return true;
else return false;
}
As for how to know if checked boxes count is more than one you can simply use a global variable to keep a track of the count like this:
var count = 0;
function test_fn (el)
{
el.checked ? count++ : count--;
return count > 1;
// if (count > 1) alert ("count is more than 1");
}
Demo

Related

referring objects and elements with each

I have a jquery each code where i am trying to match the data set of the previous checkbox with current one, so if they do not match, just uncheck the checkbox, but seems i am missing something here
obj.each(function(i,e) {
var refer = $(e);
if(e.checked && refer.prev(e.dataset.stid) != e.dataset.stid) {
e.checked = false;
}
}
here i am not sure what is wrong, but it is not working, also i am trying to add a code that if there is no previous check, just exists from this block
.prev() is a jQuery method that can return one of two things: an element, or null.
Unless e.dataset.stid is null or undefined, the condition will always be satisfied, thus unchecking all your checkboxes.
To get the previous element's data-stid attribute, try comparing refer.prev().data("stid") instead.
let obj = $("input[type=checkbox]");
obj.each(function(i,e) {
if (i === 0) return;
var refer = $(e);
if(e.checked && refer.prev().data("stid") != e.dataset.stid) {
e.checked = false;
}
});
input:not(:nth-child(2)) { margin-left: 25px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" data-stid="1" checked> data-stid="1"
<input type="checkbox" data-stid="1" checked> data-stid="1"
<input type="checkbox" data-stid="0" checked> data-stid="0"
<input type="checkbox" data-stid="1" checked> data-stid="1"

checkbox onclick wont change checked via jscript

I have 3 checkboxes, i wish to be able to click the box and it tick on/off and via jscript change the value of the input for posting to state weather item is accepted or not on another page. However i have logical script but it wont work, theres no errors but the checkboxes wont click on/off they just click on and thats it.. and the value wont change either i dont understand why.
Could somebody look at this short code and tell me why.
Thank you.
<input type="checkbox" id="paypal" name="paypal1" value=" " onclick='chbxpp();' >
</input>
<label for="paypal" class="checkboxes" >Show PayPal Accepted</label>
<br>
<input type="checkbox" id="facebook" name="facebook" value=" " onclick='chbxfb(this);' >
</input>
<label for="facebook" class="checkboxes" >Show FaceBook Contact Details</label>
<br>
<input type="checkbox" id="twitter" name="twitter" value=" " onclick='chbxtw(this);' >
</input>
<label for="twitter" class="checkboxes" >Show Twitter Contact Details</label>
function chbxpp()
{
if(document.getElementById('paypal').checked === true) {
document.getElementById('paypal').checked = false;
document.getElementById('paypal').value='no';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
if (document.getElementById('paypal').checked === false) {
document.getElementById('paypal').checked = true;
document.getElementById('paypal').value='yes';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
}
function chbxfb(objfb)
{
var that = objfb;
(objfb);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
function chbxtw(objtw)
{
var that = objtw;
(objtw);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
The objpp was my attempt at another method but just does the same thing...
p.s if i just didnt use jscript and just had the html, would the value not be valid if the checkbox was not clicked or would the value still be sent...
iv just fond this..
How to change the value of a check box onClick using JQuery?
states that the value wont be sent if the box is unchecked... But then how do i know after post what has been clicked.... will i receieve a not isset($_POST['paypal']) or an empty($_POST['paypal'])
I imagine your checkboxes begin with no check inside them or .checked === false, but when you call your function chbxpp(), it looks to see if your .checked property === true and if so it sets it back to false. The click event already changes the checkbox's .checked property for you, no need to do it in your code.
//If the checkbox is checked, set it to not checked...???
//But the problem is, the click event just set the .checked property to true
//so setting it back to false makes it like it never happened.
if(document.getElementById('paypal').checked === true) {
//document.getElementById('paypal').checked = false; //This part is a no-no
document.getElementById('paypal').value='yes';
}else{
document.getElementById('paypal').value='no';
}
Adding to Ryan Wilson's answer, set your cbx's initial value to false. (Also check the format of the cbx - the closing tag.)
<input type="checkbox" id="paypal" name="paypal1" value="false" onchange="chbxpp();" />
function chbxpp() {
// the cbx starts false. when it is clicked for the first time it
// becomes true.
if (document.getElementById('paypal').checked) {
// you don't need this.
//document.getElementById('paypal').checked = true;
document.getElementById('paypal').value = 'yes';
var vv = document.getElementById('paypal').value;
console.log(vv);
} else {
// you also don't need this.
//document.getElementById('paypal').checked = false;
document.getElementById('paypal').value = 'no';
var vv = document.getElementById('paypal').value;
console.log(vv);
}
}

Issue with if statement in JavaScript function

I use a radio button plata with two values 1 and 2 in my form and another input hidden plata2 take one value depend to plata.
So i use this code inside in an existent function total():
test = document.getElementById('plata').value;
if (test == 1) {
document.getElementById('plata2').value=pretfinal;
}
else{
document.getElementById('plata2').value=avansfinal;
}
But plata2 take just first value, else never works? can help with this.
try "checked" instead of value:
test = document.getElementById('plata').checked;
if (test) {document.getElementById('plata2').value=pretfinal;}
else {document.getElementById('plata2').value=avansfinal;}
I think what you have done is given both the radio elements the same id
test = document.getElementById('plata').value;
the code of line above will only select the 1st radio element, in your case the 1st one with value 1.
Hence leading to the if block and not the else block.
Here is a sample code for your requirement
https://jsfiddle.net/udkxynsn/
<label for='plate_1'>1</label>
<input type=radio name='plata' id='plata_1' value=1>
<br>
<label for='plate_1'>2</label>
<input type=radio name='plata' id='plata_2' value=2>
<br>
<input id='plata2'>
<br>
<br>
<div>CLICK</div>
<script>
document.querySelector('div').addEventListener('click', test);
function test(){
test = document.querySelector('[name=plata]:checked').value;
if (test == 1) {
document.getElementById('plata2').value="value1";
}else {
document.getElementById('plata2').value="value2";
}
}
</script>
Check which of radio element is selected:
function total() {
if (document.getElementById('plata').checked) {
test = 1;
}
else
{
test = 2;
}
if (test == 1) { document.getElementById('plata2').value = pretfinal; }
else { document.getElementById('plata2').value = avansfinal; }
}

Validating a checkbox after already validating other sections of a form [duplicate]

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.
JS (wrong)
function valthis(){
if (document.FC.c1.checked) {
alert ("thank you for checking a checkbox")
} else {
alert ("please check a checkbox")
}
}
HTML
<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br>
<input type = "checkbox" name = "c1" value = "c4"/> C4
<br>
</form>
<br>
<br>
<input type = "button" value = "Edit and Report" onClick = "valthisform();">
So what I ended up doing in JS was this:
function valthisform(){
var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked
if (chkd == true){
} else {
alert ("please check a checkbox")
}
}
I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.
You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?
Here's a non-jQuery solution to check if any checkboxes on the page are checked.
var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.
This should work:
function valthisform()
{
var checkboxs=document.getElementsByName("c1");
var okay=false;
for(var i=0,l=checkboxs.length;i<l;i++)
{
if(checkboxs[i].checked)
{
okay=true;
break;
}
}
if(okay)alert("Thank you for checking a checkbox");
else alert("Please check a checkbox");
}
If you have a question about the code, just comment.
I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/
I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them.
Let's begin with giving the checkboxes a class so we can round them up very nicely.
I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.
HTML
<input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
<input type="checkbox" class="checkbox" value=ck2 /> ck2<br />
JavaScript
function atLeastOneCheckboxIsChecked(){
const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}
When called, the function will return false if no checkbox has been checked and true if one or both is.
It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true.
the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.
Check this.
You can't access form inputs via their name. Use document.getElements methods instead.
Vanilla JS:
var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable
function activitiesReset() {
var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
return true;
}
}
return false;
}
error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead.
if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
error[2].style.display = 'block'; // red error label is now visible.
}
}
for (var i=0; i<checkboxes.length; i++) { // whenever a checkbox is checked or unchecked, activitiesReset runs.
checkboxes[i].addEventListener('change', activitiesReset);
}
Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});
You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.
Reference Link
<label class="control-label col-sm-4">Check Box 2</label>
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
<input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />
<script>
function checkFormData() {
if (!$('input[name=checkbox2]:checked').length > 0) {
document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
return false;
}
alert("Success");
return true;
}
</script>
< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" > < / script >
< script type = "text/javascript" >
function checkSelectedAtleastOne(clsName) {
if (selectedValue == "select")
return false;
var i = 0;
$("." + clsName).each(function () {
if ($(this).is(':checked')) {
i = 1;
}
});
if (i == 0) {
alert("Please select atleast one users");
return false;
} else if (i == 1) {
return true;
}
return true;
}
$(document).ready(function () {
$('#chkSearchAll').click(function () {
var checked = $(this).is(':checked');
$('.clsChkSearch').each(function () {
var checkBox = $(this);
if (checked) {
checkBox.prop('checked', true);
} else {
checkBox.prop('checked', false);
}
});
});
//for select and deselect 'select all' check box when clicking individual check boxes
$(".clsChkSearch").click(function () {
var i = 0;
$(".clsChkSearch").each(function () {
if ($(this).is(':checked')) {}
else {
i = 1; //unchecked
}
});
if (i == 0) {
$("#chkSearchAll").attr("checked", true)
} else if (i == 1) {
$("#chkSearchAll").attr("checked", false)
}
});
});
< / script >
Prevent user from deselecting last checked checkbox.
jQuery (original answer).
$('input[type="checkbox"][name="chkBx"]').on('change',function(){
var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
return this.value;
}).toArray();
if(getArrVal.length){
//execute the code
$('#msg').html(getArrVal.toString());
} else {
$(this).prop("checked",true);
$('#msg').html("At least one value must be checked!");
return false;
}
});
UPDATED ANSWER 2019-05-31
Plain JS
let i,
el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),
msg = document.getElementById('msg'),
onChange = function(ev){
ev.preventDefault();
let _this = this,
arrVal = Array.prototype.slice.call(
document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))
.map(function(cur){return cur.value});
if(arrVal.length){
msg.innerHTML = JSON.stringify(arrVal);
} else {
_this.checked=true;
msg.innerHTML = "At least one value must be checked!";
}
};
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>
<div id="msg"></div>
$('input:checkbox[type=checkbox]').on('change',function(){
if($('input:checkbox[type=checkbox]').is(":checked") == true){
$('.removedisable').removeClass('disabled');
}else{
$('.removedisable').addClass('disabled');
});
if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
|| ($("#checkboxid3").is(":checked"))) {
//Your Code here
}
You can use this code to verify that checkbox is checked at least one.
Thanks!!

Limit number of checkboxes allowed to be checked [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Count the number of checkboxes selected without reloading the page?
I have an order form that asks the User which type of pass they would like (1-3 days), and gives them the option to choose the days they want the pass for.
Currently, when they choose 3 days, my JQuery selects all 3 checkboxes for them, and deselects when they choose 1 or 2 day(s). However, what I'm trying to do is:
When they select 2 day pass, it only allows them to check a maximum of 2 boxes. When they select a 1 day pass, it only allows them to check 1 box.
I'm drawing a blank as to what needs to go in my validateDays() function - the best way to go about running this validation or whether this is actually the best route to take.
Every method I think of using requires the checkboxes to have the same Name/ID - but due to other parts of the form (omitted), they unfortunately can't.
Any ideas / pointers?
HEAD Section JavaScript:
<script type="text/javascript">
function validateDays() {
$('#matthewpeckham').find('input[type="checkbox"]').click(function () {
var pass = parseInt($('input[name="other_1"]:checked').val(), 10) //1,2,3
var days = $('#matthewpeckham').find('input[type="checkbox"]:checked').length;
console.log(days, pass);
if (days == pass) {
$('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', true);
}
else {
$('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', false);
}
})
$('input[name="other_1"]').change(function () {
$('#matthewpeckham').find('input[type="checkbox"]').prop({
'checked': false,
'disabled': false
});
if (parseInt($(this).val(), 10) == 3) $('#matthewpeckham').find('input[type="checkbox"]').prop({
'checked': true,
'disabled': false
});
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
jQuery('#3daypass').click(function() {
jQuery('#other_2 , #other_3 , #other_4').prop('checked', true);
});
jQuery('#2daypass , #1daypass').click(function() {
jQuery('#other_2 , #other_3 , #other_4').prop('checked', false);
});
});
</script>
BODY Section HTML:
<input name="other_1" type="radio" value="3daypass" id="3daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="2daypass" id="2daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="1daypass" id="1daypass" onClick="validateDays();">
<input name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb">
<input name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb">
<input name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb">
Here's a jQuery solution: jsFiddle example
$('input[type="checkbox"]').click(function () {
var pass = parseInt($('input[name="other_1"]:checked').val(), 10) //1,2,3
var days = $('input[type="checkbox"]:checked').length;
console.log(days, pass);
if (days == pass) {
$('input[type="checkbox"]').not(':checked').prop('disabled', true);
}
})
$('input[name="other_1"]').change(function () {
$('input[type="checkbox"]').prop({
'checked': false,
'disabled': false
});
if (parseInt($(this).val(), 10) == 3) $('input[type="checkbox"]').prop({
'checked': true,
'disabled': false
});
});
You need to check the number of checked boxes in your validate function:
function validateDays() {
var numBoxesChecked = $("input:checkbox:checked").length;
if (document.getElementById("2daypass").checked && numBoxesChecked > 2) {
// invalid
}
if (document.getElementById("1daypass").checked && numBoxesChecked > 1) {
// invalid
}
}
Keep in mind that any javascript validation can be bypassed, so ensure you are performing some type of validation on your server as well.
Also note you may want to change the numBoxesChecked selector if there are other unrelated checkboxes on the page, such as limiting it to a container e.g.
var numBoxesChecked = $('#someContainer').find("input:checkbox:checked").length;
jQuery exposes a checkbox selector that should prove useful here.
Your validateDays function can then do something along these lines
var checkedBoxes = jQuery(":checkbox:checked");
var numChecked = checkedBoxes.length;
...
else if (document.getElementById("2daypass").checked) {
if (numChecked > 2) { /*do something*/ }
}
else if (document.getElementById("1daypass").checked) {
if (numChecked > 1) { /*do something*/ }
}
else {
// DO NOTHING
}
...
However, you might have an issue with "reverting" the box. You might be able to do simply
jQuery(this).prop('checked', false)
I'm not an expert in this area by any means but here is what I do on a site of mine, you should be able to modify it to suit your needs...just remember to give your inputs the same class name.
<script type="text/javascript">
function Check() {
var count = 0;
var checkBoxes = document.getElementsByClassName('chkValidation');
for (var index = 0; index < checkBoxes.length; index++) {
if (checkBoxes[index].type == 'checkbox') {
if (!checkBoxes[index].disabled) {
count = checkBoxes[index].checked ? (count + 1) : count;
}
}
}
if (count > 3) {
alert('Question two - please select a maximum of 3 sub questions to ask.');
return false;
}
return true;
}
You could also do it dymanically, using a function like so:
$('.checkbox').on('click', function(e) {
var num_checked = 0;
$('.checkbox').each(function() {
if ( $(this).prop('checked') ) num_checked++;
});
var max_checked = $('input[name="other_1"]:checked').val();
if ( num_checked > max_checked ) {
$(this).prop('checked', false);
}
});
Assuming a few small modifications to your html:
<input name="other_1" type="radio" value="3" id="3daypass">
<input name="other_1" type="radio" value="2" id="2daypass">
<input name="other_1" type="radio" value="1" id="1daypass">
<input class="checkbox" name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb">
<input class="checkbox" name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb">
<input class="checkbox" name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb">
Demo: http://jsbin.com/osecep/1/
It's not perfect, and you'd probably want to clear the checkboxes when the number of days is changed, but that should set you on the right track.

Categories

Resources