Reputation: 88
im having trouble about the on('click')
event, i have a button
that comes from ajax
that has a click event
but when i tried clicking it nothing happens the expected output is showing an alert
after clicking the button. I tried to test putting the button directly to the html and it worked. Can someone help me about this?
PS: There are no errors in the console
and network
initializing.
$( document ).ready(function() {
init();
});
function init()
{
sendmessage();
viewhotel();
getresorts();
}
Function when button is click
function viewhotel()
{
$('#viewinfo').on('click', function() {
alert('asd');
});
}
ajax code where button came
$output .= '<div class="hotel-container">
<div class="row">
<div class="col-md-4">
<img src="admin/'.$row['main_picture'].'"class="img-responsive hotelpic">
</div>
<div class="col-md-5">
<h5 class="hotelname">'.$row['resort_name'].'</h5>
<h5 class="address"><i class="fa fa-map-marker" aria-hidden="true"></i> '.$row['resort_address'].'</h5>
</div>
<div class="col-md-3">
<h5 class="price">₱ '.$row['resort_total_cost'].'</h5>
/*here's the button*/ <button class="btn btn-warning" id="viewinfo">View more info</button>
</div>
</div>
</div>';
Upvotes: 0
Views: 163
Reputation: 1
The on('click') event will work while you specify the dynamically created button id with the parent div that you're going to append. Suppose I have a target div with an id #traget. and am going to add a button dynamically with an id #viewinfo, Then the code will be
$("#target").on("click", "#viewinfo", function(){
/*--- Do Rest----*/
});
Upvotes: 0
Reputation: 824
In case of one future element, calling viewhotel
after the AJAX call makes sense, but in cases where multiple such elements will be added (or there are some existing elements and more elements will be added), it makes more sense to bind the event thus:
function viewhotel()
{
$(document).on('click', '#viewinfo', function() {
alert('asd');
});
}
Used this way, on
will bind the event to existing and future elements in the document.
Upvotes: 0
Reputation: 687
The event needs to be bound after the html is placed on the page (in DOM).
On success of your ajax call, call the method "viewhotel()" to bind the event.
Upvotes: 2