Reputation: 116
jquery change function on radio button is working properly when they are part of html body i.e when they have written in html body, but when they loaded through ajax request change function not works. My code is- html code
<form>
<select id="sel" name="sel">
<option value="">Select Type</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="load"></div>
<label id="change">--</label>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.radi').change(function(){
console.log( "radio clicked!" );
$('#change').html("Loaded2: ");
});
$("#sel").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax ({
type: "POST",
url: "faculty.ajax_load.php",
data: dataString,
cache: false,
success: function(html){
$("#load").html(html);
console.log( "radio loaded" );
}
});
});
});
</script>
ajax_load.php is:-
<?php
echo '<input class="radi" type="radio" name="sect" value="P" id="p"/>
<input type="radio" class="radi" name="sect" value="A" id="a" checked="checked"/>';
?>
Now the problem is radio buttons are appear but when I click them change is not shown on console and label. Please help, where I am doing mistake.
Upvotes: 0
Views: 789
Reputation: 133403
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.
As you are loading using ajax call.
You need to use Event Delegation. You have to use .on() using delegated-events approach.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
General Syntax
$(document).on(event, selector, eventHandler);
Ideally you should replace document
with closest static container.
As per your code
$("#load").on('change', '.radi', function(){
console.log( "radio clicked!" );
$('#change').html("Loaded2: ");
});
Upvotes: 1