When I click on a link in my jsp
<a id="ajout_lien" href="javascript:submitFormAjout()" class="under">go </a>
I call a javascript function
function submitFormAjout() {
document.forms['constitutionForm'].submit();
}
Then there is the jquery call to prevent from a double submit :
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});
How can I change the appearance of my link while the submit is done (the real one, in the Jquery's call)? By instance change the color and label of my tag ( let's say from "go" to "waiting"?
I want it to be as generic as possible : if, in another jsp of my application, the submit is made on a button, not a link, I an use 3 parameters : newClass (css) , idElement (of the button or the link) and label if it's a link.
Try the below code
function submitFormAjout() {
document.getElementById("ajout_lien").className ="over";
document.forms['constitutionForm'].submit();
}
jQuery .one() ensures submit event is triggered only once.
$("form").one("submit", function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});
JQuery:
function submitFormAjout() {
$("#"+ (this).attr("id")).addClass("over");
$('form[name="constitutionForm"]').submit();
}
HTML:
<a id="ajout_lien" href="javascript:submitFormAjout()" class="under">text </a>
If you want className to be dynamic, then you can pass it as function parameter and use that value in the method.
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 an a element containing an href attribute. Clicking on it would delete data so I want the user to confirm that action. The href attribute refers to a php file with an id of the data that will be deleted in the GET parameter. I've added an onclick attribute, that should execute the following piece of JS (it shows a Semantic UI modal that asks for confirmation):
confirmmodal = function () {
beforeunload = function () {
$('.ui.basic.modal')
.modal({
closable: false,
onDeny: function () {
return false;
},
onApprove: function () {
return true;
}
})
.modal('show')
;
}
}
But when I run this it still goes to the page that would delete the data (although I haven't built it yet, so nothing is deleted). Would there be an option that gives the onclick attribute priority over the href attribute somehow?
You need to add event.preventDefault() at the end of your code.
Eg:
Delete
function showDialog(e) {
// custom code to show dialog here
e.preventDefault();
}
Okay, I got there with a few tweaks on the script, taking gavgrif's comment into account as well.
I made the <a> element a little different, so it won't contain an href attribute anymore:
<a title="Delete post" onclick="confirmmodal(this)" data-postid="'. $row['postnr'] .'"><i class="large delete middle aligned icon"></i></a>
Now, if the icon is clicked, the postid is available for the JS as well, so we can just refer to that in the GET parameter when the confirm button is clicked:
confirmmodal = function (a) {
$('.ui.basic.modal')
.modal({
closable: false,
onDeny: function () {
return true;
},
onApprove: function () {
window.location.href = "deletepost.php?id=" + a.dataset.postid
return true;
}
})
.modal('show')
;
}
Which is a semi-ugly fix, but it's not that many more lines, and I don't know s*** about JQuery :)
Thanks for all the help, I almost got there with preventDefault() but I couldn't continue if the action was confirmed, so this is an easier solution.
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 am trying to write an if else statement to trigger one class when another one is clicked under the condition that the one class has a marginTop of -200px.
I tried using this if statement but it doesn't work:
if ($('.logintrigger').click() && $('.register').css('marginTop') === '-200px') {
$('.registertrigger').toggle(
function () {$('.register').stop().animate({'marginTop':'-0px'},200); $('#opencloseregister').css({'backgroundPosition':'-20px 0px'});}
);
}
Any suggestions???
Made a jsfiddle with an example of proper ifelse with jquery. http://jsfiddle.net/RQ75m/
$(".logintrigger").click(function(){
if( $(".register").css("margin-top") == "200px" ){
$(".registertrigger").show(); //toggle function here
return false; //so that the page doesn't refresh
} else {
$(".registertrigger").hide();
return false; //so that the page doesn't refresh
}
});
It sounds like you simply need to rework your expression. The problem is you're trying to see if an element is 'clicked', when you should just attach an event handler.
$('.loginTrigger').click(function()
{
if('.register').css('marginTop') === '-200px')
{
// Do Stuff
}
});
you are calling the click event, i think you want to add an event to the click event...
$('.logintrigger').click( function(e){
if($('.register').css('marginTop') === '-200px'){
$('.registertrigger').toggle();
}
});
When you are calling $('.logintrigger').click(), it is triggering click event.
it should be:
if ($('.logintrigger').click(function(){
if ($('.register').css('marginTop') === '-200px') {
$('.registertrigger').toggle(
function () {
$('.register').stop().animate({'marginTop':'-0px'},200);
$('#opencloseregister').css({'backgroundPosition':'-20px 0px'});
}
);
}
})
$('.logintrigger').on('click', function(){
if($('.register').css('marginTop')==='200px') {
$('.registertrigger').toggle( function () {
$('.register').stop().animate({'marginTop': 0 },200);
$('#opencloseregister').css({'backgroundPosition':'-20px 0px'});
});
}
});
The code below is for a simple newsletter signup widget.
I'm sure there's a way to make it more concise, any ideas?
var email_form = $('.widget_subscribe form');
var email_submit = $('.widget_subscribe .submit');
var email_link = $('.widget_subscribe .email');
// Hide the email entry form when the page loads
email_form.hide();
// Show the form when the email link is clicked
$(email_link).click( function () {
$(this).toggle();
$(email_form).toggle();
return false;
});
// Hide the form when the form submit is clicked
$(email_submit).click( function () {
$(email_link).toggle();
$(email_form).toggle();
});
// Clear/reset the email input on focus
$('input[name="email"]').focus( function () {
$(this).val("");
}).blur( function () {
if ($(this).val() == "") {
$(this).val($(this)[0].defaultValue);
}
});
You have some similar code here.
// Show the form when the email link is clicked
$(email_link).click( function () {
$(this).toggle();
$(email_form).toggle();
return false;
});
// Hide the form when the form submit is clicked
$(email_submit).click( function () {
$(email_link).toggle();
$(email_form).toggle();
});
It could be refactored so the similarity is obvious.
// Show the form when the email link is clicked
$(email_link).click( function () {
$(email_link).toggle();
$(email_form).toggle();
return false;
});
// Hide the form when the form submit is clicked
$(email_submit).click( function () {
$(email_link).toggle();
$(email_form).toggle();
});
So you could wrap toggling the link and the form into a function.
var toggleEmailLinkAndForm = function () {
$(email_link).toggle();
$(email_form).toggle();
}
$(email_link).click(toggleEmailLinkAndForm);
$(email_submit).click(toggleEmailLinkAndForm);
And as others have pointed out, you can drop the redunant $()s.
var toggleEmailLinkAndForm = function () {
email_link.toggle();
email_form.toggle();
}
email_link.click(toggleEmailLinkAndForm);
email_submit.click(toggleEmailLinkAndForm);
It's already pretty concise, there's not much more you can do.
Anywhere you have $(email_submit) you can just have email_submit, because you've already wrapped it in $() (which makes it a jquery object).
Eg:
email_submit.click( function () {
email_link.toggle();
email_form.toggle();
});
I like Patrick McElhaney Code Best.
toggleEmailLinkAndForm() {
email_link.toggle();
email_form.toggle();
}
email_link.click(toggleEmailLinkAndForm);
email_submit.click(toggleEmailLinkAndForm);
Part of refactoring is not going overboard. I would not recommend creating an extra click event that calls the other click event. The point of refactoring is readability and flexibility. You can also use the jQuery method "add" to shrink the code but it will become even harder to read.
email_link.add(email_submit).click(function(){
email_link.add(email_form).toggle();
});
Like Patrick said (+1), and you can also skip the extra function:
email_submit.click(function () {
email_link.toggle();
email_form.toggle();
});
email_link.click(function () {
email_submit.click(); //calls the click function already subscribed
return false;
});