views:

22

answers:

1

Hi All,

I have assigned a click event to a button, which retrieves a different HTML snippet and injects it into a DIV element using the .html(string) method.

$('#btnClose').click(function(){ 
   $.get('Content.html',function(data) {
      $('#EditCategory').html(data); 
   }); 
});

The Content.html page is as follows:

<button id="btnNewCategory" type="button">Add new category</button>
<script type="text/javascript">
   $('#btnNewCategory').click(alert('Test'));
</script>

Every time I click the '#btnClose' button the HTML snipper content is displayed but the alert('Test') is also fired. I've tried stopPropagation(),preventDefault() and return false; and have had no joy. Can anyone shed any light on what I'm doing wrong???

+1  A: 

Your handler should be like this instead:

$('#btnNewCategory').click(function() {
  alert('Test')
});

What you currently have is firing alert('Test') immediately and trying to assign the result to a click handler, if you want it to run when clicked, use an anonymous function like I have above.

This isn't a propagation issue, read here for a better understanding of that, but a binding one :)

Nick Craver
Well spotted !! I don't know how I missed it !
Click Ahead