This question already has an answer here:
I have a 'test.html' and a 'test.php' files.
The 'test.html':
<html>
<head>
<script type="text/javascript" src="/js/jquery-1.8.2.js"></script>
</head>
<body>
<p>Hello</p>
</body>
</html>
<script type="text/javascript">
$(function() {
$("p").on('click', function() {
$(this).load("test.php");
$(this).off();
});
});
</script>
<script type="text/javascript">
$(function() {
$("#sel_1").on('change', function() {
alert("SELECT changed!");
});
});
</script>
And the 'test.php':
<?php
echo "<select id='sel_1'>";
echo "<option>one</option>";
echo "<option>two</option>";
echo "<option>three</option>";
echo "</select>";
?>
When i click the 'p' item (Hello), then the jQuery load a new content into 'p'.
But when i change a select item, I would like to see the alert messages, but it will not appear. How can I solve this?
</div>
This should work:
<script type="text/javascript">
$(function() {
$('body').on('change', "#sel_1", function() {
alert("SELECT changed!");
});
});
</script>
As others mentionned, you need to use event delegation.
Here is a small example:
html:
<div>
Hello
</div>
<button> Add Content </button>
javascript:
$(function () {
$("button")
.on('click', function () {
$("div")
.append(getSelect());
});
$("div")
.on('change', '.mySelects', function () {
alert('select changed!');
});
});
function getSelect() {
return $("<select></select>")
.addClass("mySelects")
.append($("<option></option>")
.html("abc")
.val("1"))
.append($("<option></option>")
.html("def")
.val("2"));
}