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?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
jennifer Jolie
  • 727
  • 6
  • 16
  • 30

3 Answers3

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

wirey00
  • 33,517
  • 7
  • 54
  • 65
  • 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 – wirey00 Jan 24 '13 at 21:31
0

Use this...

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

Greetings.

MG_Bautista
  • 2,593
  • 2
  • 18
  • 33
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/

Chandu Dexter
  • 456
  • 2
  • 4