I have a website that includes all kinds of websites using an iframe element, so I wanted to have an option to disable default submit action of all button elements inside the iframe(I have overcome cross-origin problems).
Now, first, I tried with adding 'disabled' attribute to the button elements inside the iframe and that works perfectly, but I also found that it looks awful on some websites(css issue) so I have focused on adding a new click event handler that would just return false and prevent default action. I tried first on the live website(without the iframe), from the chrome console running this:
// disable all click handler
$('button').off('click')
// Will submit form without this handler
$('button').bind('click', function(event) { event.stopPropagation(); return false; } );
and this successfully disables submit action. However, when I tried the same approach with the iframe:
<iframe id="iframe" src='http://somewebsite.com'></iframe>
<script>
var element = $($('#iframe').prop('contentDocument')).find('button').get(3);
$(element).off('click');
$(element).bind('click', function(event) { event.stopPropagation(); return false; } );
console.log(jQuery._data(element, 'events').click[0].handler)
// output function (event) { event.stopPropagation(); return false; }
</script>
As you can see, DOM element inside the iframe has provided event handler to stop default action, but for some reason that doesn't prevent it. Is there any reason this doesn't work with an iframe ?
Can you try the following? It will make sure the iframe is loaded then will check its content:
$("iframe").load(function (){
var btn = $('iframe').contents().find('bitton');
btn.off('click');
btn.bind('click', function(event) { event.stopPropagation(); return false; } );
});
Related
this trigger works correctly ONE time. If it fires again, it just refreshes my page, so I’m guessing that the preventDefault isn’t working. Am I missing something?
function watchForm() {
$(‘form’).submit(event => { //listening for event on the form pop-up menu
event.preventDefault(); //suppresses browser from going to a linked page.
$(’#js-error-message’).empty();
let searchState = $(’#js-stateMenuForm :selected’).val();
getParks(searchState); //calls getParks function.
});
}
Rewrite your function to this below and see if it works:
function watchForm(){
// for every form on the page
$('form').on('submit', function(e){
// empty the error element
$('#js-error-message').empty();
var searchState = $('#js-stateMenuForm :selected').val();
// call the function that uses the value you are looking forward to.
getParks(searchState);
// where e is the event
e.preventDefault();
return false; // force return of the form's submission
});
}
Also, you can check this post: Jquery .on() submit event
I have big upload form, user can drag and drop images here. But when images are loaded, i'm showing button, which on click should link to some page. But this element instead of loading next page, opens file chose window (its parent default behaviour)
So I'm checking, if event has class, if it's true, I'm using e.preventDefault().
And this works better (I don't have image choose window on link click, but also this link will not work - every event is disabled) My question is, how i can enable linking now?
// jFiler is a parent - upload form, with event - on click it opens window for file choose - like input field.
$(document).on('click', '.jFiler', function(e) {
if ($(event.target).hasClass("jFiler-input-done-btn")) {
e.stopPropagation();
e.preventDefault();
}
});
$('.jFiler-input-done-btn').on('click',function(e) {
// Test works, but this is a link, and it cannot link to another page now...
alert ('test')
});
You break the link execution with e.stopPropagation() and e.preventDefault() in the parent click event. You have to just return true there.
$(document).on('click', '.jFiler', function(e) {
if( $(event.target).hasClass("jFiler-input-done-btn") ) {
return true;
}
});
Just redirect to the other page inside the click event you already attach :
$('.jFiler-input-done-btn').on('click',function(e) {
windows.location.href = $(this).attr('href');
});
//OR also
$('.jFiler-input-done-btn').on('click',function(e) {
e.stopPropagation();
});
Hope this helps.
I've made a simple lightbox implementation in my code. By Clicking on #makePayment link a lightbox is opened, and within that lightbox there is a form. When user clicks on #paymentDetailsConfrimLB to submit the form, I've just displayed an alert.
Before I explain the problem, please have a look at the code I've written:
$("#makePayment").click(function() {
$("body").addClass("modalPrint");
var lb = new LightBox("paymentDetailsLB", "675", "500");
lb.htmlObjRef.style.height = "auto";
lb.show();
$("#paymentDetailsCloseLB, .hideBox").click(function() {
$("body").removeClass("modalPrint");
lb.hide();
});//paymentDetailsCloseLB
$("#paymentDetailsConfrimLB").click(function( event ) {
alert('form submission happened.');
event.preventDefault();
return false;
});//paymentDetailsConfrimLB
return false;
});//makePayment
Problem is, when I first load the page, and open the lightbox, and click the submit button, the alert is shown once (as it should), but if I close the lightbox, re-open it, and then submit the form, it is submitted twice and alert is shown twice. Similarly if I again close and re-open the lightbox, upon form submission the alert shows up 3 times, and it goes on like this.
Any idea on how I can resolve this?
Other than Kavin's approach, another solution also worked for me. I just added this line immediately after the event.preventDefault() method:
event.stopImmediatePropagation()
And it resolved the issue.
You're setting click callback every time you open lightbox. Try to move click callbacks out of #makePayment:
$("#makePayment").click(function() {
$("body").addClass("modalPrint");
var lb = new LightBox("paymentDetailsLB", "675", "500");
lb.htmlObjRef.style.height = "auto";
lb.show();
return false;
});//makePayment
$("#paymentDetailsCloseLB, .hideBox").click(function() {
$("body").removeClass("modalPrint");
lb.hide();
});//paymentDetailsCloseLB
$("#paymentDetailsConfrimLB").click(function( event ) {
alert('form submission happened.');
event.preventDefault();
return false;
});//paymentDetailsConfrimLB
You're binding a new handlers every time the submit button is clicked. You only need to define a handler once, and it will be executed whenever that action occurs. Otherwise, each handler you bind will execute.
If you absolutely needed to bind the handlers the way you are, then you could also use .one, which will only bind the handler the first time for each element.
jQuery .one() documentation
Attach a handler to an event for the elements. The handler is executed
at most once per element per event type.
Try something like this.
$(document).on('click', '#makePayment', function() {
$("body").addClass("modalPrint");
var lb = new LightBox("paymentDetailsLB", "675", "500");
lb.htmlObjRef.style.height = "auto";
lb.show();
return false;
}).on('click', '#paymentDetailsCloseLB, .hideBox', function() {
$("body").removeClass("modalPrint");
lb.hide()
}).on('click', '#paymentDetailsConfrimLB', function() {
alert('form submission happened.');
event.preventDefault();
return false;
});
The problem is:
$("#paymentDetailsConfrimLB").click(function( event ) {
alert('form submission happened.');
event.preventDefault();
return false;
});//paymentDetailsConfrimLB
it adds to the click queue, so to speak. So if you add multiple click events to something, all of them get added and all of them run by default. You don't notice it because all your other functions don't matter about being run multiple times.
A way to solve this is to put a check within the function.
$("#paymentDetailsCloseLB, .hideBox").click(function() {
$("body").removeClass("modalPrint");
lb.hide();
});//paymentDetailsCloseLB
pDCLB=$("#paymentDetailsConfrimLB");
if(!pDCLB.attr('alertc')); //check if the attribute exists, if not, we've never been here before.
pDCLB.attr('alertc',1); //adds the attribute so we can check it later.
$("#paymentDetailsConfrimLB").click(function( event ) {
alert('form submission happened.');
event.preventDefault();
return false;
});//paymentDetailsConfrimLB
}
I am using this below code for button click event using jQuery. When button is clicked the page reloads.
$('#button1').click(function () {
//Code goes here
return false;
});
If your "button" is a button element, make sure you explicity set the type attribute, otherwise the WebForm will treat it as submit by default.
<button id="button1" type="button">Go</button>
If it's an input element, do so with jQuery with the following:
$('#button1').click(function(e){
e.preventDefault();
// Code goes here
});
Read more: event.preventDefault()
You can use event.preventDefault() to prevent the default event (click) from occurring.
$('#button1').click(function(e) {
// prevent click action
e.preventDefault();
// your code here
return false;
});
I have a web page which I have prevented the default action on all submit buttons, however I would like to re-enable default submit action on a button how can I do this?
I am currently preventing the default action using the following:
$("form").bind("submit", function(e){
e.preventDefault();
});
I have successfully done this using the following:
$(document).ready(function(){
$("form:not('#press')").bind("submit", function(e){
e.preventDefault();
});
But can I do this dynamically when the button is clicked?
You would have to unbind the event and either rebind to a separate event that does not preventDefault or just call the default event yourself later in the method after unbinding.
There is no magical event.cancelled=false;
As requested
$('form').submit( function(ev){
ev.preventDefault();
//later you decide you want to submit
$(this).unbind('submit').submit()
});
Either you do what redsquare proposes with this code:
function preventDefault(e) {
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now switching back
$("form#foo").unbind("submit", preventDefault);
Or you assign a form attribute whenever submission is allowed. Something like this:
function preventDefault(e) {
if (event.currentTarget.allowDefault) {
return;
}
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now allowing submissions on the form
$("form#foo").get(0).allowDefault = true;
function(e){ e.preventDefault();
and its opposite
function(e){ return true; }
cheers!
$('form').submit( function(e){
e.preventDefault();
//later you decide you want to submit
$(this).trigger('submit'); or $(this).trigger('anyEvent');
With async actions (timers, ajax) you can override the property isDefaultPrevented like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
I had a similar problem recently. I had a form and PHP function that to be run once the form is submitted. However, I needed to run a javascript first.
// This variable is used in order to determine if we already did our js fun
var window.alreadyClicked = "NO"
$("form:not('#press')").bind("submit", function(e){
// Check if we already run js part
if(window.alreadyClicked == "NO"){
// Prevent page refresh
e.preventDefault();
// Change variable value so next time we submit the form the js wont run
window.alreadyClicked = "YES"
// Here is your actual js you need to run before doing the php part
xxxxxxxxxx
// Submit the form again but since we changed the value of our variable js wont be run and page can reload (and php can do whatever you told it to)
$("form:not('#press')").submit()
}
});
You can re-activate the actions by adding
this.delegateEvents(); // Re-activates the events for all the buttons
If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.