4

I want after click on link append html input checkbox in a class, after it when clicked on input checkbox getting alert is checked.

I tried as following code but dont work for me:

DEMO: http://jsfiddle.net/HsveE/

HTML

<a href="#" id="ho">Click Me</a>
<div class="hi"></div>

jQuery

$('#ho').on('click', function(e){
    e.preventDefault();
    $('.hi').append('<input type="checkbox" id="isAgeSelected"/>');
})
$(".hi input[type=checkbox]").on('click',function () {
    alert('is checked')
})

How can fix it?

1
  • 1
    delegation... or bind after append Commented Jan 24, 2013 at 21:13

3 Answers 3

2

You need to delegate since your element doesn't exist at the time of binding - or bind after element does exist

$(".hi").on('click',"input[type=checkbox]",function () {
    alert('is checked')
})

http://jsfiddle.net/5dYwG/

Doing this binds the event handler to your element/elements with class=hi - since it exists at the time the dom is ready and is the element you are appending your checkboxes to. It will then listen for the event as it bubbles up from your checkboxes and handle them.

One other thing is to always wrap your binding inside a document.ready function so it will wait until your dom is loaded before trying to bind the event handlers.

$(function(){
   // your binding code here
})

EDIT

$(".hi").on('click',"input[type=checkbox]",function () {
  if(this.checked){
    alert('is checked')
  }
})

FIDDLE

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

1 Comment

because you are alerting everytime it is clicked.. If you only want it to alert when it's checked then you need an if statement
0

Use this...

$(".hi").on('click',"input[type=checkbox]",function () {
    if($(this).is(':checked')){
        alert('is checked');
    }
})

Greetings.

Comments

0

Here is the solution.

$('#ho').on('click', function(e){
  e.preventDefault();
  $('.hi').append('<input type="checkbox" id="isAgeSelected"/>');
});
$(".hi").on('click', '#isAgeSelected', function () {
  alert('is checked = ' + this.checked)
});

Also fiddle if you like to try http://jsfiddle.net/greenrobo/3Rugn/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.