RayLoveless
RayLoveless

Reputation: 21058

check if a checkbox is checked jquery

Does anyone know why this isn't working. It will always print 'unchecked'.

<html>
<head>
<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">

function msg(x)
{

if($(x).attr('checked')){
  alert('checked!!');
}
else{
  alert('unchecked');
}

}

</script>


</head>
<body>

<form>
<input type="checkbox" id="fname2" onClick="msg(this.id)" /><br/>

</form>

</body>
</html>

Upvotes: 0

Views: 973

Answers (3)

Poly
Poly

Reputation: 21

Use

function chkChecked(elmt) {
    if($(elmt).is(':checked')) {
        alert('checked!!');
    }
    else alert('unchecked');
}

Upvotes: 2

WolfRevoKcats
WolfRevoKcats

Reputation: 294

You need a # to tell jQuery that you want to select an id X rather than an element X.

if($('#'+x).attr('checked'))

Or, if you change onClick="msg(this.id)" to onClick="msg(this)" you can use:

if($(x).attr('checked'))

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227240

You are sending this.id to the function, then you are wrapping it in the $(). This does not work. You need just to send this to msg: onClick="msg(this)".

Upvotes: 6

Related Questions