Don Sky Don Sky - 1 year ago 70
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 = "";

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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download