0

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> 

3 Answers 3

6

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)".

Sign up to request clarification or add additional context in comments.

1 Comment

If you want to send IDs to msg, you need to do: $('#'+x).
2

Use

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.