Don Sky Don Sky - 4 months ago 8
jQuery Question

Why jquery selector alway return true in If condition?

Why does this always return true?

<input type="checkbox" name="c1" id="c1" value="&controls=0">Hide Controls


if ($('input[name=c1]:checked')){
var controls = $('#c1').val();
} else {
var controls = "";
}
alert(controls);


Is it a problem with value? But as you see I need a value...

Answer

Jquery selector return an object and selector object alway is true.

If you want to check existence of element, you can use .is() method or .length property.

if ($("input[name=c1]").is(":checked"))
// Or 
if ($("input[name=c1]:checked").length)