I have the following javascript code:
$(document).ready (function()
{
setInterval("RepeatedlyCallUpdate()",10000);
// Other code
$('#btnRefresh').click(function(e){
e.preventDefault();
alert ("Test");
});
// Other code
});
function RepeatedlyCallUpdate() {
$.ajax({
url: "/getdled.php",
data: "user=success",
success: function(msg){
console.log(msg);
var oldhtml=$("#Downloaded").html();
if ( msg !== oldhtml ) {
$("#Downloaded").html(msg);
}
}
});
}
The html code for #Downloaded:
<div id="Downloaded"><h3 style="padding-left:20px;">Downloaded files</h3>
</div>
At runtime, the #Downloaded div block is populated with html code so that it becomes this:
<div id="Downloaded"><h3 style="padding-left:20px;">Downloaded files</h3>
<ul class="nav nav-pills">
<li>
<button style="margin-left: 15px;" class="btn btn-primary refreshbtn" type="button" id="btnRefresh">
Refresh
</button>
</li>
</ul><div>
<div class="row">
<div style="margin-left: 15px;" class="col-md-4">
Some link</div>
<div class="col-md-1">314M</div>
</div>
</div>
</div>
The issue is that my #Downloaded button click event does not fire. What am I missing?
You can use event delegation
$("#Downloaded").on('click', '#btnRefresh', function(){
alert("lol");
});
Related
I'm using ajax to make a request and open a modal bootstrap window afterwards. The problem is that when I use ajax, I make a request to my controller, and the return (modal content) I load as follows:
//modal loading
$('#contentModalFinanceiroParcela').html(data);
//exibição da modal
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
So far, everything perfect. The problem is that from then on, I can't bind the form to register the submit event of the form. In the function bindFormFinanceiroParcela, no matter how much I pass the "dialog", bind does not work.
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
Searching the forums, I found that the process works if I load the modal using the "load" command, as below, but I can't do it like that, otherwise it will make a second request to the controller, because previously, I already used ajax .
//That way it works, but I can't use it.
$('#contentModalFinanceiroParcela').load(url, function () {
$('#modalFinanceiroParcela').modal({
keyboard: true
}, 'show');
// Inscreve o evento submit
bindFormFinanceiroParcela(this);
stopLoadPage();
});
Is there a possibility that I can bind the form without using the "load" command mentioned in the script above?
function openModalFinanceiroParcelaSemURL(data) {
startLoadPage();
//Create the modal window block in the body of the page
if (!$("#modalFinanceiroParcela").data('bs.modal'))
CreateModalFinanceiroParcela();
//Load modal content via ajax request
$('#contentModalFinanceiroParcela').html(data);
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
stopLoadPage();
}
function bindFormFinanceiroParcela(dialog) {
$('form', dialog).submit(function (e, i) {
if ($(this).valid() || i) {
startLoadOneMoment();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
window.location = window.location;
} else {
$('#contentModalFinanceiroParcela').html(result);
bindFormFinanceiroParcela();
}
stopLoadOneMoment();
}
});
return false;
} else {
return false;
}
});
function CreateModalFinanceiroParcela() {
var html = '<div class="modal modal-primary modal-system" tabindex="-1" role="dialog" id="modalFinanceiroParcela" data-backdrop="static"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="content-modal-system" id="contentModalFinanceiroParcela"></div></div></div></div>';
$("body").append(html);
}
RAZOR DELETE:
#using Retaguarda.Domain.Enuns
#model Retaguarda.Application.ViewModels.Financeiro.FinanceiroParcela.FinanceiroParcelaViewModel
#{
ViewData["Title"] = "Excluir Parcela";
Layout = null;
}
<div>
<form asp-action="Delete" id="frm-excluir-financeiro-parcela">
#Html.AntiForgeryToken()
<div class="modal-shadow">
<div class="modal-header modal-header-primary">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4><i class="modal-title text-center glyphicon glyphicon-trash"></i> #ViewData["Title"] </h4>
</div>
<div class="panel">
<div class="panel-body container-fluid pt-15 pl-15 pr-15">
<div class="form-horizontal">
<vc:summary />
<br />
<div class="message-delete">
#Html.HiddenFor(model => model.Id, new { id = "hid-financeiro-parcela-id" })
<i class="icon fa-trash" aria-hidden="true"></i>
<p>
Tem certeza de que deseja excluir a parcela #(Model.Parcela)?<br />
</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-md-offset-2 col-md-10">
<div class="float-right">
<div class="btn-group btn-group-sm mr-auto"
role="group">
<div class="btn-group btn-group-sm" role="group">
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
<button id="btn-excluir-financeiro-parcela" type="button" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>
<button id="btn-cancelar-financeiro-parcela" class="btn btn-danger" data-dismiss="modal"><i class="icon wb-close"></i> Cancelar </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Ajax call
$('#dtFinanceiroParcela').on('click', 'tr .btn-excluir-financeiro-parcela', function (e) {
e.preventDefault();
startLoadOneMoment();
var id = $(this).attr('data-id');
var data = { id: id };
var dataURL = jQuery.param(data);
$.ajax({
url: "/financeiro-parcela-gerenciar/remover-financeiro-parcela/" + id,
type: "GET",
// data: dataURL,
contentType: "application/json",
async: false,
success: function (result) {
if (typeof result.success !== 'undefined') {
if (!result.success) {
stopLoadOneMoment();
swal("Oops", result.message, "error");
return false;
}
}
// alert(this.url);
stopLoadOneMoment();
openModalFinanceiroParcelaSemURL(result);
return false;
},
error: function () {
stopLoadOneMoment();
alert("Oops! Algo deu errado.");
return false;
}
});
Your form inside razor does not contain any submit button because its commented out.
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
Remove the comment or change the type of the other button to "submit"
I guess the submit event is attached successfully but never called due to the missing submit button inside your form.
How can I add an HTML element received via AJAX to another HTML element previously added via AJAX? I tried to use .append but not working:
Example:
$.ajax({ (...), success: function() { $('.padding').append('<div id="request">Foo</div>') } });
This above working well, because .padding is initially loaded on the page. But when I try
$.ajax({ (...), success: function(data) { $('#request').append('<div class="description">Bar</div>') } });
not working. Why and how can I do it the right way?
Below, my .padding content:
<div class="padding">
<!-- Below, HTML result from first AJAX -->
<div class="ui attached segments" id="request">
<div class="ui right center aligned segment" id="header">
<h4 class="ui gray header"> P2017003</h4>
</div>
<div class="ui stackable three item menu segment">
<div style="justify-content: flex-start" class="item">
<button class="ui button">
<i class="left chevron icon"></i>
Voltar
</button>
</div>
<div class="item">
<!--Buttons AJAX-->
<div class="two ui red inverted small buttons segment-controller">
<button id="detalhes" class="ui active button">
Detalhes
</button>
<button id="acompanhar" class="ui button">
Acompanhar
</button>
</div>
</div>
<div style="justify-content: flex-end" class="item">
<button class="ui button">Imprimir</button>
</div>
</div>
<div class="ui main segment">
P-2017-003
</div>
</div>
</div>
I've rigged up this setup to simulate your situation. I've never once encountered the situation where the div with id request is not present in the DOM.
function getDataA() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1'
}).then(result => {
$('.padding').append('<div id="request">Call A finished</div>');
});
}
function getDataB() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/2'
}).then(result => {
if ($('#request').length === 0) {
console.log('no request element found');
}
$('#request').append('<div class="description">Call B finished</div>');
});
}
getDataA()
.then(getDataB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="padding"></div>
My guess is your second call is done before the first call. Perhaps your code is something like this:
getDataA();
getDataB();
Now you're depending on which call finishes first. When call B finishes first your code breaks and when call A finishes first you're in luck.
You could run both requests in parallel if you want, it will require using $.when().
function getDataA() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1'
});
}
function getDataB() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/2'
});
}
$.when(getDataA(), getDataB())
.then(function(resultA, resultB) {
$('.padding').append('<div id="request">Call A finished</div>');
$('#request').append('<div class="description">Call B finished</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="padding"></div>
I've tried it with your provided HTML and I still am not able to reproduce the situation.
function getDataA() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1'
}).then(result => {
$('.padding').append(`
<!-- Below, HTML result from first AJAX -->
<div class="ui attached segments" id="request">
<div class="ui right center aligned segment" id="header">
<h4 class="ui gray header"> P2017003</h4>
</div>
<div class="ui stackable three item menu segment">
<div style="justify-content: flex-start" class="item">
<button class="ui button">
<i class="left chevron icon"></i>
Voltar
</button>
</div>
<div class="item">
<!--Buttons AJAX-->
<div class="two ui red inverted small buttons segment-controller">
<button id="detalhes" class="ui active button">
Detalhes
</button>
<button id="acompanhar" class="ui button">
Acompanhar
</button>
</div>
</div>
<div style="justify-content: flex-end" class="item">
<button class="ui button">Imprimir</button>
</div>
</div>
<div class="ui main segment">
P-2017-003
</div>
</div>
`);
const
trigger = document.getElementById('detalhes');
trigger.addEventListener('click', getDataB);
});
}
function getDataB() {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/2'
}).then(result => {
if ($('#request').length === 0) {
console.log('no request element found');
}
$('#request').append('<div class="description">Call B finished</div>');
});
}
const
trigger = document.getElementById('fill-padding');
trigger.addEventListener('click', getDataA);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="fill-padding" type="button">Fill padding</button>
<div class="padding">
</div>
So, the issue is that jQuery hasn't update it's internal structures yet.
Sometimes this happens when appending elements, and trying to find them right away.
Instead do one of the 3:
Use jQuery.find() instead (eg: $("body").find("#id"))
Store the element html as a jQuery object:
var html = 'Hi';
var elem = $(html);
"Accumulate' the html all at once, and append it all at once.
var html = '';
$.ajax({ (...), success: function() {
html += 'Foo';
$.ajax({ (...), success: function(data) {
html += 'Bar';
$('.padding').append(html);
}
});
}
});
I write jsp code and run code by tomcat. tag button in tag form . Code JSP like that:
<form action="" method="get">
<div class="minicart">
<span class="item"><b>0</b> ITEM /</span> <span class="price"><b></b></span>
<div class="cart_drop">
<span class="darw"></span>
<div class="minicart">
<span class="item"><b>0</b> ITEM /</span> <span class="price"><b>$ 0 VND</b></span>
<div class="cart_drop">
<span class="darw"></span>
<ul>
<li>Mời Bạn Hãy Mua Hàng Của Chúng Tôi</li>
<div class="cart_bottom">
<div class="subtotal_menu"><small>Tổng Cộng:</small><big>$ 0 VND</big></div>
Checkout
</div>
</ul>
</div>
</div>
</div>
</div>
<div class="add_to_buttons">
<button id="addToCart" class="add_cart" name="3">Add to Cart</button>
</div>
When i click button have id="addToCart" , then source code in file mutation-summary.js is call return re-load this page. I don't want re-load this page when i click button. I don't no why? And file matation-summary.js is not in my source. Here code when i click button have id="addToCart".
$("#addToCart").click(function(event){
$.ajax({
type: "POST",
url: "../gioHang",
data: dataString,
cache: false,
success: function (html) {
// xử lý lại chỗ này!!!
//dataString= 'searchword='+ '';
if(html.indexOf("alert") > 0){
var temp= $(".minicart").children();
$(".minicart").empty();
$(".minicart").append(html);
var length= temp.length;
var temp2= temp[length-2];
var temp3= temp[length-1];
//$(".minicart").append(temp[1]);
$(".minicart").append(temp2);
$(".minicart").append(temp3);
}else{
$(".minicart").empty();
$(".minicart").append(html);
}
var dem=1;
$(".minicart").click(function(){
if(dem %2 !=0){
$(".cart_drop").css({"display": "block"});
dem=2;
}else{
$(".cart_drop").css({"display": "none"});
dem=1;
}
});
}
});
});
The default type for a button is submit. See this: Can I make a <button> not submit a form?
Try updating your button to this code:
<button type="button" id="addToCart" class="add_cart" name="3">Add to Cart</button>
So I have some results that have items that get toggled, hidden/shown, etc. That bit works just fine except for the items that are appended to the bottom of the results. The click handler does not fire on them but work just fine on the others. I assume it has to do with reading the nodes at the time of page load. How do I get the appended items to also work?
<div class="event">
<a href="/profile/00000000">
<img class="user-image" src="https://graph.facebook.com/00000000/picture?width=100&height=100">
</a>
<div class="event-info">
<div class="content">
<div class="event-time-location">
<span class="user-name">Levi Thornton</span>
<span class="user-action-time">Posted 21 minutes ago</span>
</div>
<div class="event-caption">1
</div> </div>
<div class="event-like-comment">
<input id="js-eventId" type="hidden" value="201" name="eventId">
likedlike comment
more
</div>
</div>
<div class="comments" id="comments-201" style="display: block;">
<div class="newComments">
<input id="js-eventId" type="hidden" value="201" name="eventId">
<textarea class="addComment" value="Write a comment..." placeholder="Write a comment..." title="Write a comment..."></textarea>
</div>
</div>
<!-- comments -->
<div class="clear"></div>
</div>
The jQ:
...
// add like
$(".event-like").click(function(event){
event.preventDefault();
var likeBtn = $(this);
$.post('/shindig/ajax-like-event', { eventId: $(this).siblings('#js-eventId').val(), userLogged: $('#js-userLogged').val(), ajax: true}, function(data){
if(data['success']){
likeBtn.hide();
likeBtn.siblings(".event-liked").show();
} else {
if(data['noaccess']){
window.location.href = data['url'];
}
}
},"json");
});
// soft delete like
$(".event-liked").click(function(event){
event.preventDefault();
var likeBtn = $(this);
$.post('/shindig/ajax-unlike-event', { eventId: $(this).siblings('#js-eventId').val(), userLogged: $('#js-userLogged').val(), ajax: true}, function(data){
if(data['success']){
likeBtn.hide();
likeBtn.siblings(".event-like").show();
} else {
if(data['noaccess']){
window.location.href = data['url'];
}
}
},"json");
});
// hit bottom scrolling, load more results
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
console.log('bottom');
$.post('/index/ajax-feed-items-by-time', { pager: $("#js-pager").val(), ajax: true}, function(data){
$( ".feedContent" ).append( data );
$pager = $("#js-pager").val()+10;
$("#js-pager").val($pager);
});
}
});
Replace
$(".event-like").click(function(event) {
with
$(document).on("click", ".event-like", function(event) {
and similarly throughout your code. It's called event delegation, and the best place to start reading about it is the jQuery documentation.
Below is my html format i want to open leftbar div tag while clicking of open-left tag and also close leftbar div tag while clicking of open-left tag.
<div id="leftbar" class="snap-drawers">
<div class="snap-drawer snap-drawer-left">
<div>
<br />
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center">
<img src="assets/img/nloop-min.png" alt="" class="drawer-logo" />
</div>
<br />
<ul>
<li><i class="fa fa-home fa-1x"></i> Home</li>
<li><i class="fa fa-dot-circle-o fa-1x"></i> Tour</li>
<li><i class="fa fa-bullseye fa-1x"></i> FAQ</li>
<li><i class="fa fa-magic fa-1x"></i> About</li>
<li><i class="fa fa-comment-o fa-1x"></i> Contact</li>
</ul>
<br />
<p>
© 2013 - nLoop</p>
</div>
</div>
</div>
<div id="content" class="snap-content">
<div id="sidebarmenu" class="col-lg-1 col-sm-1 col-xs-1 col-md-1">
</div>
<div id="rightpart" class="margingap">
Right part
</div>
</div>
<script type="text/javascript">
var snapper = new Snap({
element: document.getElementById('content'),
disable: 'right'
});
$(document).ready(function () {
var addEvent = function addEvent(element, eventName, func) {
if (element.addEventListener) {
return element.addEventListener(eventName, func, false);
} else if (element.attachEvent) {
return element.attachEvent("on" + eventName, func);
}
};
addEvent(document.getElementById('open-left'), 'click', function () {
snapper.open('left');
var state = $(this).is('.open');
if (state) {
snapper.close('left');
}
});
});
</script>
Open and close div element while cliking an anchor tag:
$("#open-left").click(function(){
$("#leftbar").toggle();
});
See more about this here: .toggle() Documentation
Code explanation:
I am just attaching a click event to the #open-left tag and then I called the .toggle() on the #leftbar. This just pretty much keeps record of what is the current state of the object, hiddden or shown, and then calls the particular function according to the state.
Also, see this working example: fiddle.
Are you maybe looking for something like jQuery's hide() and show()? Or toggle()?
Try this:
var isOpen = false;
$("#open-left").click(function(){
if(isOpen){
$("#leftbar").slideUp(); isOpen = false;}
else{ $("#leftbar").slideDown(); isOpen = true; }
});