jquery: Callback not received on clicking of button - javascript

I need to send a request on click of button but callback is not received on firing of click event of the button.
Following is code snippet:
$(document).ready(function () {
var counter = 0;
$("#trail").click(function () {
$("#dialog").dialog();
if (counter < 1) {
$("#searchboxdiv").after('<input type="text" id="searchbox">');
$("#searchbox").after('<input type="button" id="searchbutton" value="search">');
counter++;
}
});
$("#searchbutton").click(function () {
var dataToSend = null;
$.ajax({
data: dataToSend,
url: "FormHandler",
success: function (result) {},
beforeSend: function () {
dataToSend = $("#searchbox").val();
}
});
});
$("#searchboxdiv").on('click', "#searchbutton", function(){
var data = null;
});
});
I added the textbox in the dialog box dynamically and on click of button in dialog box, callback is not received

Your options:
Use event delegation. Bind the click to immediate static parent like this :
$("#searchboxdiv").on('click', "#searchbutton", function(){ });
Or, bind it to the document.
$(document).on('click', "#searchbutton", function(){ });
Or, move the existing click after counter++;, ie., inside $("#trail")'s click handler.
For more info, see on()

Use event delegation (for dynamically added #searchbutton)
$('#searchboxdiv').on('click',"#searchbutton",function(){
http://learn.jquery.com/events/event-delegation/

Related

I have a page that needs to automatically trigger the click event and pass parameters to him when entering

$(document).ready(function() {
});
$(".divID").click(function (){
var test = $(this).attr('value');
});
How do I call the click event Parallel parameters
Use trigger method of jQuery
$(document).ready(function() {
$(".divID").click(function (){
var test = $(this).attr('value');
});
$(".divID").trigger('click');
});

Why does my jQuery delegated click fire multiple times?

I am copying an element and adding it to a a list of elements. First, I get some HTML using an ajax call:
var setButtonClick = function (url, btn) {
$.ajax(url, $('form').serialize(), 'Html').then(function (data) {
$(btn).parent().find(sel.addListItem).on('click', function () {
addListItem(data, this, btn);
});
addListItem(data, btn, btn);
});
}
addListItem looks like this:
var addListItem = function (data, context, btn) {
var $template = $(data);
// stuff not related removed for brevity
$(btn).before($template);
}
I then have a remove function using a delegate:
$(sel.editableList).delegate(sel.removeListItem, 'click', function () {
// fires once for every element with the sel.removeListItem selector
}
I need the click event to fire once for the clicked element only. I can get a basic version of delegate working by inserting content like this:
$( "body" ).delegate( "p", "click", function() {
$( this ).after( "<p>Another paragraph!</p>" );
});
Therefore, I'm thinking it may be because I'm inserting a copy of the element or is it the same element I'm adding over and over? I've also tried to use clone to create a new element before inserting like:
var $template = $(data).clone();
Can anyone show me where I am going wrong with this please?
The problem is that every time your ajax is called you attach a click event handler to the elements. It gets called repeatedly, because you add it to the elements that already existed and had this handler attached.
The solution for your problem is to detach previously attached handlers with off() function.
var setButtonClick = function (url, btn) {
$.ajax(url, $('form').serialize(), 'Html').then(function (data) {
$(btn).parent().find(sel.addListItem)
.off('click')
.on('click', function () {
addListItem(data, this, btn);
});
addListItem(data, btn, btn);
});
}
#
In the future you may want to attach different click event handlers or may want to turn off specific handlers, for that you could use namespaces.
$(elem).on('event.namespace', function(){});
$(elem).off('event.namespace');
That way you could have multiple click event handlers on one element. This would be the code if you have more than one click event handlers
var setButtonClick = function (url, btn) {
$.ajax(url, $('form').serialize(), 'Html').then(function (data) {
$(btn).parent().find(sel.addListItem)
.off('click.addItem')
.on('click.addItem', function () {
addListItem(data, this, btn);
});
addListItem(data, btn, btn);
});
}
#
And here's the example.
$('.btn').on('click.ns1', function(){
alert('Hey');
});
$('.btn').on('click.ns2', function(){
alert('How you doin?');
});
// Comment me out to see the difference
$('.btn').off('click.ns2');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btn">Click me</button>

Preventing double event binding in jQuery

I have this code
$(".generate").click(function() {
$.getJSON("jsonfile.json").done(function(data) {
if (parseInt(data)>0) {
$(".mybutton").click(function() {
alert(data);
});
}
});
});
When the "generate" button is clicked, the getJSON function is called and if data says "ok" then I can press the "mybutton" to alert the data;
Only problem is if I press the "generate" button a few times (I want this to happen), the "mybutton" will alert "hello" also a number of times (depending on how many times I clicked the generate button).
I have tried e.stopPropagation(), but this did not help.
The reason is that every time you click the button .generate you add a new event handler on the element with the class .mybutton
It's not very clear what you're trying to do, but if the purpose is to store the data you get from the ajax call, you can do like this:
//data container
var localData;
//will show the actual content of the variable when .mybutton is clicked
$(".mybutton").click(function()
{
alert(localData);
});
//this will update the variable when .generate is clicked
$(".generate").click(function()
{
$.getJSON("jsonfile.json").done(function(data)
{
if (parseInt(data)>0)
{
localData = data;
//this will trigger the click event on the button .mybutton that will fire the handler with the alert
$(".mybutton").trigger('click');
}
});
});
You could unbind and re-bind the handler each time
if (parseInt(data)>0) {
$(".mybutton").off('click').click(function() {
alert(data);
});
}
What if you try it this way? (Didn't test this, but should work)
$(".generate").click(function() {
$(this).unbind('click').next()
$.getJSON("jsonfile.json").done(function(data) {
if (parseInt(data)>0) {
$(".mybutton").click(function() {
$(this).unbind('click').next()
alert(data);
});
}
});
});
Why do you always rebind the event. Is the button removed from the DOM after you click the generate button?
If not you could only bind the event once and just disable the button while no data is available:
$(".mybutton").prop('disabled', true); // initially disable
$(".mybutton").click(function() { // bind the event once
alert(data);
});
$(".generate").click(function() {
$(".mybutton").prop('disabled', true); // disable if new data starts to generate
$.getJSON("jsonfile.json").done(function(data) {
if (parseInt(data)>0) {
$(".mybutton").prop('disabled', false); // enable if everything is ok
}
});
});
Use delegation with on() like
$(function() {
var buttonData = {};
$(".generate").click(function() {
$.getJSON("jsonfile.json").done(function(data) {
if (parseInt(data) > 0) {
buttonData = data;
}
});
});
$(document).on('click', '.mybutton', function() {
alert(buttonData);
});
});
and bind it outside of the getJSON success handler

Trigger the event after making the HTML object in JQuery

I want an event to be triggered after the creation of the corresponding HTML object (href in my case).
I've written this code:
$(document).ready(function() {
$('body').on('click', '#stats-link', function(e) {
console.log('TRIGGERED'); // nothing is logged
e.preventDefault();
$.post('stats.php', {'email': $('#email').val()}, function() {
window.location = $(this).attr('href');
});
});
$('#submit_button').click(function(e) {
e.preventDefault();
...
$('#info').html('<p class="desc">bla bla bla</p>');
...
});
});
So, I make a href object identified by stats-link in the #submit_button function, then I want him to be triggered in the corresponding function (i.e., $('body').on(...), but it doesn't happen. What am I doing wrong?
Did you missed this line:
$('#stats-link').trigger('click');
This will trigger the click event. The code you shared only binds the event. You need to trigger it.
JS:
$(document).ready(function () {
$('body').on('click', '#stats-link', function (e) {
e.preventDefault();
alert('clicked')
$.post('stats.php', {
'email': $('#email').val()
}, function () {
window.location = $(this).attr('href');
});
});
$('#submit_button').click(function (e) {
e.preventDefault();
$('#info').html('<p class="desc">bla bla bla</p>');
$('#stats-link').trigger('click'); //This is where you trigger the click.
});
});
Working Demo: http://jsfiddle.net/lotusgodkk/artaq4xj/
What is e? Are you sure the click event isn't actually working, but just giving you a script error and bailing out before it does anything? Your callback function does not define the passed in event parameter e.
$('body').on('click', '#stats-link', function() { // <-- No e parameter supplied.
e.preventDefault(); // <---- What is e?
...
}
Your preventDefault() parameter is lacked :
$('body').on('click', '#stats-link', function(event) {
event.preventDefault();
$.post('stats.php', {'email': $('#email').val()}, function() {
window.location = $(this).attr('href');
});
});

Function Running Multiple Times in jQuery

I have created a function which makes an ajax request to a PHP file and then adds a product to the basket. This function works as it should on the first click, but on each subsequent click it runs the function again. So for example, on the 2nd click it runs the function twice, on the 3rd click it runs it three times and so on... The problem is reset when the page is refreshed...
Here's the on click code:
$("#add_123456").click(function () {
$("#add_123456").addClass('added');
var quantity = $("#qty_123456").val();
$('#basket_1').submit(function (event) {
event.preventDefault();
basket_add("feqf73nbdw7","123456","XYZ123","1","0.1","19.23");
});
});
Here's the function:
function basket_add(cartID, productID, code, quantity, weight, price) {
var item_add = {"Cart_ID": cartID,
"Product_ID" : productID,
"Code" : code,
"Qty" : quantity,
"Weight" : weight,
"Price" : price
};
$("#basketpop").animate({top: "40px"}, 200);
$.ajax({
url: '/templates/new/includes/ajax/add_to_basket.php',
type: 'POST',
data: item_add,
dataType: "html",
success: function(html){
$('.basket_content').empty().append(html);
$('.basket_content').css("height", "auto");
var item_add = null;
}
});
return false;
};
Don't think the issue is with the PHP file that is being called.
Cheers
Assuming the #add_123456 button is a submit button, the problem is because you are adding a new submit() handler to the form on each click of the button. Instead you only need to add the submit handler once and raise the event on the form on button click. Try this:
$('#basket_1').submit(function (event) {
event.preventDefault();
basket_add("feqf73nbdw7","123456","XYZ123","1","0.1","19.23");
});
$("#add_123456").click(function () {
$("#add_123456").addClass('added');
var quantity = $("#qty_123456").val();
$('#basket_1').submit();
});
If you are only submitting via AJAX though, you can remove the need to submit the form at all, like this:
$("#add_123456").click(function () {
$("#add_123456").addClass('added');
var quantity = $("#qty_123456").val();
basket_add("feqf73nbdw7","123456","XYZ123","1","0.1","19.23");
});
Because every time you click the #add_123456, the code $('#basket_1').submit(function (event) {...}) will be run, which will add a callback function to $('#basket_1').submit, you may want to bind the callback first, and trigger submit when click.
Something like:
$('#basket_1').submit(function (event) {
event.preventDefault();
basket_add("feqf73nbdw7","123456","XYZ123","1","0.1","19.23");
});
$("#add_123456").click(function () {
$("#add_123456").addClass('added');
var quantity = $("#qty_123456").val();
$('#basket_1').trigger('submit');
});
The issue could be created by the submit listener. A new one will be appended at every click.
Maybe you should have separate your submit listerer doing something like that:
$("#add_123456").click(function () {
$("#add_123456").addClass('added');
var quantity = $("#qty_123456").val();
});
$('#basket_1').submit(function (event) {
event.preventDefault();
basket_add("feqf73nbdw7","123456","XYZ123","1","0.1","19.23");
});
Another solution is to unbind your listener before binding:
$("#add_123456").click(function () {
$("#add_123456").addClass('added');
var quantity = $("#qty_123456").val();
$('#basket_1').unbind( 'submit' ).bind( 'submit', function (event) {
event.preventDefault();
basket_add("feqf73nbdw7","123456","XYZ123","1","0.1","19.23");
});
});
You are attaching another event handler every time the button is clicked.
Either attach the onsubmit handler outside of the onclick handler, or use
$('#basket_1').off('submit').on('submit',(function (event) {
event.preventDefault();
basket_add("feqf73nbdw7","123456","XYZ123","1","0.1","19.23");
});

Categories