Using preventDefault - javascript

I've been looking at some code posted by someone and I can't make sense of why he used preventDefault.
var $windows = $('#tgx-window,#tgs-window,#tgm-window,#tgl-window'), $buttons = $('#tgx-button,#tgs-button,#tgm-button,#tgl-button');
$windows.hide();
$buttons.on('click', function(e) {
var $id;
e.preventDefault();
$buttons.removeClass('closebutton');
$id = $('#' + this.id.split('-')[0] + '-window');// Get window id
$windows.slideUp();
if(! $id.is(':visible') ) {
$id.slideDown();
$(this).addClass('closebutton');
}
});
It seems to behave exactly the same with or without it. My best guess so far is that it's common practice to use preventDefault/return false in function bodies.
My question is why he used that method at all?
Oh, yeah. I'm new to JavaScript.
http://jsfiddle.net/62NPt/53/

From the docs:
If this method is called, the default action of the event will not be
triggered.
So if your button is an input submit button for example, the event.preventDefault() will prevent the default behaviour of your button and prevent your form from submitting and reload the page. This is normally helpful when you want to apply AJAX call.

If the button is of type submit and in case of anchor if you use preventDefault() the default action of the event will not be triggered.
If you dont want to stop default action of element then it does not make any difference.

Related

jQuery disable double click prevention breaking functionality of a PHP function in a form

I have a jquery bug that I cant solve - hoping for help with a solution. Dont know if it is browser bug related (probably not), jQuery related, or Yii (our backend) related - but I need to try to solve it with the jQuery portion. Code at bottom of message.
Requirement: Disable accidental double submissions on forms.
Current Solution: Check for form submission state through a delegate and when the DOM form state changes to submit - append the disable attribute to the form submit button to prevent accident double form submission.
jQuery double click disabler:
$( document ).ready(function() {
$('html').delegate('form', 'submit', function() {
$(this).find(':submit').attr('disabled', true);
});
});
Problem: This works perfectly on every part of the CRM we are developing EXCEPT for a single timekeeper (clock in/clock out) feature. With the timekeeper the form has two submit buttons (one for clock in, one for clock out). Only one submit button shows at a time (Either "In" or "Out". When you click the button - it submits the form and changes the submit button to the other state by checking a session var to determine what state it is in and determines which of the two submit buttons are to be displayed. Problem is if you click it, the form appears to submit, but the state don't change. If you click it really fast a few times you can get it to change state. I suspect this is a timing or order of operations issue, but I have no idea how to fix it. The fix MUST be done on the front end, so here is the code (both the PHP being impacted and jQuery double click prevention). Perhaps a different method of disabling double submissions may work, please post your solution if you have one to try. Commenting out the current jQuery allows the form to function as designed. What might be causing this, and how might I change the jQuery double click prevention to solve it?
On page PHP for the time clock:
<form action = "<?=$clockUrl?>" method = "post" >
<input type = "hidden" name = "previousUrl" value = "<?=$currentUrl?>">
<?php if ($sessionVar->timeclockin) {?>
<input type = "submit" name = "submit-clockout" value = "Out">
<class="clock-time" ><?=$sessionVar->timeclockin?></class="clock-time">
<?php } else {?>
<input type = "submit" name = "submit-clockin" value = "In">
<?php }?>
</form>
Thank you for pointing me in the right direction Tyler! I was able to fix the issue with the following alteration to my script.
function do_nothing() {
console.log("click prevented");
return false;
}
$('html').delegate('form', 'submit', function(e) {
$(e.target).find(':submit').click(do_nothing);
setTimeout(function(){
$(e.target).unbind('click', do_nothing);
}, 10000);
});
Update 1:
If you are looking to prevent the button from being pressed twice then inside of your onclick or submit function, you should use something similar to the following:
$('#yourButton').prop('disabled', true);
If the page then redirects then you won't have to undo this. If it does, then do the opposite by changing true to false.
The submit function should instead disable the submit button until it either returns or fails.
An alternative is to use a lambda style function and replace it temporarily with an empty function until the request returns or fails.

anchor link not working with jquery event.preventDefault;

I need to open popup on click of anchor link with jquery.
here is HTML part
Clear Search
here is Jquery
$("a.clearField").on("click", function(){loadclearSearchPopup()});
function loadclearSearchPopup(obj){
var delay = '';
$(obj).preventDefault;
//popup open code goes here;
return false;
}
I know i can work around by replacing href with href="#"
But i am curious why event.preventDefault and return false not working?
Any help
$(obj).preventDefault;
should be
e.preventDefault();
It's a method of the event, not a property of the jQuery object. Also, the reason that return false is not working is because you are not passing the return value back to the handler
$("a.clearField").on("click", function (e){
var delay = '';
// Prevents the link from being followed
e.preventDefault();
// Prevents following links and propagation (bubbling the event)
// Note that this is a jQuery feature only. In standard DOM event handlers,
// return false is the same as e.preventDefault()
return false;
// But you don't need both
});
Because you have to attach it to event, not $(obj)
event.preventDefault()
#Juan's answer is correct (though I answered 15 sec earlier), but I'd like to show how to do it correctly with some changes to his code
$("a.clearField").click(loadclearSearchPopup);
function loadclearSearchPopup(e){
e.preventDefault();
// ... your code after preventing default action
}
I didn't use anonymous function as far as you have all your code in loadclearSearchPopup()
I used click instead of on('click', ...) assuming that you don't have a lot of links on your page with exactly the same functionality and you will unlikely change it's content
I prevent action on 1st string because maybe later you will need to return some result or break it, and preventing on last string will not execute
Note, that you cannot pass arguments to your function, but you can handle them IN it
FIDDLE

How to stop default href action

I have code in the below format in my JSP.
sumbit
On pressing the link my form gets submitted. However, I need to block the default a href behaviour and just need to call the submit function.The submit function submits the form
I have tried catching the click event on a HREF by jQuery and then firing e.preventDefault(). Following the same, I have picked up the HREF attribute, and then done an eval() to fire the function.
However, I have not been able to stop the default HREF functionality, and a new page is always saved in browser cache.
I also don't have the freedom to manually go in and change the code. Please suggest.
UPDATE
The issue with the code is:
submit
is one of the example of HREF being used in JSP. There may be different type of functions being called, using the above format:
I had used the below jQuery:
$("a[href^=\'javascript\']").live('click',function(e)
{
e.preventdefault();
eval($(this).attr('href'));
return false;
});
However, this does not stop the default HREF functionality. What am I missing?
As you mentioned in your question, you cannot manually change the markup.
So, I think, this is what you really want.
<form id='myform' action=''>
</form>
submit​
​
JS:
function submit() {
document.getElementById('myform').submit();
}
jQuery(function() {
$('a').click(function() {
var href = $(this).attr('href').replace('javascript:','');
console.log(href);
alert('hi');
eval(href);
return false;
});
});​
​
Demo
Update:
You can avoid eval(href), by using window[href]();
See this Demo
Try:
sumbit

JS, how to stop process execution if it's beeing executed ...?

How can I stop sending data to the server if the button allready has been clicked ? I don't want a disable="disabled" response (buttons are custom made).
I tried setting a global var button_clicked = FALSE; set it true when button has been clicked, after that set it again to false when the response has been received . But that doesnt work neither because my mouse is messed up and spam clicks really fast (although i click only once -> this actualy helped me to see that the method mentioned isn't so acurate).
Are there better methods to stop a process or disable a DOM element onClick? Maybe disable the event? js or jquery answer preferable . Or maybe this really can't be done on really fast requests . I know it depends on alot of things (like user's cpu). Any comment or answer is welcome. Maybe for every click on the page set the user to wait for some miliseconds ?
Try this little constructor:
function MyForm()
{
this.check = false;
this.form = function(){
var f = this;
$('#form').submit(function(e){
e.preventDefault
if( f.check === false )
{
f.check = true;
$.ajax({
...blah blah
success: function( data )
{
//if you want to let them send again, uncomment this next line
//f.check = false;
}
})
}
});
this.form();
}
$(document).ready(function(){
var my = new MyForm();
});
If you register an event listener, the Event object you get will have a preventDefault() method. This avoids following a clicked link or sending a submitted form.
If it is a custom action triggered by an event handler, the only possibility is to check a condition in the handler function whether the action really should be taken. Yet, a disabled button is not that bad because you will need to inform the user that nothing will happen.
Remove the click handler when the button is clicked. Add it again when you are ready for the next click.
button.onclick = null;

Disable click handler when click is fired in jQuery

We have a website built in .NET and jQuery. We have custom jQuery to call the load method on a processing ASP.NET page. That ajax call is fired in a click handler, e.g.
$("#Submit").click(function(){
$(a_selector).load("Process.aspx?data=" + someDataObject, null, function(){
alert("Done")});
}
return false;
);
Our issue is when we hit the #Submit button the click is fired which calls the ajax to process it. People seem to be double-clicking the button and therefore we're getting multiple results in our database from the dual clicks. Does anyone have an idea on how to prevent this issue? I considered something like disabling the button via JS but I'd like to know of other ideas.
Use the one function of jQuery. This way, the event is only ever fired once. Of course, you should also disable the button so the user knows that clicking on it is futile. In addition, show a spinner, progress bar, or change the cursor styling to indicate to the user that something is happening and the system isn't stuck.
stop propagation
$("#Submit").click(function(event){
event.stopPropagation();
if (typeof $_submitSend == "undefined")
var $_submitSend = true;
else if ($_submitSend == true)
return false;
$_submitSend = true;
$(this).attr("disabled", "disabled");
$(a_selector).load("Process.aspx?data=" + someDataObject, null, function(){
alert("Done")});
$_submitSend = false;
$(this).removeAttr("disabled");
}
);
$("#Submit").click(function(){
$(a_selector).removeClass("class").load("Process.aspx?data=" + someDataObject, null, function(){
$(this).addClass("class");
alert("Done")});
}
return false;
);
Then just add some specific class without any styling which you will use as a selector. Dont know if it will work the way you want, but it looks like simplest solution to me... :)

Categories

Resources