Reputation: 13128
I've run into an issue with my jQuery.
Basically I pick up on a form submit and using jQuery Post to my api.
Now if items are found, each
is used to created a table with the displayed data which can then be accessed by a user.
$('#update-postcode').submit(function(){
$('#location-set-content').html('');
event.preventDefault();
var form = $(this).serialize();
// Request
$.post('/api/postcode/check',
form,
function(data) {
// check response
$.each(data,function(k,v) {
var status = $.trim(data.status);
if(parseInt(status) < 1){
// remove the status
delete data.status;
$('#location-set-content').html('<h1 class="text-center">Unable to Find Location :(</h1>');
} else if(parseInt(status) == 1) {
// remove the status
delete data.status;
var output = '<table class="table table-bordered"><thead><tr><th>Postcode</th><th>Area</th><th>State</th><th>Actions</th></tr></thead><tbody>';
$.each(data, function(k, v){
output += '<tr>';
output += '<td>'+ v.postcode +'</td>';
output += '<td>'+ v.area +'</td>';
output += '<td>'+ v.state +'</td>';
output += '<td class="text-center"><a id="set-location" href="#" lid="'+ v.id +'">Set</a></td>';
output += '</tr>';
});
output += '</tbody></table>';
$('#location-set-content').append(output);
}
});
});
return false;
});
The table is created no problems - now as you can see there is one last field - <a id="set-location" href="#" lid="'+ v.id +'">Set</a>
This should run be accessible through:
$('a#set-location').on('click', function(){
event.preventDefault();
var lid = $(this).attr('lid');
// Request
$.post('/api/postcode/set',
{
lid: lid
},
function(data){
if(data.status == 0) {
notification('location-set-content', data.response.message, 'danger', 0);
} else if(data.status == 1){
notification('location-set-content', data.response.message, 'success', 0);
go_to('/user/settings#location', 700);
}
console.log(data);
});
return false;
});
But this will not work unless it is within the each
of the initial request.
So basically the only way it will work is if the $('#id').on('click')
function is inside the original submit
.
How would I go about fixing this as the issue being caused is multiple ajax requests when more than 1 item is returned from the first request.
Upvotes: 1
Views: 79
Reputation: 37520
It sounds like you're binding to the click
event for a#set-location
on page load. At that point there aren't any matching elements to bind to. What you want to do is attach the handler further up the DOM on an element that exists at document ready. Perhaps something like this:
$('#location-set-content').on('click', 'a#set-location', function(){
or even...
$(document).on('click', 'a#set-location', function(){
Upvotes: 2