2

For some reason, the following code does not work properly:

<input onclick="$(function(){ alert($(this).attr('checked')); })" name="step1[agree]" id="step1_agree" value="1" type="checkbox">

It alerts with undefined. I have also tried doing something like this:

onclick="$(function(){ var chk=$(this); alert(chk.attr('id')); })"

... but ends up with the same result. What am I doing wrong and how can I fix this?

0

6 Answers 6

5
<input onclick="alert($(this).attr('checked'));" name="step1[agree]" id="step1_agree" value="1" type="checkbox">

But a better option would be

<input name="step1[agree]" id="step1_agree" value="1" type="checkbox">

$('#step1_agree').click(function() {
  alert($(this).attr('checked));
});
Sign up to request clarification or add additional context in comments.

1 Comment

Please prepend # to your selector
3

This should work.

onclick="alert(this.checked);"

Comments

2

Please learn about binding in jQuery.

$('#step1_agree').bind('click', function() {
    alert(this.checked);
});

Comments

1

Not sure why you are wrapping it in a function like that. It should just be

onclick="alert($(this).attr('id'));"

Comments

0

Seems you have to use the following:

<script type="text/javascript">
    $(function(){
$('#step1_agree').click(function(){
alert('')
});
}) 
</script>

Comments

0

Please refer to unobtrusive javascript

You can use something like

$(function(){
    $("#step1_agree").click(function(){
       alert (this.checked); 
    });
});

$(function(){ }); gets fired once the DOM is ready.

You must assign all event handlers inside document ready. You can use an id selector to attach a click event handler to the desired element. To get the checked attribute you can use the native javascript code this.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.