performing JavaScript action on $.post()
-
26-04-2021 - |
Pregunta
Here's my JavaScript code on my "test" page.
$('#link_share_input').keyup(function () {
var link_share_input = $(this).val();
if (link_share_input != '') {
$.post('http://' + window.location.hostname + '/assets/scripts/ajax_dashboard_dynamic_preview.php', {
preview_type: 'link',
link_share_input: link_share_input
}, function (data) {
if (data !== "") {
$('.link_preview_span').show();
$('.link_attachment_preview').html('<div class = "center" style = "padding: 10px 0"><img src = "http://www.assets.buddyweb.me/style_images/loading.gif"></div>');
$('.link_attachment_preview').html(data);
} else {
$('.link_preview_span').hide();
}
})
}
})
$('#video_url_input').keyup(function () {
var video_url_input = $(this).val();
if (video_url_input != '') {
$.post('http://' + window.location.hostname + '/assets/scripts/ajax_dashboard_dynamic_preview.php', {
preview_type: 'video',
video_url_input: video_url_input
}, function (data) {
if (data !== "") {
$('.link_preview_span').show();
$('.link_attachment_preview').html('<div class = "center" style = "padding: 10px 0"><img src = "http://www.assets.buddyweb.me/style_images/loading.gif"></div>');
$('.link_attachment_preview').html(data);
} else {
$('.link_preview_span').hide();
}
})
}
})
the #link_share_input
and #video_url_input
div's comes from a file which is $.post
ed onto the page. Unless I put the above JavaScript onto the page it is $.post
ed from it will work.
How can I get this JavaScript to work on the data $.post
ed from a file to the "test" file?
Solución
Change $('#link_share_input').keyup
to..
$(document).on('keyup', '#link_share_input', function(e) { ... });
This basically drops an event listener on document, and whenever the keyup event is fired and the target matches #link_share_input
it will then fire your event callback. Because you're modifying the HTML over $.post and such it works exactly like you would expect.
Quick note: This requires jQuery 1.7 and above. There are other, equivalent methods for older versions of jQuery, .delegate
and .live
.