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>
Related
I have a div called project and it is rendered with EJS
There several projects in the data for EJS, they are rendered by forEach loop - so several similar div appear.
The project div has id for identification in Jquery.
Further it has a project.name and project.id as a data-*
The problem which I encountered:
If I don't reload the page as intended - first try works well and Element inner text get updated correctly.
But on second try to change another project name both are changed to value of previous, so to say for both projects. In few words - new change overrides all previous. How is it possible?
Link to see how it looks in GIF
Imgur
Strange behaviour of chaining requests Imgur
<%userData.forEach(function(project){%>
<div class="project" id='project <%=project.id%>'>
<div class="projectHeader">
<div class="projectTitle">
<h5 id="projectTitle <%=project.id%>" class="projectName">
<%=project.name%>
</h5>
<div class="projectButtons">
<span data-toggle="tooltip" data-placement="top" title="Edit Project Title">
<a data-toggle="modal" data-target="#editProjectTitleModal">
<i id="editProjectName" class="editProject fas fa-pencil-alt"
data-name="<%=project.name%>" data-id="<%=project.id%>"></i>
</a>
</span>
</div>
</div>
</div>
A simple modal is called when the a tag in project is clicked.
<div class="modal fade" id="editProjectTitleModal" tabindex="-1" aria-labelledby="exampleformModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form class="" action="" method="">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Title</h5>
</div>
<div class="modal-body">
<div class="input-group">
<input id="editProjectNameInput" autocomplete="off" pattern="[a-zA-Z0-9 ].{1,25}" title="1 to 25 characters" class="form-control" aria-label="With textarea" placeholder="Enter new title" required></input>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="confirmEditProjectName" class="btn btn-primary">Save changes</button>
</div>
</form>
</div>
</div>
</div>
Jquery event handler which serves to change project.name, at first sends it to database and ammend DOM with new name. So the database get the new data, but the page is not reloaded and project.name changed simultaneously.
It grabs project-name and project-id and sends Ajax regular post - method, on success - change element's inner text to project-name
// Edit Project Title by ID
$(document).on('click', "#editProjectName", function() {
//Grab Id of the Project
var editProjectId = $(this).attr('data-id');
//Fill Modal input with current project.name
var currentTitle = document.getElementById('projectTitle ' + editProjectId).innerText;
$("#editProjectNameInput").val(currentTitle)
var url = '/editProjectName';
$('#confirmEditProjectName').on('click', function(event) {
//Take new project name from updated modal input
var newTitle = $("#editProjectNameInput").val();
//If they are same - alert
if (currentTitle === newTitle) {
event.preventDefault();
alert("New Title should be different")
} else {
event.preventDefault();
if (newTitle.length > 1 && newTitle.length <= 25) {
$.ajax({
type: "POST",
url: url,
data: {
projectName: newTitle,
projectID: editProjectId
},
success: function(result) {
//Hide modal and change element inner text to new value
$("#editProjectTitleModal").modal('hide')
document.getElementById('projectTitle ' + editProjectId).innerText = newTitle;
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
I removed the space from the IDs and I changed from using the ID of #editProjectName to just using the class that is already on that object of editProject.
<%userData.forEach(function(project){%>
<div class="project" id='project<%=project.id%>'>
<div class="projectHeader">
<div class="projectTitle">
<h5 id="projectTitle<%=project.id%>" class="projectName">
<%=project.name%>
</h5>
<div class="projectButtons">
<span data-toggle="tooltip" data-placement="top" title="Edit Project Title">
<a data-toggle="modal" data-target="#editProjectTitleModal">
<i class="editProject fas fa-pencil-alt"
data-name="<%=project.name%>" data-id="<%=project.id%>"></i>
</a>
</span>
</div>
</div>
</div>
// Edit Project Title by ID
$(document).on('click', ".editProject", function() {
//Grab Id of the Project
var editProjectId = $(this).attr('data-id');
//Fill Modal input with current project.name
var currentTitle = document.getElementById('projectTitle' + editProjectId).innerText;
$("#editProjectNameInput").val(currentTitle)
var url = '/editProjectName';
$('#confirmEditProjectName').on('click', function(event) {
//Take new project name from updated modal input
var newTitle = $("#editProjectNameInput").val();
//If they are same - alert
if (currentTitle === newTitle) {
event.preventDefault();
alert("New Title should be different")
} else {
event.preventDefault();
if (newTitle.length > 1 && newTitle.length <= 25) {
$.ajax({
type: "POST",
url: url,
data: {
projectName: newTitle,
projectID: editProjectId
},
success: function(result) {
//Hide modal and change element inner text to new value
$("#editProjectTitleModal").modal('hide')
document.getElementById('projectTitle' + editProjectId).innerText = newTitle;
},
error: function(err) {
console.log(err);
}
})
}
}
})
})
After some research I have found out that once the on('click') is called it is On until the page get reloaded.
Thanks to this Question and Answer:
https://stackoverflow.com/a/6121501/13541013
I figured out - on('click') event should be switched off by calling $(this).off() (this is the event)
In my case I had to make $(this).off() right after:
$(document).on('click', "#editProjectName", function() {
$(this).off() ... further code
And it has to be done for every single on('click') event in the script.
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 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");
});
I've searched and tried for 2 days now, with no luck whatsoever.
What i'm trying:
I generate several div's through a foreach in xslt, that contains a hidden div where i store a code to match value out of an external xml file on. Something like this:
<div class="pakket_content">
<a href="http://">
<div class="waardering_wrapper col-xs-12">
<div class="sterwaardering col-xs-8">
<img src="http://">
</div>
<div class="CODE">CODE</div>
<div class="waardering col-xs-4">
<p>-</p>
</div>
<div class="waardering pull-right">
<b>-</b>
</div>
</div>
</a>
<a href="">
<button type="button" class="btn btn-default btn-md pull-right col-xs-12">
Nu boeken!
<span class="glyphicon glyphicon-arrow-right"></span>
</button>
</a>
</div>
Where the div class 'code' contains the code to match on.
The xml that comes out of this is:
<entities>
<accommodation cms-id="458245" external-id="CODE" name="Trip A">
<destination cms-id="45541" name="Paramaribo" level="destination"/>
<country cms-id="4545" name="Suriname" level="country"/>
<accommodation-type>Hotel</accommodation-type>
<testimonial-count>88</testimonial-count>
<average-testimonial-score>7.6</average-testimonial-score>
<deep-link>
http://link.com
</deep-link>
<testimonial-count-per-language>88</testimonial-count-per-language>
<testimonial-count-all>88</testimonial-count-all>
<average-testimonial-score-all>7.6</average-testimonial-score-all>
</accommodation>
</entities>
Now i wanted to append the average-testimonial-score to div "waardering" when the external-id attribute in equals the value in . But how would i go about that?
I tried with looping through the value of the div class and the attribute, like this:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "file.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('accommodation').each(function(index) {
var cijfer = $(this).find('average-testimonial-score-all').text();
$('.CODE').each(function(index) {
var divcode = $(this).text();
$.attr('external-id').each(function(index) {
var attrcode = $(this).text();
if (divcode == attrcode) {
$(".waardering").append(cijfer);
};
});
});
});
}
});
});
With no result.
Can someone push me in the right direction with this?
Fetching accommodation external-id in correct way (according to how .attr() is supposed to work), the code works as it should.
I omitted Ajax request for testing.
Fiddle.
$(document).ready(function()
{
var xml = '<entities><accommodation cms-id="458245" external-id="CODE" name="Trip A"> <destination cms-id="45541" name="Paramaribo" level="destination"/> <country cms-id="4545" name="Suriname" level="country"/> <accommodation-type>Hotel</accommodation-type> <testimonial-count>88</testimonial-count> <average-testimonial-score>7.6</average-testimonial-score> <deep-link>http://link.com</deep-link> <testimonial-count-per-language>88</testimonial-count-per-language> <testimonial-count-all>88</testimonial-count-all> <average-testimonial-score-all>7.6</average-testimonial-score-all> </accommodation></entities>';
$(xml).find('accommodation').each(function(index)
{
var cijfer = $(this).find('average-testimonial-score-all').text();
var externalId = $(this).attr("external-id");
$('.CODE').each(function(index)
{
var divcode = $(this).text();
if (divcode == externalId)
{
$(".waardering").append(cijfer);
};
});
});
});
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.