Check checkbox based on variable value - javascript

I'm struggling with a checkbox. I want the checkbox to be checked depending on a variable coming from the database. I can see the value in my console, so it's dynamically filled, but I can't have the checkbox checked.
I tried 2 things:
$(document).ready(function() {
$('input[name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"]').each(function(index) {
if ($(this).val() ==
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%")
($(this).prop('checked', true));
});
And
$(document).ready(function() {
var checkBox =
[
["OPTIN_NEWSLETTER_STARTER_INDEPENDANT",
"%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"],
];
for (var i = 0; i < checkBox.length; i++) {
if (checkBox[i][1] == "Yes") {
if ($('input[name="' + checkBox[i][0] + '"]'))
{
$('input[name="' + checkBox[i][0] +
'"]').prop("checked", true).change();
}
}
};
This is my html checkbox:
<label class="yesNoCheckboxLabel">
<input type="checkbox"
name="OPTIN_NEWSLETTER_STARTER_INDEPENDANT" id="control_COLUMN136"
label="OPTIN_NEWSLETTER_STARTER_INDEPENDANT"
value="%%OPTIN_NEWSLETTER_STARTER_INDEPENDANT%%"
checked="">OPTIN_NEWSLETTER_STARTER_INDEPENDANT</label>
It would be great to have someone's insights, thanks!
Kind regards,
Loren

I tested your case locally and It's working fine may be you are lacking some where else and make sure use attr in order to set value for jquery 1.5 or below
For jquery 1.5 or below
($(this).prop('checked', true));
$(document).ready(function() {
$('input[name="vehicle1"]').each(function(index) {
if ($(this).val() ==
"vehicle1")
($(this).prop('checked', true));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a bike<br>
<input type="checkbox" name="vehicle1" value="vehicle1"> I have a car
</form>
and last thing make sure that value must be same for this condition
$(this).val() == "vehicle1"

Related

How to check checkbox checked or not using 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

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!!

Difficulty inserting variable into jquery attribute identification

I'm trying to us jquery to detect if another text box in the same group is checked. The code below is shows how I'm trying to retrieve the group name when the advanced box is checked and use it to see if the accompanying Basic box is checked. The problem is that "basicTrue" is always assigned "undefined", regardless of the condition of the basic checkbox.
<div id="boxes">
<input style="text-align:center;" type="checkbox" name="group1" value="Basic">
<input style="text-align:center;" type="checkbox" name="group1" value="Advanced">
<input style="text-align:center;" type="checkbox" name="group2" value="Basic">
<input style="text-align:center;" type="checkbox" name="group2" value="Advanced">
</div>
$("#boxes").contents().find(":checkbox").bind('change', function(){
val = this.checked;
var $obj = $(this);
if($obj.val()=="Advanced"){
var group = $obj.attr("name");
var basicTrue = $('input[name=group][value="Basic"]').prop("checked");
if(basicTrue)
{
//Do stuff
}
else
{
$obj.attr('checked', false);
}
}
This code is a proof of concept I used to prove that code formatted this way works, it does return the status of the "Basic" checkbox in "group1".
var basicTrue = $('input[name="group1"][value="Basic"]').prop("checked");
I know the variable "group" is being given the right name: group1 for example. Is there a reason why using this variable in the code wouldn't work?
Those are variables, and they need to be concentenated into the string in the selector, like so:
$('input[name="' + group + '"][value="Basic"]').prop("checked");
A simplified version:
$("#boxes input[type='checkbox']").on('change', function(){
var bT = $('input[name="'+ this.name +'"][value="Basic"]').prop("checked");
if( this.value == "Advanced" && bT) {
//Do stuff
} else {
$(this).prop('checked', false);
}
});

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.

How to automatically uncheck checkbox if textbox is filled

I've made the checkbox to be default check. How can I uncheck the checkbox automatically if certain textfield is filled. I've thinking of using javascript.
I tried using this
<input type="text" name="commentID" id="commentID" onkeyup="userTyped('skipID', this)"/>
<input type="checkbox" name="skipID" value="N" id="skipID" checked="checked" />
and the javascript
function userTyped(commen, e){
if(e.value.length > 0){
document.getElementById(commen).checked=false;
}else{
document.getElementById(commen).checked=true;
}}​
It works but how if i have 3 textfield, and I want the checkbox to be filled only after all textfield is filled.
Just do this:
<input type="checkbox" id="someid" checked="checked"/>
<textarea onchange="if (this.value != '') document.getElementById('someid').checked = false;"></textarea>
if(document.getElementById('yourtextBox').value!=' ')
{
document.getElementById('checbox').checked=false;
}
Try the following code. In this code, each time when you type a character in the textfield, the function will be called and the length of the textfield value is not zero, the checbox will be unchecked and it will be checked while you clear your textfield
//Function get called when you type each letter
function OnChangeTextField(){
//getting the length of your textbox
var myLength = $("#myTextbox").val().length;
if(myLength > 0){
$("#myCheckbox").attr("checked", false);
}else{
$("#myCheckbox").attr("checked", true);
}
}
<input type = "text" id = "myTextbox" onkeyup= "OnChangeTextField();"/>
<input type="checkbox" id = "myCheckbox" value = "true" checked = "checked"/>
$("#comment").on("keyup blur", function () {
$("#box").prop("checked", this.value == "");
});
EDIT: You can also use jQuery
$("#comment").on("keyup blur", function() {
$("#box").prop("checked", this.value == "");
});
Try jQuery, This works for me...

Categories

Resources