I am getting values (1 or 0) from my database via ajax/jquery and I want to set a bunch of checkbox checked states depending on the values returned for each.
So firstly, I am setting the values for all checkboxes. Then I run a function to set the checkbox checked state based on the values. When I try this, all checkboxes are checked regardless of value:
Snippet of my Ajax response (jQuery)
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
$("#checkbox1").prop('value',value[2]);
$("#checkbox2").prop('value',value[3]);
$("#checkbox3").prop('value',value[4]);
$("#checkbox4").prop('value',value[5]);
});
$("#div :checkbox").each(function () {
if ($(this).attr('value', '1')){
$(this).attr('checked', true);
}
else
if ($(this).attr('value', '0')){
$(this).attr('checked', false);
}
});
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
You are likely trying to set the value of the checkbox false with a string. This does not work. You need it to be a booelan true/false or 0/1 .. The value "0" will set the checkbox "checked". See the example and how the second checkbox remains checked.
$(document).ready(function() {
$("#chkbox1").prop("checked", 0);
$("#chkbox2").prop("checked", "0");
$("#chkbox3").prop("checked", 1);
$("#chkbox4").prop("checked", "1");
$("#chkbox5").prop("checked", parseInt("0"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label>
<input id="chkbox1" type="checkbox" name="chk" checked />checkbox1
</label>
<label>
<input id="chkbox2" type="checkbox" name="chk" checked/>checkbox2
</label>
<label>
<input id="chkbox3" type="checkbox" name="chk" />checkbox3
</label>
<label>
<input id="chkbox4" type="checkbox" name="chk" />checkbox4
</label>
<p>
<label>
<input id="chkbox5" type="checkbox" name="chk" checked />checkbox5
</label>
</p>
To properly "check/uncheck" a chekcbox you should use the jQuery functions prop('checked',true) or prop('checked',false).
Change the if/else statement in this way:
if ($(this).attr('value', '1')){
$(this).prop('checked', true);
}
else
if ($(this).attr('value', '0')){
$(this).prop('checked', false);
}
You are not checking for current value you are setting value to 1 for all checkboxes;
if ($(this).attr('value', '1')){
.attr('attribute name', [new value to set]);
So you are using this function in wrong way. To get value try
if ($(this).attr('value')){
Here you will get 1 or 0 as you said you are getting 1 & 0 from server after ajax.
Related
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"
I have a group of checkboxes that when you click ONE, they should ALL be checked.
When a user clicks one checkbox, it checks all the other checkboxes starting with that class name. What I want is for the user to click a checkbox, and $(".atpSelections").change is triggered only once per click.
Here's the code:
$(".atpSelections").change(function() {
console.log("CHANGED");
//Check ALL other checkboxes starting with that class name:
var className = $(this).attr("class");
className=className.replace("atpSelections ", "");
className=className.trim();
className=className.split("-");
//Get current checkbox state
var currentState = $(this).attr("checked");
//Now loop through all other checkboxes starting
//with the same class name and check them:
$("input[class*='"+className[0]+"-']").each(function(i){
//THIS IS TRIGGERING "$(".atpSelections").change"!!
if(currentState && currentState=="checked")
{
$(this).prop('checked', true);
}else
{
$(this).prop('checked', false);
}
});
});
The Problem
The problem is that when the user clicks one checkbox, the $(".atpSelections").change method gets triggered over and over because $(this).prop('checked', true); triggers $(".atpSelections").change again, and it just goes round and round.
So 1 click to a checkbox triggers 100s "change" events, when I only want it triggered once.
How do I alter the checkbox's state inside $(".atpSelections").change without triggering $(".atpSelections").change again?
Attempts
I tried changing $(".atpSelections").change to $(".atpSelections").click but it had the same issue. I think $(this).prop('checked', true); triggers the click event.
Solution
I used #James 's answer and changed
var currentState = $(this).attr("checked");
to
var currentState = $(this).prop("checked") ? "checked" : "";
and it worked perfectly! Thanks.
Here's the JSFiddle: https://jsfiddle.net/zL7amo0y/
The problem is with your currentState variable. Please do a console.log on it. I'm guessing it's undefined?
Below is your code fixed in both jQuery and Vanialla JS.
JQuery:
$(".atpSelections").change(function() {
var currentState = $(this).prop("checked");
console.log(currentState);
$("input[name='checkboxToCheck']").each(function(i){
if(currentState)
{
$(this).prop('checked', true);
}else
{
$(this).prop('checked', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myForm">
<label for="checkbox1">Main Checkbox:</label>
<input class="atpSelections" value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox2">Checkbox2:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox3">Checkbox3:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
</form>
Vanilla JS:
var checkbox = document.getElementById("checkbox1")
var checkboxToCheck = document.getElementsByName("checkboxToCheck");
checkboxToCheck = [].slice.call(checkboxToCheck);
function checkAllBoxes() {
checkboxToCheck.forEach((element) => {
if (checkbox.checked) {
element.checked = true;
} else {
element.checked = false;
}
});
}
checkbox.addEventListener("change", checkAllBoxes);
<form name="myForm">
<label for="checkbox1">Main Checkbox:</label>
<input value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox2">Checkbox2:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
<label for="checkbox3">Checkbox3:</label>
<input name="checkboxToCheck" value="checkbox1" type="checkbox" id="checkbox1" />
</form>
I'm thinking know what is your problem, I got it with a plugin of checkboxes too.
Try this
$(".atpSelections").on('change.custom', function(e) {
console.log("CHANGED CUSTOM");
//Check ALL other checkboxes starting with that class name:
var className = $(this).attr("class");
className=className.replace("atpSelections ", "");
className=className.trim();
className=className.split("-");
//Get current checkbox state
var currentState = $(this).attr("checked");
//Now loop through all other checkboxes starting
//with the same class name and check them:
$("input[class*='"+className[0]+"-']")
.off('change.custom')
.each(function(i){
//THIS IS TRIGGERING "$(".atpSelections").change"!!
if(currentState && currentState=="checked"){
$(this).prop('checked', true);
}else{
$(this).prop('checked', false);
}
});
});
Normally it's okay :)
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
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);
}
});
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...