I’m playing (read: initial foray into) with jQuery and making a simple note taking application. Right now, I’m pulling content from a database ala ajax and inserting that into the page.
However, when I try and do a simple callback for .click() on the dynamic content (save button), it does not work. The intention is to send the content back up to the database to be stored.
If I take that same content that I’m having jquery whip up dynamically and just toss that statically in the HTML that the webserver is sending down, it does work. I don’t understand why one works and the other does not.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<link rel="stylesheet" type="text/css" href="layout.css" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<!--Get notes out of database and show them-->
<script type="text/javascript">
$(function()
{
$.ajax({
url: 'noteGet.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows) {
var noteId = rows[i][0];
var noteContent = rows[i][2];
$('#allNotes')
.append('<span id="stickyNote'+noteId+'" class="stickyNote"><textarea id="stickyNoteTextArea'+noteId+'" class="stickyNoteTextArea">'+noteContent+'</textarea><a href="#" id="stickyNoteSave'+noteId+'">save</a></span>')
}
}
});
//works
$('#stickyNoteSave1').click(function() {
alert("save button clicked");
});
//does not work
$('#stickyNoteSave13').click(function() {
alert("save button clicked");
});
});
</script>
<!--
<script type="text/javascript">
$('#noteForm').submit(function(event) {
event.preventDefault();
$.post("notePost.php", $('#noteTextArea').serialize(), function(data) {
alert(data);
});
});
});
</script>
-->
</head>
<body>
<span id="allNotes">
<!---The .click callback with the jquery selector works for only this span!-->
<span id="stickyNote1" class="stickyNote"><textarea id="stickyNoteTextArea1" class="stickyNoteTextArea">fake</textarea><a href="#" id="stickyNoteSave1">special save</a></span>')
</span>
</body>
</html>
When you bind an event, the event is attached to the DOM element matched by your selector. If the element doesn’t exist yet, nothing is bound.
The solution is to use a delegate:
#containershould be an element containing the newly inserted elements (could bedocument, but something more specific is better) and.elementselectorshould be a selector matching the elements you actually want the events for, e.g.#stickyNoteSave13