I have an MVC application and one of the views contains a button with a condition.
<i class="fa fa-sticky-note-o"></i>Did Not Eat
<button type="button" id="btnRemoveDidNotEat" class="btn btnRemoveDidNotEat">Remove Did Not Eat</button>
On click of btnRemoveDidNotEat,btnRemoveDidNotEat is hidden.
If btnDidNotEat is clicked,btnRemoveDidNotEat is shown.
Here is my JS code.
$('.btnDidNotEat').on('click', function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').show();
});
});
$('#btnRemoveDidNotEat').on('click', function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').hide();
});
});
The functionality works for the first time. On click of ".btnDidNotEat", the other button '#btnRemoveDidNotEat' is shown. On click of '#btnRemoveDidNotEat', it is hidden as required.
However the second time,On click of ".btnDidNotEat", the other button '#btnRemoveDidNotEat' is shown. But the button click function for '#btnRemoveDidNotEat' is not called.
I have tried doing the same with style="display:none;", but that gives me the same issue. I have also tried using toggle.
Am I missing something?
EDIT : Simplified the question to make it more clear.
I am not sure I understand your question right, but it looks like your AJAX response seems to have a partial view result. If you are trying to access the button click event of that partial view of AJAX, it will not hit the click event because it will not be attached to the DOM. So instead of your code, you should use something like this.
$("body").on("click", ".btnRemoveDidNotEat", function() {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').hide();
});
}
I'm not sure if I understood your question correctly, but here is what I got fiddle
Here is some improvements of your script:
$('.btnDidNotEat').click(function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').toggle();
});
});
$('#btnRemoveDidNotEat').click(function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').toggle();
});
});
You can use toggle() function instead of adding and deleting class.
Related
i face a problem of jquery click function when i scroll down in list.
in list, data is loaded by ajax request and when i scroll down then click function (trigger) is not working.
when i not scroll down, ajax data is not loaded then click function is working.
i'm confuse why this happened. i used following triggers below but not success.
on()
click()
bind()
load()
delegate()
i'm sending you code. this is code below. Please help me to sort out.
$(window).ready(function(){
$(".like").on("click", function(){
var id = $(this).attr('data');
// alert(id);
$.ajax({
url: "/stores/addLike",
type: 'GET',
data: {
id: id
},
error: function (data) {
console.log(data);
},
success: function (data) {
console.log(data);
if(data == "liked"){
alert('Sorry, you have already liked this beat.');
}else if(data == "notlogin"){
alert('Please login first to like a beat.');
window.location = "https://demo.amplifihub.com/login";
}else{
$(".likes"+id).text(data);
}
}
});
});
});
instead of $(".like").on("click", function(){ }); use $(document).on("click", ".like", function(){}); or use any static parent dom element to preserve the DOM event. I believe you are generating .like class element on scroll ajax call.
CODE:
<span class="clickable" id="span_resend">Resend</span>
<script>
$('#span_resend').click(function (e) {
e.preventDefault();
var save_this = $(this);
var middle_this = $('<span class="loader">now_loading</span>');
$(this).replaceWith(middle_this)
$.ajax({
url:'/ajax/',
type:'post',
dataType:'json',
cache:false,
data:{
com: 'some',
},
success:function (data) {
console.log(data)
if (data.res === 'success'){
middle_this.replaceWith(save_this)
}
}
});
})
</script>
It works well when I click resend first.
However cause of script tag, there will be term of now_loading and after loaded, then clicking #span_resend does not works well.
I think it's from that I did not bind click function well on #span_resend.
But I don't know how to do it.
How can I do this?
More explanation: This code is to get ajax response from server, and that ajax response takes some time, maybe 10~15 seconds. So I want to change my resend button to show that ajax is being called, at the same time user cannot click during the waiting of ajax response from server.
The Problem:
Here's what's happening in your code that isn't obvious right away. On first click, you create a jQuery object containing the clicked span, you save this to a variable and after your post completes, you then replace the temporary span with the value of the variable.
Seems like everything should be just fine, but what you've actually done is dynamically added a control to your HTML and while the html of the control is identical to the original span, it is not the same control.
Why does this matter?
Events. It's all about events. When you copy a control, you aren't copying those event listeners associated with it too. So when that event fires again, it looks for the original control and doesn't find it.
You can read in depth about events and event listeners here.
So great, what do you do about all this?
The Solution:
The answer here is to bind those events to a control that is higher than the one you're replacing and won't be replaced itself. So maybe your body tag, or even the document tag. Here's what that would look like in your code:
// Instead of this:
$('#span_resend').click(function (e) {
// Some code.
});
// Do this:
$(document).on('click', '#span_resend', function (e) {
// Some code.
});
This ensures that those event listeners aren't removed when you replace the control.
Here's a mock up of your code using this method:
$(document).on('click', '#span_resend', function (e) {
e.preventDefault();
var save_this = $(this);
var middle_this = $('<span class="loader">now_loading</span>');
$(this).replaceWith(middle_this)
$.ajax({
url:'https://reqres.in/api/users?delay=3',
type:'post',
dataType:'json',
cache:false,
data:{
com: 'some',
res: 'success'
},
success:function (data) {
if (data.res === 'success'){
middle_this.replaceWith(save_this);
}
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="clickable" id="span_resend">Resend</span>
Hope that helps!
I recommend not replacing the button with a now loading but to hide it and show a separate loading indicator, then revert back once it's done
$(document).ready(function() {
$("#saveBtn").click(saveData);
});
function saveData() {
$('#saveBtn').hide();
$('#nowLoadingInd').show();
//AJAX here instead of timeout (just for demo purpose)
window.setTimeout(function() {
$('#saveBtn').show();
$('#nowLoadingInd').hide();
}, 10000);
}
#saveBtn {
display:inline-block;
background:green;
color:white;
border-radius:10px;
cursor:pointer;
padding:3px 5px
}
#nowLoadingInd {
color:gray
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div id="saveBtn">Save!</div>
<div id="nowLoadingInd" style="display:none">Now Loading...</div>
</body>
</html>
Alternatively, you can pass an element to your ajax options and reference it in the then callback with the this object:
$.ajax({
url:"yourUrl",
data:{your:"data"},
extraProperty:$('#yourElem')
}).then(function() {
this.extraProperty.show()
});
I am trying to execute a $.ajax() inside a function called by a .on() method, so that in the newlly attached data, it would be possible to execute a script on a .click() event - I know this is probably something similar to other requests, but i have tryed and tryed, and can't find what is wrong withthe code...
The ajax function is called by a change in a select, and 'this' is passed as a variable to the function.
The data is correctly inserted inside the targeted div, but it seems that there is no bubbling, because no javascript runs from it (but runs outside of targeted div).
I used .on() so it would bubble up, and update the DOM, and I dont see wath I am doing wrong with it...
The ajax is called with:
$("body").on("change", "[data-project-ajaxSelect='true']", {select: this},Select_AjaxCall);
function Select_AjaxCall(event) {
$select = event.data.select;
if (typeof $select.data === "undefined" || $select.data === null) {
var $select = $(this);
}
var options = {
url: $select.attr("data-project-action"),
type: $select.attr("data-project-method"),
target: $select.attr("data-target"),
data: { guid: $select.val() }
}
$.ajax({
type: options.type,
url: options.url,
data: options.data,
dataType: "html",
success: function (data) {
console.log(data)
$(options.target).html(data);
}
});
return false;
};
From that code, a button is added with the following View code:
<button id=#Model.Guid
class="button default cycle-button"
data-toggle="modal"
data-target="#modalDiv"
data-backdrop="static"
data-keyboard="true"
data-modal-modal="true"
data-modal-controller="Fin_Movement_Type"
data-modal-action="Create"
data-modal-var-guid=#Model.Guid
data-modal-var-modal=#ViewBag._modal>
<span class="icon mif-plus"></span>
</button>
And by cicking on this button, the following .click() event should be fired...
$("[data-modal-modal='true']").click(function () { ... }
But it isn't.
Please Help me find where is the bug with my code... thank you.
Edit
It seems you need live functionality that has been removed from jQuery, but you can use on instead of that, this way:
$(function () {
$(document).on("click","[data-modal-modal='true']", function () {
alert('clicked');
});
});
Original
You can add your code at the end of your success method:
success: function (data) {
console.log(data);
$(options.target).html(data);
$("[data-modal-modal='true']").on("click", function() {
alert('clicked!');
});
}
Also you can load the button with suitable script in onclick attribute, for example:
<button id="#Model.Guid"
...
onclick="alert('clicked!');">
<span class="icon mif-plus"></span>
</button>
I have a snippet in my project similar to the one seen below:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$('#this_container').fadeIn();
}
});
The above snippet is working. When thisCondition evaluates to true, the container does fade in. However, I also have the snippet below that is not functioning as expected. It binds to show so that when the container fades in an event will be triggered:
$('#this_container').bind('show', function() {
$.ajax({
...
});
});
Shouldn't the snippet above react to line 5 in the change event handler? Why is the bind method not triggering?
Confirmed that show is not a valid nor jQuery-triggered event.
But you can trigger it yourself!
Try something like this :
$('#this_container').fadeIn("slow", function() {
$(this).trigger("show");
});
The show is not a valid event, neither is triggered by jQuery. You need to construct your script in a different way altogether:
$('#field').change(function() {
var thisCondition = $(this).val();
if(thisCondition) {
$.ajax({
success: function () {
$('#this_container').fadeIn();
}
});
}
});
So, you can try to bring the AJAX content, and upon a successful request, you can show the container.
try to use :
$('#this_container').fadeIn( "slow", function() {
// Animation complete
$.ajax({
...
});
});
I have added a row to a grid in jQuery success function, like this(edited adding Rob and Fleix comments):
$(function() {
$('#MyGrid').delegate('a.remove', 'click', function() {
alert("del");
// e.preventDefault();
jQuery.ajax(
{
type: "POST",
url: "Upload/Remove",
data: "removefile=" + stringhtml// error console shows it as undefined
});
$(this).closest('tr').remove();
});
$("#uploadForm").ajaxForm({
iframe: true,
dataType: "xml",
url: "Upload/Index",
success: function(result) {
('#MyGrid tbody').append('<tr><td> ' + stringhtml+ ' </td><td><a href="#"
class="remove">Remove</a></td></tr>');
});
});
the ajax call is not making for remove click ,but is hitting once page is loaded. How to make the ajax call for remove click, with passing the stringhtml?
Could you guys help me out!
thanking you,
michaeld
Bind to the click event of the remove links
$('#MyGrid').delegate('a.remove', 'click', function(e){
e.preventDefault();
$(this).closest('tr').remove();
});
Change your row append code to
$('#MyGrid tbody').append('<tr><td> ' + stringhtml+ ' </td><td>Remove</td></tr>');
First, update your "Remove" link so that it is like:
Remove
Then implement your remove() function like this:
function remove(node) {
node.parentNode.parentNode.removeChild(node.parentNode);
//equivalent: $('#MyGrid tbody')[0].removeChild(node.parentNode);
}
Here's an example: http://jsfiddle.net/nNde4/5/
First of all, avoid using inline onclick attributes. Instead use $(selector).bind('click', function(e){}); or $(selector).click(function(e){});. In your case, actually using live() would make more sense, since you don't have to attach every event over and over. So using the following should work:
$('#MyGrid a').live('click', function(e){
$(e.target).parent().parent().remove();
});
Also note that you don't have to call this every time you add a row. Call this only once when the tabel is created (on load etc) and it should work just fine.