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
Related
I have a group of buttons with different values but same name (says "save"). When one of this button is clicked, a jquery event is triggered and sends the value of that exact button with an ajax call to the server. When the server responds with a success, I would like the value of that same clicked button to change into "saved". I have written a little function that does that, but the problem is that when you click on one of those buttons that say "save" and it's a success, all the values of the other buttons change into "saved". How can I change only the value of the clicked button and instead of all the buttons with the same name?
Here's my html:
<button class="homemade" name="saveArticle" value="v1">Save</button>
<button class="homemade" name="saveArticle" value="v2">Save</button>
Here's my Jquery function:
$(function() {
$('[name="saveArticle"]').bind('click', function() {
$.getJSON('/articles/save', {
article_id: this.value,
}, function(data) {
$("[name='saveArticle']").text(data.message);
});
return false;
});
});
use arrow functions then you can just use this to refer to the clicked button.
$(function() {
$('[name="saveArticle"]').bind('click', function() {
$.getJSON('/articles/save', {
article_id: this.value,
}, (data)=>{
$(this).text(data.message);
});
return false;
});
});
alternatively you could use the event target.
$(function() {
$('[name="saveArticle"]').bind('click', function(event) {
$.getJSON('/articles/save', {
article_id: this.value,
}, function(data) {
$(event.target).text(data.message);
});
return false;
});
});
Shouldn’t that do the trick to give you access to the element that was clicked?
$(function() {
$('[name="saveArticle"]').bind('click', function() {
// here `this` points to element on which event fired
$(this) // <-- creates jQuery object of it
});
});
I have a change function in javascript who permit me to do an action when the user click on a chekbox who's name is "nameCheckbox" so i have this script.
$("input[name='nameCheckbox']").each(function()
{
var object = creatObject($(this).val());
$(this).change(function()
{
if($(this).is(':checked'))
{
var object = creatObject($(this).val());
}
else
{
object.remove();
}
});
});
But i want to have another checkbox who permit to check or uncheck all the checkbox who's name is "nameCheckbox" and pass by the function change of all the element. So i have this code.
$("[name='allCheck']").change(function()
{
var selectAll = false;
if($(this).is(":checked"))
{
selectAll = true;
}
$("input[name='nameCheckbox']").each(function()
{
if(selectAll)
{
$(this).prop('checked',true);
}
else
{
$(this).prop('checked',false);
}
//And here i want to do something like $(this).change();
});
});
Thank you
$(this).change() should work, according to change()
Description: Bind an event handler to the "change" JavaScript event,
or trigger that event on an element.
This is effectively the same as using trigger()
$(this).trigger('change');
I have 6 images that load in different 6 different modal windows and they each have a next button and also a close button in them. The next button works with the following jquery code:
$('#nextModal12').click(function() {
$('#featuresModal1').modal('hide');
$('#featuresModal1').on('hidden.bs.modal', function () {
$('#featuresModal2').modal('show');
document.getElementById('#featuresModal1').style.display="none";
});
});
$('#nextModal23').click(function() {
$('#featuresModal2').modal('hide');
$('#featuresModal2').on('hidden.bs.modal', function () {
$('#featuresModal3').modal('show');
document.getElementById('#featuresModal2').style.display="none";
});
});
However, the problem is: Even when I close/hide the first modal ('#nextModal12') by clicking the CLOSE button instead of the next, the second modal appears.
I believe this is because the hidden.bs.modal function is picked up and called again even when I'm not clicking the next button. How do I prevent the script from picking up the hidden.bs.modal function indiscriminately?
Try use .one function instead of .on. When you use .on() your callback would be repeating again and again, beacuse you bind it again for each click;
$('#nextModal12').click(function() {
$('#featuresModal1').modal('hide');
$('#featuresModal1').one('hidden.bs.modal', function () {
$('#featuresModal2').modal('show');
});
});
$('#nextModal23').click(function() {
$('#featuresModal2').modal('hide');
$('#featuresModal2').one('hidden.bs.modal', function () {
$('#featuresModal3').modal('show');
});
});
Don't bind hidden.bs.modal again and again on modal click, just bind it once like,
$('#nextModal12').click(function() {
$('#featuresModal1').modal('hide');
});
$('#featuresModal1').on('hidden.bs.modal', function () {
$('#featuresModal2').modal('show');
$(this).hide();// you can use hide function
});
$('#nextModal23').click(function() {
$('#featuresModal2').modal('hide');
});
$('#featuresModal2').on('hidden.bs.modal', function () {
$('#featuresModal3').modal('show');
$(this).hide();
});
Alternatively, you can try
$('#nextModal12').click(function() {
$('#featuresModal1').modal('hide'); // hide first
$('#featuresModal2').modal('show'); // show second
});
$('#nextModal23').click(function() {
$('#featuresModal2').modal('hide');
$('#featuresModal3').modal('show');
});
What's the best way to prevent a double-click on a link with jQuery?
I have a link that triggers an ajax call and when that ajax call returns it shows a message.
The problem is if I double-click, or click it twice before the ajax call returns, I wind up with two messages on the page when I really want just one.
I need like a disabled attribute on a button. But that doesn't work on links.
$('a').on('click', function(e){
e.preventDefault();
//do ajax call
});
You can use data- attributes, something like this:
$('a').on('click', function () {
var $this = $(this);
var alreadyClicked = $this.data('clicked');
if (alreadyClicked) {
return false;
}
$this.data('clicked', true);
$.ajax({
//some options
success: function (data) { //or complete
//stuff
$this.data('clicked', false);
}
})
});
I came with next simple jquery plugin:
(function($) {
$.fn.oneclick = function() {
$(this).one('click', function() {
$(this).click(function() { return false; });
});
};
// auto discover one-click elements
$(function() { $('[data-oneclick]').oneclick(); });
}(jQuery || Zepto));
// Then apply to selected elements
$('a.oneclick').oneclick();
Or just add custom data atribute in html:
<a data-oneclick href="/">One click</a>
You need async:false
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
$.ajax({
async: false,
success: function (data) {
//your message here
}
})
you can use a dummy class for this.
$('a#anchorID').bind('click',function(){
if($(this).hasClass('alreadyClicked')){
return false;
}else{
$(this).addClass('alreadyClicked);
$/ajax({
success: function(){$('a#anchorID').removeClass('alreadyClicked');},
error: function(){$('a#anchorID').removeClass('alreadyClicked');}
});
}});
Check this example. You can disable the button via CSS attribute after the first click (and remove this attribute after an ajax request or with a setTimeout) or use the jQuery.one() function to remove the trigger after the first click (without disabling the button)
var normal_button = $('#normal'),
one_button = $('#one'),
disabled_button = $('#disabled'),
result = $('#result');
normal_button.on('click', function () {
result.removeClass('hide').append(normal_button.html()+'<br/>');
});
one_button.one('click', function () {
result.removeClass('hide').append(one_button.html()+'<br/>');
});
disabled_button.on('click', function () {
disabled_button.attr('disabled', true);
setTimeout(function () {
result.removeClass('hide').append(disabled_button.html()+'<br/>');
}, 2000);
});
Although there are some good solutions offered, the method I ended up using was to just use a <button class="link"> that I can set the disabled attribute on.
Sometimes simplest solution is best.
You can disable click event on that link second time by using Jquery
$(this).unbind('click');
See this jsfiddle for reference
Demo
You can disable your links (for instance, href="#" ), and use a click event instead, binded to the link using the jQuery one() function.
Bind all the links with class "button" and try this:
$("a.button").click(function() { $(this).attr("disabled", "disabled"); });
$(document).click(function(evt) {
if ($(evt.target).is("a[disabled]"))
return false;
});
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/