jQuery event.Preventdefault(); is not doing anything - javascript

i have some scripts on my site that send replies to a server and reload the page using ajax. sometimes though, it reloads the page for no reason.
so I added this code
<script type="text/javascript">
$("form").submit(function(){
event.preventDefault();
return false;
)
</script>
but it is still reloading the page when i hit sumbit.
why.

You simply forgot to bring in the event argument into the handler:
$("form").submit(function( event ) {
Also: check the error console, in your example code you are missing an ending bracket });
As a side note: make sure you are selecting the form element after it has been loaded, to be safe use domReady:
$(function() {
$("form").submit(function(event){
event.preventDefault();
});
});

event as a global (window.event) is non-standard. jQuery normalizes this for you, so just pass in event as an argument:
$(document).ready(function() { // Make sure you wait until the document is ready
$("form").submit(function(event) {
event.preventDefault();
});
});
Also, returning false calls event.preventDefault() as well as event.stopPropagation(). You only want the first to happen, so be explicit.

$("form").submit(function(event){})

In a comment on another answer, you've said:
it still reloads the page
That suggests that you have this code above the form you want it to act on in the HTML. Move the script below the form (usually just before the closing </body> tag is best), or use jQuery's ready event.
Also note that if you're using return false, you don't need event.preventDefault, because return false from a jQuery event handler does event.preventDefault() and event.stopPropagation(), so:
<form ...>
<!-- ... -->
</form>
<!-- ... -->
<script>
$("form").submit(function(){
return false;
});
</script>
</body>
Or alternately, this anywhere on the page, using the shortcut for ready:
$(function() {
$("form").submit(function(){
return false;
});
});

Related

using anchor tag I dont want to call the href

so for example I have
AltaVista
for the sake of this exercise I dont want to go to the altavista site. I want to call a function that loads an alert instead...so I have tried...
<a onClick="registerHandlers(); return false;" href="//www.altavista.com">Yahoo!</a><br/>
<script>
function registerHandlers() {
alert("hi");
}
</script>
this is not working does anyone know why
I suggest you use event.preventDefault() to prevent the link's dafault link behaviour. And if want to use jquery to add some event handles, return false is not recommended as it will also prevent all other event handlers on that element from running.
function registerHandlers(e) {
if (e.preventDefault) {
e.preventDefault();
}
alert('hi');
}
<a onClick="registerHandlers(event)" href="//www.altavista.com">Yahoo!</a><br/>

Trigger click after load page

I'm working with a wordpress theme and I need to activate a button when the page loads, but none of the following has worked for me (my button has the ID "reset"):
$(document).ready(function() {
$("#reset")[0].click();
});
--
$(document).ready(function(){
$("#reset").click();
})
--
$(window).load(function(){
$('#reset').click();
});
I put the code in the header or in the page where i need to activate the button, but does not work.
Thanks!
I give you example here
$(document).ready(function(){
$("#reset").click();
})
the code above should work.
JavaScript does not allow seamless programmatic triggering of an actual click event.
What you could do is
declare the click callback as a separate, named function
e.g.
function myClickCallback(e) {
// Do stuff here
}
Set this as the click callback of your button (e.g. $('#reset').on('click', myClickCallback)).
Invoke the callback when the page loads (e.g. $(document).ready(myClickCallback);)
I am not sure why you 'd want this functionality, since it sounds weird. From reading your description, by "activating", you could also mean enabling the button. To do that you should do something like the following
$(document).on('ready', function (e){
$('#reset').removeAttr('disabled');
});
You may need to refer to it using jQuery instead of $:
The jQuery library included with WordPress is set to the noConflict() mode...
https://codex.wordpress.org/Function_Reference/wp_enqueue_script#jQuery_noConflict_Wrappers
$(document).ready(function(){
$("#reset").trigger('click');
});
Use the function Trigger with the event click
$(document).ready(function(){
$("#reset").trigger('click');
});
This what works for me:
$(function () {
$('#btnUpdatePosition').click();
});
On the button event, the JQuery binding event doesn't work:
$('#btnUpdatePosition').click(function () {
alert('test again');
});
But it works when I added the event on attribute declaration:
<input type="button" value="Update" id="btnUpdatePosition" onclick="alert('Click has been called')" />
You can also call if you have a function on element:
<input type="button" value="Update" id="btnUpdatePosition" onclick="fncShow();" />

JQuery after submit form post link is not send? [duplicate]

Hello Friends this is my code to form submit and then send post link but form submit success then after not send post link.
document.getElementById("pitch_image_path_form").submit(function(e){
$.post("submit_investorform.php",{'flage':'getallimagesfromselectedid','form':'pitch_image_path_form'},function(result){
$("#pitch_image_path_showalldatafromid").html(result);
});
e.preventDefault();
});
this is my code form is submit but post request is not send.
dear renishkhunt please try this code. this is help fully for me.
$("#pitch_image_path_form").ajaxSubmit({ success: function(){
$.post("submit_investorform.php",{'flage':'getallimagesfromselectedid','form':'pitch_image_path_form'},function(result){
$("#pitch_image_path_showalldatafromid").html(result);
});
} });
please check this link this is tutorial.
http://malsup.com/jquery/form/
.submit() is a jQuery function, so you need to wrap your $("#pitch_image_path_form")[0] in a jQuery wrapper, like so:
$($("#pitch_image_path_form")[0]).submit(function(){
There is no submit() event in DOM, you are mixing DOM and jQuery
change
document.getElementById("pitch_image_path_form").submit
to
$("#pitch_image_path_form").submit
$("pitch_image_path_form").submit(function(e){
e.preventDefault();
$.post(
"submit_investorform.php",
{'flage':'getallimagesfromselectedid','form':'pitch_image_path_form'}
, function(result) { $("#pitch_image_path_showalldatafromid").html(result); }
);
});
Because DOM does not support submit(), there is do submit() function in DOM. Same exact answer when you asked this the last time.
When you call .submit(), it posts the form with the specified action of the <form>.
You might want to stop the propagation, by using either event.stopPropagation();, event.preventDefault(); or return false; at the end of your function.
$("#pitch_image_path_form").submit(function(event){
event.stopPropagation();
event.preventDefault();
//Your .post()
return false;
});
Plus, as epascarello pointed out, .submit() is a jQuery function.
If you want to use it, use it on the jQuery object by removing [0] before submit(), as you're not supposed to have multiple elements with the same ID.

Delegate to capture two form submissions

Using the following function to capture two dynamically generated form submissions, but is not preventing their submission.
$('body').delegate('.edit_faq, .new_faq', 'submit', function(e){
e.preventDefault();
//voodoo
});
I was using the following, using live. This works, but live is depreciated and the end result is for this code to end up in a flexible plugin.
$('.edit_faq').add('.new_faq').live('submit', function(e){
e.preventDefault();
//magic
});
What you have written is actually working.
check:
http://jsfiddle.net/peuqU/
press run as jsfiddle sometimes needs a refresh before testing submits.
I have only been able to test it with chrome 23.
Try on which is the recommended way, and return false:
$('body').on('submit', '.edit_faq, .new_faq', function(e){
e.preventDefault();
//Do your stuff here.
});
As to why the submission still occurs, maybe you have a JS error somewhere in the page?
FIXED--
The problem was that the code required being wrapped on a document onReady:
$(document).ready(function(){
$('body').on('submit', '.edit_faq, .new_faq', function(e){
e.preventDefault();
//voodoo
});
})
I occurs to me that since live did not require the ready, that maybe this is still wrong?

Access event to call preventdefault from custom function originating from onclick attribute of tag

I have links like this:
<a href="#" onclick="myfunc({a:1, b:'hi'})" />click</a>
<a href="#" onclick="myfunc({a:3, b:'jo'})" />click</a>
And I would like to do a preventDefault() inside myfunc(), because a # will be added in the address bar when clicking on the link
(without doing return false; or href='javascript:void(0);')
Is this possible?
Can I get the event inside myfunc()
I believe you can pass in event into the function inline which will be the event object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event).
A quick example.
function sayHi(e) {
e.preventDefault();
alert("hi");
}
Click to say Hi
Run it as is and notice that the link does no redirect to Google after the alert.
Then, change the event passed into the onclick handler to something else like e, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).
The simplest solution simply is:
<a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>
It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)
<a onclick="
if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' +
Math.round(new Date().getTime() / 1000);"
href="http://www.domain.com/docs/thingy.pdf">
If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.
Try this:
<script>
$("a").click(function(event) {
event.preventDefault();
});
</script>
Can you not just remove the href attribute from the a tag?
<script type="text/javascript">
$('a').click(function(){
return false;
});
<script>
Add a unique class to the links and a javascript that prevents default on links with this class:
<a href="#" class="prevent-default"
onclick="$('.comment .hidden').toggle();">Show comments</a>
<script>
$(document).ready(function(){
$("a.prevent-default").click(function(event) {
event.preventDefault();
});
});
</script>
I think when we use onClick we want to do something different than default. So, for all your links with onClick:
$("a[onClick]").on("click", function(e) {
return e.preventDefault();
});
Simple!
onclick="blabla(); return false"
You can access the event from onclick like this:
<button onclick="yourFunc(event);">go</button>
and at your javascript function, my advice is adding that first line statement as:
function yourFunc(e) {
e = e ? e : event;
}
then use everywhere e as event variable
Without any JS library or jQuery.
To open a nice popup window if possible. Fails safely to normal link open.
...
And the helper function:
function openNewWindow(event, location) {
if (event.preventDefault && event.stopImmediatePropagation) {
event.preventDefault();
event.stopImmediatePropagation();
} else {
event.returnValue = false;
}
window.open(location, 'targetWindow', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=800,height=450');
}
e.preventDefault();
from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Or have return false from your method.

Categories

Resources