Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  184] [ 3]  / answers: 1 / hits: 15242  / 12 Years ago, fri, september 7, 2012, 12:00:00

I have a page where some html is being dynamically added to the page.



This is the html and javascript that is created:



<div>
<script type=text/javascript language=javascript>
$('#btn').click(function() {
alert(Hello);
});
</script>

<a id=btn>Button</a>
</div>


Looking in my Firebug console, I get an error that says:




TypeError: $(#btn) is null




jQuery is being loaded on the page initially.



What am I doing wrong here?


More From » jquery

 Answers
24

You have to bind on() (or the events defined within the on() method, to an element that exists in the DOM at the point at which the jQuery was run. Usually this is on $(document).ready() or similar.



Bind to the closest element in which the $('#btn') element will be appended that exists in the DOM on page-load/DOM ready.



Assuming that you're loading the $('#btn') into the #container div (for example), to give:



<div id=container>
<div>
<a href=# id=btn>Button text</a>
</div>
</div>


Then use:



$('#container').on('click', '#btn', function(){
alert('Button clicked!');
});

[#83186] Thursday, September 6, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sheylap

Total Points: 141
Total Questions: 99
Total Answers: 99

Location: Sint Maarten
Member since Tue, Mar 29, 2022
2 Years ago
;