I'm trying to fetch some data through ajax. One of the data determines whether or not a checkbox should be checked by default. If the returned variable isVisible is 1, then it should be checked, if its 0 then it should be unchecked. Here's the code:
$.getJSON(myUrl, function(result)
{
isVisible = result.isVisible;
// snip...
} );
Later on in the code:
var isChecked = (isVisible) ? true : false;
$("#visible").attr('checked', isChecked);
The problem is that, whether or not isVisible is set to 1 or 0, the checked variable is always being evaluated to true. I'm really not sure what the problem is. Perhaps isVisible is being treated as a string ?? How do I resolve this?
Probably isVisible is a string. "0" is a truthy value in Javascript. Use this instead:
var checked = (isVisible==="1") ? true : false;
How about
isVisible = (result.isVisible == "1")
?
I guess "isVisible" is a string not a number, so it pass the test.
Try parseint(isVisible, 10), an let me know
Ajax is asynchronous. you need to use callbacks.
$.getJSON(myUrl, function(result)
{
isVisible = result.isVisible;
// snip...
callback_setvis();
} );
function callback_setvis(){
var ischecked = (isVisible) ? true : false;
$("#visible").attr('checked', ischecked);
}
After reviewing your question again it seems the above might not work.
This might be an issue of attr vs prop
if you are in jQuery 1.6 or greater you should do:
$("#visible").prop('checked', ischecked);
Related
I have to validate the checkbox.
if($("#update_user_modal #room1").attr('checked', false)) room1Val = 0;
This is working fine. But I have to check if it is not checked also. The else method wont work.
if($("#update_user_modal #room1").attr('checked', true)) room1Val = 1;
This is working also.
BUT! When i use both like this:
if ($("#update_user_modal #room1").attr('checked', false)) room1Val = 0;
if($("#update_user_modal #room1").attr('checked', true)) room1Val = 1;
it works just sometimes.
I tried with .prop also.
What am I doing wrong?
JQuery: Use .is(':checked')
if ($("#update_user_modal #room1").is(':checked') room1Val = 0;
else room1Val = 1;
Javascript: use .checked property of a checkbox.
if document.getElementById('chkboxName').checked room1Val = 0;
else room1Val = 1;
Try to use is(":checked") option.
Your code would look like this:
if (!$("#update_user_modal #room1").is(":checked")) room1Val = 0;
if($("#update_user_modal #room1").is(":checked")) room1Val = 1;
Check documentation for more information.
According to the W3C forms specification, the checked attribute is a
boolean attribute, which means the corresponding property is true if
the attribute is present at all—even if, for example, the attribute
has no value or is set to empty string value or even "false". This is
true of all boolean attributes.
Nevertheless, the most important concept to remember about the checked
attribute is that it does not correspond to the checked property. The
attribute actually corresponds to the defaultChecked property and
should be used only to set the initial value of the checkbox. The
checked attribute value does not change with the state of the
checkbox, while the checked property does. Therefore, the
cross-browser-compatible way to determine if a checkbox is checked is
to use the property:
if ( elem.checked )
if ( $( elem ).prop( "checked" ) )
if ( $( elem ).is( ":checked" ) )
Source
You are not reading the attribute value, but writing it. Don't use the second argument to attr -- only use one:
room1Val = +$("#update_user_modal #room1").attr('checked'))
This will do the two cases in one go, since it returns a boolean. The + makes that a 0 or 1.
Secondly, it is better to use prop over attr for this case:
room1Val = +$("#update_user_modal #room1").prop('checked'))
You should do it like below:
if ($("#update_user_modal #room1").prop('checked')) {
room1Val = 1;
} else {
room1Val = 0;
}
I wrote, what I thought, was a straight forward if statement in JS but it is running incorrectly.
function printLetter(LetterId) {
var studentflag = $("#IsStudent").val();
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
Everytime it runs, the studentflag var value is correct, but regardless of whether it is true or false, it goes into option 1. I am pretty sure I have done true/false checks like this before in JS, but do I need to spell it out (studentflag == true) instead?
This is known as truthy and falsy Values
The following values are always falsy:
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
All other values are truthy:
including "0" (zero in quotes),
"false" (false in quotes) like if (studentflag) //being studentflag "false",
empty functions,
empty arrays, and
empty objects.
If #StudentFlag is either "true" or "false", then if(studentFlag) will always follow the true route because both are non-empty strings (truthy). You need to do something along these lines:
var studentflag = $("#IsStudent").val();
if (studentflag === "true") {
//do option 1
} else {
//do option 2
}
.val () doesn't return a boolean.
Try this instead;
function printLetter(LetterId) {
var studentflag = $("#IsStudent").is (':checked');
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
This is assuming #IsStudent is a checkbox. If it's not, try this (assuming the value is true (as a string, not a boolean));
function printLetter(LetterId) {
var studentflag = ($("#IsStudent").val () == 'true')
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
IMO there should be more context in the question. If submitted solution works for OP that is great, but for others using this as a resource, the accepted solution might not work in all cases.
The value retrieved from an element via JS actually depends on the input itself and its HTML structure. Here's a demo explaining the difference between using .val(), .attr('val'), and .is(':checked') with checkboxes and radios. All of those variants can pull different values from an element depending on its HTML structure and current UI state.
Fiddle : http://jsfiddle.net/h6csLaun/2/
var studentflag = $("#IsStudent").val();//This is a string .. not a boolean
if (studentflag === "true") //therefore this has to be string comparison
Or you can make studentflag boolean as follows:
var studentflag = $("#IsStudent").val() === "true";
if (studentflag) { ....
I have a live -on click- event for a Header which has an arrow flipping up/down upon opening & closing it's contents.
The strangest thing is happening with ! followed by a variable -- which is supposed to flip it from true -> false, and vice versa. Basically it's not working at all, and it flips to false and stays there... Check out the fiddle to see what I mean.
I've deleted lots of code for the sake of brevity.
Demo Code
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).attr('data-state');
if (_state === 'true') {
// do stuff
}
else {
// do stuff
}
// This is where the issue is happening, it isn't flipping the Boolean value
// !"true" = false, !true = false, it works with strings or booleans
$(this).attr('data-state', !_state);
});
I can get it working perfectly fine if I do the following:
if (_state === 'true') {
// Manually flip the data-state boolean
$(this).attr('data-state', false);
}
Is there something I'm missing why this isn't working the way it should ?? Just wondering why it's doing this!
I think you are trying to do this:
http://jsfiddle.net/JKUJb/2/
if so, the problem was that you are using .attr() which returns a string, so if you convert:
!"true" //false
!"false" //false
.data() on the other hand returns the value already "casted
EDIT:
Just to be more clear, in javascript the only falsy values are:
false;
null;
undefined;
'';
0;
NaN;
So if you really wanted to use .attr(), you could, but I recommend that first you do:
var _state = $(this).attr('data-state') === 'true'; //if 'true' then true, false otherwise
Good luck!
Change your second line to:
var _state = $(this).attr('data-state') == 'true';
And in the if statement check for boolean:
if ( _state ) {
// do stuff
...
_state is a String (typeof _state === String //true) you need to convert it to a boolean first
(a String will alwase be true)
If you really want to use data- attributes for this, use jQuery's .data method to retrieve and set the value. It will automatically convert the string "true" into a Boolean, or the string "1" into a number:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).data('state');
if (_state) {
// do something
}
$(this).data('state', !_state);
});
http://jsfiddle.net/mblase75/JKUJb/6/
Or you could toggle a class -- you can use the .hasClass method to return a Boolean:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).hasClass('data-state');
if (_state) {
// do something
}
$(this).toggleClass('data-state');
});
http://jsfiddle.net/mblase75/JKUJb/3/
Is there a better way for checking an attribute for:
it exist. so value must be false if attribute doesn't exist
Value is correct (boolean)
var isOwner = false;
if ($(selectedItem).is('[data-isOwner="True"]') || $(selectedItem).is('[data-isOwner="true"]')) {
isOwner = true;
} else {
isOwner = false;
}
Now I need to check for 'True' and 'true'...
Thanks
You can convert the value stored in data-isOwner to lower case and only compare the value to 'true'.
if (($(selectedItem).attr ('data-isOwner') || '').toLowerCase () == 'true')
The above use of <wanted-value> || '' will make it so that if the selectedItem doesn't have the attribute data-isOwner the expression will result in an empty string, on which you can call toLowerCase without errors.
Without this little hack you'd have to manually check so that the attribute is indeed present, otherwise you'd run into a runtime-error when trying to call toLowerCase on an undefined object.
If you find the previously mentioned solution confusing you could use something as
var attr_value = $(selectedItem).attr ('data-isOwner');
if (typeof(attr_value) == 'string' && attr_value.toLowerCase () == 'true') {
...
}
Is there any better way to do this :
var IsC = $('input[type=checkbox]').attr("checked") == "checked" ? true : false;
?
You can use the :checked selector
var IsC = $('input[type=checkbox]').is(":checked");
Or :
var IsC = $('input[type=checkbox]:checked').length>0;
$("input[type=checkbox]").is(":checked")
var IsC = $('input[type=checkbox]').attr("checked") == "checked" ? true : false;
is the same as just saying:
var IsC = $('input[type=checkbox]').attr("checked") == "checked";
since == will return true or false. (purely a javascript change)
The jQuery optimization (in terms of number of characters, at least) is:
var IsC = $('input:checkbox').is(':checked');
//returns true if at least one checkbox in the document is checked
You can add a scope for the comparison by telling the selector where the input should be found:
var IsC = $('#myForm input:checkbox').is(':checked');
One way is to use solution posted by dystroy.
Another is to use prop method instead of attr. Check examples at http://api.jquery.com/prop/
elem.checked
// true (Boolean) Will change with checkbox state
$(elem).prop("checked")
// true (Boolean) Will change with checkbox state
elem.getAttribute("checked")
// "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked") //(1.6)
// "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked") //(1.6.1+)
// "checked" (String) Will change with checkbox state
$(elem).attr("checked") //(pre-1.6)
// true (Boolean) Changed with checkbox state