Javascript + jquery checkbox validation? - javascript

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;
}

Related

How to check for attribute value

Please advise me if I am using correct syntax here for checking if “aria-expanded” is true for a particular set of elements with css class “classname”:
if ($(‘.classname’).hasAttribute('aria-expanded','true')) {
 output here
}
jQuery doesn't have a hasAttribute method, so I'm assuming $ = docuument.querySelector. (Note: not document.querySelectorAll; so, you're only considering a single element).
The hasAttribute method takes a single parameter: the name of the attribute you are checking for. To check that attribute's value, you'll need to use getAttribute and then compare that. So you might do:
if( $('.classname').getAttribute('aria-expanded') === 'true') {}
If you are using jQuery, then you can just use the attr method:
if ($('.classname').attr('aria-expanded') === 'true') {}
See also the MDN docs for hasAttribute.
If you're trying to check a set of elements, you could do something like this:
function allHaveAttribute(elements, attrName, attrValue) {
// First, check that all elements have the attribute
for (var i = 0; i < elements.length; i++) {
if (!elements[i].hasAttribute(attrName)) return false;
}
if (attrValue) { // if we're checking their value...
for (var i = 0; i < elements.length; i++) {
if (elements[i].getAttribute(attrName) !== attrValue)
return false;
}
return true;
} else { // we know all elements have the attribute
return true;
}
}
var els = document.querySelectorAll('.classname');
if (allHaveAttribute(els, 'aria-expanded', 'true') {
// action here
}
JSBin Example: http://jsbin.com/payaqijeqa/edit?js,console
jQuery doesn't have a .hasAttribute function
If it did, it would most likely only work on the first of the set
The following uses native JavaScript (ES5) to check that .every element in the set document.querySelectorAll('.classname') has that attribute set to true.
let allSet = [].every.call(document.querySelectorAll('.classname'), function(el) {
return el.getAttribute('aria-expanded') === 'true';
});
NB: the above test is case sensitive. It also ignore any elements that don't have that attribute at all. If the latter is an issue:
let allSet = [].every.call(document.querySelectorAll('.classname'), function(el) {
return el.hasAttribute('aria-expanded') && el.getAttribute('aria-expanded') === 'true';
});
You can check to see if every element with class "className" has the attribute "aria-expanded='true'" with:
if( $(".className").length === $(".className").filter("[aria-expanded='true']").length) {
//output here
}
CSS has attribute selectors that allow selection of elements with certain attributes. If you negate the selector (which is unique to jQuery), you can test if there are any elements that have the class but don't have the attribute value by using:
$(".className[aria-expanded!='true']").length == 0

Asserting all checkboxes are checked

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);

How to add class to a jQuery element if a condition is true and remove the same class if the condition is false?

Is there a shorter way to do the following?
var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");
if (is_checked) {
select_all_checkbox.parent().addClass("selected");
} else {
select_all_checkbox.parent().removeClass("selected");
}
Use toggleClass, passing a second argument (a boolean) that specifies whether the class should be added or not:
select_all_checkbox.parent().toggleClass("selected", is_checked);
If you have multiple elements selected by input.select_all, you have to iterate over them though:
$("input.select_all").each(function() {
$(this).parent().toggleClass('selected', this.checked);
});
Absolutely! You can choose between the methods (addClass/removeClass) programmatically, and use the one that is returned when an expression is executed.
Like this:
var select_all_checkbox = $("input.select_all");
var is_checked = select_all_checkbox.prop("checked");
select_all_checkbox.parent()[is_checked ? "addClass" : "removeClass"]("selected");

How to know whether checkbox is checked or not, jquery?

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

Javascript equality weirdness

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);

Categories