I have a checkout form that uses php to load some javascript & html into #Div-A when the page loads. The javascript binds a click event to #Button-A in the same div. Something like this:
<div id="#Div-A"><input type="button" id="Button-A"/>
<script type="text/javascript">
$('#Button-A').bind('click', function() {
$.ajax({
type: 'get',
url: 'some/url/gets/called',
success: function() { this happens on success }
});
});</script>
</div>
Afterward, #Global-Button is created and a javascript function binds a different click event to this second button which then triggers #Button-A to be clicked like this:
$('#Global-Button').live('click', function(event) {
$("#Button-A").trigger("click");
})
The reason being that the contents of #Div-A can change (via ajax), so the second button acts as a global trigger regardless of which button or function happens to reside in #Div-A.
The problem I'm encountering is that for some reason if #Global-Button is clicked after page load #Button-A gets triggered twice. If an Ajax event reloads the contents of #Div-A then all is well and the the trigger happens only once as it should.
I've examined the html within #Div-A before and after reloading via Ajax and everything appears to be identical. There are definitely no duplicate buttons or functions anywhere as far as I can see that would cause two events to be triggered.
I know only a very little about the DOM and can only guess this has something to do with the order in which things are loaded and events are bound.
This is always recommended to use 'unbind' before bind to make sure the event is not bound multiple times. In your case, there may be two possibilities -
'#Global-Button' click function is bound twice.
'#Button-A' click function is bound twice and '#Global-Button' is actually triggering the click once.
Change your code like -
$('#Global-Button').unbind('click').bind('click', function(event) {
$("#Button-A").trigger("click");
})
and also -
$('#Button-A').unbind('click').bind('click', function() {
$.ajax({
type: 'get',
url: 'some/url/gets/called',
success: function() { this happens on success }
});
});
Don't use .live. Live is deprecated use .on instead
Every time you click on #Blobal-Button you are biding an click event.So you need to off before use it
Use .off to remove event handler
$('#Global-Button').off('click');
$('#Global-Button').on('click', function(event) {
$("#Button-A").trigger("click");
})
You can also use
$(".selector").on("click", function (**e**) {
**e**.stopImmediatePropagation();//use to stop click twice or more
})
Related
I'm having the oddest problem with a jquery/ajax html update form.
My app is a single page TODO App that uses a Rails controller, but all DOM changes take place through Jquery/Ajax. After the TODOs are rendered to the page through Javascript, there is an edit button for each TODO.
When the edit button is clicked, an API request is made that results in an update form being appended to the DOM.
However, when the update button from that form is clicked it isn't recognized by Jquery and for some unknown reason Rails re-renders the Index.html.erb page everytime. I've tried 10 different solutions for the selector and nothing works.
The method that selects appends the edit form to the DOM is here:
$(document).on("click", ".ugh3", function(e) {
e.preventDefault()
let id = e.target.id
let event = e
$.ajax({
type: "GET",
url: `/todos/${id}`,
success: function(response) {
let newTodo = new Todo(response)
let todoHtml = newTodo.formatEdit()
$('.todo-list').append(todoHtml)
}
})
})
The above call works perfectly. But when I try to get the form submit or on Click to work it never will recognize it and the Index.html.erb page is resubmitted. I've tried preventDefault and return false as shown below:
$("form.edit_todo").on("submit", function (e) {
debugger
e.preventDefault();
return false;
})
If anyone has a couple minutes to look at this I'd greatly appreciate it. This has been driving me insane for two days now. Thank very much!
The git repo is: https://github.com/jwolfe890/todoapp/blob/master/app/assets/javascripts/todo.js
As you're appending the form dynamically, the submit handler - $("form.edit_todo").on("submit", ... - will not fire as the form did not yet exist in the DOM at the time of binding.
Similar to the click event you're using on the .ugh3 class, you need to register the submit event against the document:
$(document).on('submit', 'form.edit_todo', function (e) { ... })
The document is a constant - it will always exist, and therefore any event listener can be bound against it. When a submit event is fired, the document detects it (a result of event bubbling) and jQuery will take the target element (the one causing the event) and compare it against any registered handlers (handlers are created with you $.on function). If there's a match it will execute that handler.
Hi I have some suggestion for you:
Are you putting the code inside the document.ready() function of jquery. Like the following:
$(document).ready(function(){
$("form.edit_todo").on("submit", function (e) {
debugger
e.preventDefault();
return false; }); });
I think this should work keeping in mind that "form.edit_todo" is referring to the form object
I have a script where a user can press a button which makes an AJAX call. Once the call is completed, the button is replaced with text saying "Complete" as well as a new button called "Undo". The purpose is to allow the user to undo the action they just took:
<script type="text/javascript">
$('button').on('click', function() {
ajax call
});
update.append('Complete<button type=\"button\" id=\"undo\">Undo</button>');
$(this).remove();
});
</script>
However, I am having trouble making the Undo button connect to the onclick function for that id. Actually, nothing seems to happen when I click the Undo button.. I believe it may have to do with the undo button having been generated within an update.append from the onclick function above.. However, I am having trouble understanding what is going wrong. Here is my function for the undo click event for a button with id=undo (which was added in the original onclick function above):
$("#undo").click(function() {
ajax call
});
I placed this function just below the first function in my script, but nothing happens when I press the Undo button. Even if I add an alert within the function for testing, the alert doesn't even show.
Any suggestions would be much appreciated.
$("#undo").click will only work if the element was not added dynamically to the DOM. Since you are dynamically adding undo use .on instead:
$('body').on('click', '#undo', function() {
ajax call
});
I guess Spencers answer will not work.
Cuz event should be attached to already existing element in DOM
modifying his code like below should work
$("body").on('click', '#undo', function() {
ajax call
});
Simple on click binding will not work. You have to use the following.
$("body").on('click', '#undo', function() {
ajax call
});
or
$(document).on('click', '#undo', function() {
ajax call
});
What i would like to do is trigger a button's click event from within a view that gets returned from an ajax call. This process works fine in a pc browser such as chrome but not so in a mobile browser. (i am using both jquery and jquery mobile).
(there is a lot more code involved in this but i have removed it for clarity)
I have a button in my html page like so.
<input type="button" id="bt1" value="" />
It has an onclick event listener on it defined somewhere else.
I have an ajax call that calls a php script like so:
$.ajax({
url: 'blah.php',
type: 'get',
data: {
id : $('#field').val()
},
dataType: 'html',
success: function (data) {
$('#somediv').html(data);
}
});
It returns "data" which is a segment of html with inline javascript. It containts the following code:
<div>
<script type="text/javascript">
$(document).ready(function () {
$("#bt1").trigger("click");
});
</script>
</div>
What ive noticed is that the trigger event will not be fired when used in a mobile. but works fine in pc.
Is there a different in the DOM when dealing with mobile that it prevents a trigger("click") from working if the object is outside the view?
Try adding the touchstart event along side the click event.
$("#bt1").trigger("touchstart click");
you may need to implement touch events on mobile. Take a look at this SO answer:
Understanding touch events
If you cannot change what comes back from the server then you can listen for a click event and trigger a touch event.
Good luck,
Mike
It cannot find the button since the javascript code and the button element is being created programatically, try:
$(document).find('#bt1').trigger('click');
or
$(document).find('#bt1').each(function(e) {
e.trigger('click');
}
or, better:
success: function (data) {
$('#somediv').html(data).promise().done(){
$('#bt1').trigger('click');
});
}
In my project, I'm working on a function which deletes rows from a table and also from the database using .ajax(). I've created my function for when the user clicks on the delete button. As you can understand, there a several rows and every row has its own delete button.
Now, when the user clicks on one of them for the first time, a popup modal appears with the question if he/she is sure about deleting the item. When he/she clicks yes, the popup disappears and the row fades-out. This all works perfectly, but...
When you click on a second delete button without refreshing the page, JavaScript fires off the current requested delete (and id) + de previous one. If you do it for a third time, it will fire of the current one and the two previous ones.
I tried to empty the current var $(this).attr('data-page-id');, but it still does the same thing when the .ajax() success function gets fired.
$('a.btn-page-delete').click(function() {
var curPageId = $(this).attr('data-page-id');
$('#delete-page').modal('show');
$('a#action-confirm').click(function() {
$.ajax({
type : 'POST',
url : '/pages/async/delete',
dataType : 'json',
data : { page : curPageId },
success : function(data) {
$('#delete-page').modal('hide');
console.log(curPageId);
console.log(data);
},
error : function() {}
});
});
});
When your outer click event handler gets called
$('a.btn-page-delete').click(function() {
it'll .bind() another click event handler to $('a#action-confirm') everytime. So, everytime the outer event is executed you add one more event handler.
I'm sure you can and should re-build and construct this in a better way, but in the present state your only choice is to .unbind() / .off() the inner click handlers, like
$('a#action-confirm').off('click').click(function() {
that will remove any click event handler bound via jQuery previously.
Ref.: .off()
I have an ASP.NET Web Form application developed by another developer.
This developer made extensive use of ASP.NET controls therefore there are many automatically generated Javascript functions wired to HTML elements' event.
Now I have been asked to add a functionality: disable the submit button upon first stroke, in order to avoid the users to click several times on the button.
Here is the jQuery code that I use http://jsfiddle.net/2hgnZ/80/ and the HTML DOM is identical to the one I use:
$('#form1').submit(function(e) {
$(this).find('input[type=submit]').attr('disabled', 'disabled');
// this is to prevent the actual submit
e.preventDefault();
return false;
});
This script in my code does not work and after many attempts I am sure it depends on the JavaScript event wired to the onSubmit event of the button.
How can I postpone the execution of this Javascript on favour of the jQuery unobtrusive function?
hmm. Can you confirm that your event is firing? I cheked the submit docs, and it is bound rather than live, which is good.
How about wiring to the button, instead? It would not be perfect, because the enter key doesn't use the button, but if it works that way you'll learn something
Have you tried calling e.stopImmediatePropagation(); http://api.jquery.com/event.stopImmediatePropagation/
This piece of code delays the execution of function amount you want.
// delay code for one second
$(document).ready(function()
{
window.setTimeout(function()
{
// delayed code goes here
}, 1000);
});
This piece of code should help you get the original event and then trigger it after your desired code.
$(function(){
var $button = $('#actionButton'),
clickEvent = $button.data("events")['click'][0].handler; //saves the original click event handler
$button.unbind('click'); //and removes it from the button
//create a new click event.
$button.click(function(e){
// doWhatever we need to do
$.ajax({
url: url,
data: data,
success: function(){
$.proxy(clickEvent,$button)(e);//attach the original event to the button
}
});
});
});