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
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 have 5 checkboxes with the same name property relative-view.
I want to assert that all of them are checked. I can do this to check the first and last one
expect(element.find('input[name="relative-view"]').first().prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]').last().prop("checked")).toBe(true);
But I don't know how to check them all. I have tried the following but I get an error saying undefined is not a function
expect(element.find('input[name="relative-view"]')[0].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[1].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[2].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[3].prop("checked")).toBe(true);
expect(element.find('input[name="relative-view"]')[4].prop("checked")).toBe(true);
How can I do this?
[n] notation returns DOM elements which don't have .prop() - that's jQuery API. Use .eq():
var boxes = element.find('input[name="relative-view"]');
expect(boxes.eq(0).prop("checked")).toBe(true);
expect(boxes.eq(1).prop("checked")).toBe(true);
expect(boxes.eq(2).prop("checked")).toBe(true);
expect(boxes.eq(3).prop("checked")).toBe(true);
expect(boxes.eq(4).prop("checked")).toBe(true);
An alternative approach would be to use the standard .checked property:
var boxes = element.find('input[name="relative-view"]').get();
expect(boxes[0].checked).toBe(true);
expect(boxes[1].checked).toBe(true);
expect(boxes[2].checked).toBe(true);
expect(boxes[3].checked).toBe(true);
expect(boxes[4].checked).toBe(true);
Also, try just iterating over the jQuery collection:
$('input[name="relative-view"]', element).each(function () {
expect(this.checked).toBe(true);
});
You can write a function which will go through all checkboxes and return false if any of them is not checked. Use:
function CheckAllCheckboxes(){
var _RetValue = true;
$('input[name="relative-view"]').each(function(){
if($(this).prop("checked") != true)
_RetValue = false;
return false; // quit from each()
}
return _RetValue;
}
Then you can use
expect(CheckAllCheckboxes()).toBe(true);
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') {
...
}
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);
I have a javascript function that goes something like this:
function doSomething(me) {
var isMeChecked = me.checked;
for (i=0;i<=10;i++) {
me.checked = !isMeChecked;
alert (me.checked);
}
}
I assumed that isMeChecked would remain constant after the first load, but it apparently is a reference variable to me.checked, and so it changes with every iteration.
How do I force isMeChecked to get set to the value of me.checked when it's first loaded, and not the reference of me.checked?
Alright, to make this more clear, I am editing this post to show actual code in use that is exhibiting the undesirable behavior:
Here are the javascript functions:
function CheckAll(me, gridViewId) {
var isMeChecked = (me.checked)?true:false;
alert('CheckAllFired_1');
Parent = document.getElementById(gridViewId);
for (i = 0; i < Parent.rows.length; i++) {
alert('CheckAllFired_2_' + i.toString());
var tr = Parent.rows[i];
var td = tr.childNodes[0];
var item = td.firstChild;
if (item.id != me.id && item.type == "checkbox") {
alert('CheckAllFired_3_' + i.toString() + '_' + me.checked + '_' + isMeChecked);
item.checked = !isMeChecked;
item.click();
}
}
}
function CheckSelectAll(me, checkBoxHeaderId, gridViewId) {
alert('CheckSelectAllFired_1');
if (!me.checked) {
alert('CheckSelectAllFired_2');
document.getElementById(checkBoxHeaderId).checked = false;
return;
}
else {
alert('CheckSelectAllFired_3');
document.getElementById(checkBoxHeaderId).checked = true;
Parent = document.getElementById(gridViewId);
for (i = 0; i < Parent.rows.length; i++) {
alert('CheckSelectAllFired_4_' + i.toString());
var tr = Parent.rows[i];
var td = tr.childNodes[0];
var item = td.firstChild;
if (item.type == "checkbox") {
alert('CheckSelectAllFired_5_' + i.toString());
if (!item.checked) {
alert('CheckSelectAllFired_6_' + i.toString());
document.getElementById(checkBoxHeaderId).checked = false;
return;
}
}
}
return;
}
}
I have an asp.net gridview. The first column is a column of checkboxes, with a checkbox in the header as well that toggles "Select/Deselect All" of the other checkboxes in the column.
The checkbox in the header has it's onclick event set to onclick="CheckAll(this, 'myGridViewClientID')"
All of the remaining checkboxes in the grid, have their onlick event set to onclick="CheckSelectAll(this, 'headerCheckBoxID', 'myGridViewClientID'"
Both the headerCheckBoxID and myGridViewClientID are set in the codebehind when the gridview is rendering.
The idea is that when the checkbox in the header is checked, it will set all the other checkboxes to the opposite checked status, and then fire their click event to simulate a click, and also fire their onclick actions (which involve things like changing the color of their row, setting the datakey of the row into a SelectedValues array if it is checked, etc).
However, I also wanted the child checkboxes to have the following behavior:
1) If any of them get unchecked, uncheck the "select all" checkbox.
2) If all of them get checked, check the "select all" checkbox.
Now, because the click event of the child checkboxes has the opportunity to change the checked status of the headercheckbox, when the loop returns back to the "checkall" event, the state of the headercheckbox is different than when it first started, and so it ends up only checking the first child checkbox when trying to do a select all.
Using alerts, I was able to see that when the checked state of the headercheckbox is changed in the CheckSelectAll function, that value is also changed for the "isMeChecked" value in the CheckAll function which is spawning the CheckSelectAll functions.
That looks an awful lot like a reference variable then. I don't know how to stop it from doing that.
Think about it. assume x.checked = true. run doSomething(x).
When the function starts, me.checked is true. Now look at your for loop:
Pass 1: me.checked is true. so isMeChecked is true. so you set me.checked to false.
Pass 2: me.checked is false. isMeChecked is still true, because you don't change it inside the loop. so me.checked is again set to false.
Pass 3: see pass 2.
...
When the function exits, isMeChecked is true, and me.checked is false. All you have done is set me.checked to false 10 times.
This is not a matter of isMeChecked being a reference (because it's not), but just an error in your logic if you were expecting different results.
Unless I'm crazy, there's no such thing as a reference to a boolean in javascript. They're always passed by value. Can you paste complete example code that we can run without filling in any blanks?
Your loop is just broken -- Read the comments
// doSomething({checked:true});
function doSomething(me) {
// isMeChecked = true;
var isMeChecked = me.checked;
for (i=0;i<=10;i++) {
// me.checked = false ... always...
me.checked = !isMeChecked;
alert (me.checked);
}
}
You could do var isMeChecked = me.checked?true:false;
Also, me.checked != isMeChecked is not the same as me.checked = !isMeChecked, which is probably what you intended.