Can we stop checkout process on woocommerce using javascript manually?
I am using this code for submit and want to stop process if certain condition occurs. I tried return false but it doesn't work.
JQuery("form.woocommerce-checkout").on('submit', function() {
var np = $('#notepopup').val();// val = 0
if(ne == 0){
return false;
}
});
please suggest something
You can prevent the form from submitting by prevent its default behavior (submit):
$("form.woocommerce-checkout").on('submit', function(e) {
if(ne == 0){
e.preventDefault();
}
});
More doc on preventDefault().
Edit
Using these alerts,
$("form.woocommerce-checkout").on('submit', function(e) {
alert("Before if ");
if(ne == 0){
alert("Inside if ");
e.preventDefault();
}
alert("After if ");
});
When exactly do you see you form submitted?
Event Relay with Validator
Figured out a way of doing this by building a kind of Relay system for the submit events attached to the checkout.
Just treat the "canSubmit()" as your event handler and return true only if you want the checkout form to submit as normal.
( ($) => {
var confirmDetails = true;
function canSubmit( e ) {
// Handle event here. Return true to allow checkout form to submit
return false;
}
function init() {
// Use set timeout to ensure our $( document ).ready call fires after WC
setTimeout( () => {
var checkoutForm = $( 'form.checkout' );
// Get JQuery bound events
var events = $._data( checkoutForm[0], 'events' );
if( !events || !events.submit ) {
return;
}
// Save Submit Events to be called later then Disable Them
var submitEvents = $.map( events.submit, event => event.handler );
$( submitEvents ).each( event => checkoutForm.off( 'submit', null, event ) );
// Now Setup our Event Relay
checkoutForm.on( 'submit', function( e ) {
e.preventDefault();
var self = this;
if( !canSubmit( ...arguments ) ) {
return;
}
// Trigger Event
$( submitEvents ).each( ( i, event ) => {
var doEvent = event.bind( self );
doEvent( ...arguments );
} );
} );
}, 10);
}
$( document ).ready( () => init() );
} )( jQuery );
For anyone looking for a solution this now, the below code worked for me. It needs jQuery(document).ready(function($) and to use the event checkout_place_order to work like so:
jQuery(document).ready(function($) {
jQuery("form.woocommerce-checkout").on('checkout_place_order', function(e) {
console.log("Submission Stopped");
return false;
});
});
If you require WooCommerce's validation to run first before stopping the checkout, there is a solution here!
I have a form with CSS animations, when form field is selected labels animate out and when text is filled labels shouldn't animate back. And this works for input fields but not with textarea. Can't seem to find the problem, and I've been playing with it for some time now.
This is my JS code:
<script>
(function() {
// trim polyfill : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim
if (!String.prototype.trim) {
(function() {
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
String.prototype.trim = function() {
return this.replace(rtrim, '');
};
})();
}
[].slice.call( document.querySelectorAll('input.input_field', 'input-textarea.input_field-textarea') ).forEach( function( inputEl ) {
// in case the input is already filled..
if( inputEl.value.trim() !== '' ) {
classie.add( inputEl.parentNode, 'input--filled' );
}
// events:
inputEl.addEventListener( 'focus', onInputFocus );
inputEl.addEventListener( 'blur', onInputBlur );
} );
function onInputFocus( ev ) {
classie.add( ev.target.parentNode, 'input--filled' );
}
function onInputBlur( ev ) {
if( ev.target.value.trim() === '' ) {
classie.remove( ev.target.parentNode, 'input--filled' );
}
}
})();
</script>
EDIT: This was the problem, code was going like this:
document.querySelectorAll('textarea.input_field-textarea', 'input.input_field'))
Instead of removing those 2 extra '':
document.querySelectorAll('textarea.input_field-textarea, input.input_field'))
Thanks to all for help!
Change the input-textarea.input_field-textarea selector to textarea.input_field-textarea. There's no such <input-textarea/> element:
[].slice.call(document.querySelectorAll('input.input_field', 'textarea.input_field-textarea')).forEach(function(inputEl) {
// ...
});
I need your help.
I have some submit buttons with an animation, here is a working demo:
http://plnkr.co/edit/KhDdXWYnj3kVxhiKaEFL
But now the submit don't works, just ask and play animation. not submit the form
<button type="submit" name="send_approve" onClick="return message1()" class="progress-button" data-style="rotate-back" data-perspective data-horizontal>Enviar </button>
this is the code for animation:
[].slice.call( document.querySelectorAll( 'button.progress-button' ) ).forEach( function( bttn ) {
new ProgressButton( bttn, {
callback : function( instance ) {
var progress = 0,
interval = setInterval( function() {
progress = Math.min( progress + Math.random() * 0.1, 1 );
instance._setProgress( progress );
if( progress === 1 ) {
instance._stop(1);
clearInterval( interval );
}
}, 200 );
}
} );
} );
Before to the animation I had this and works fine, but now I just want press button, animation and submit without confirm validation
function message1() {
var r = confirm("¿ Sure to submit ?");
if (r == true) {
return true;
}
else {
alert('it didnt work');
return false;
}
}
You know how can I do that ?
Thanks for your help !
Well, first make sure you remove that onclick attribute if you don't want to prompt that question anymore.
Second, make sure your button, along with all the other fields, is wrapped inside a form tag, like this:
<form name="theForm" method="GET" action="http://www.google.ro/search">
<input name="q" type="text" placeholder="enter search keyword" />
<button type="submit" <!-- rest of the attributes except for onclick -->>
<!-- rest of the content, like those spans go here -->
</button>
</form>
Third, in JS, after the progress is done just submit the form:
if ( progress === 1 ) {
instance._stop(1);
clearInterval( interval );
document.forms["theForm"].submit();
}
I know this is simple but I cant get the conditional if below to work...
This line below " if ( !$section.id == "no-transition" ) " is not correct.
I'm trying to stop javascript from working on section elements that have the id of "no-transition".
Can someone point me in the right direction?
function initEvents() {
$sections.each( function() {
var $section = $( this );
if ( !$section.id == "no-transition" ) {
// expand the clicked section and scale down the others
$section.on( 'click', function() {
[code taken out to shorten post...]
if( !supportTransitions ) {
$section.removeClass( 'bl-expand-top' );
}
$el.removeClass( 'bl-expand-item' );
return false;
} );
}
} );
You really should not have multiple elements with the same id on a page.
Your if condition should be modified to:
...
if ( $section.attr('id') != "no-transition" ) {
...
Is there a way to programmatically trigger the onmouseover event in plain JavaScript? or "extract" the method from the onmouseover event to call it directly?
eg
<div id="bottom-div" onmouseover="myFunction('some param specific to bottom-div');">
<div id="top-div" onmouseover="????????"></div>
</div>
top-div is above bottom-div, so the onmouseover won't get fired in bottom-div. i need a way of calling myFunction('some param specific to bottom-div'); from top-div
const mouseoverEvent = new Event('mouseover');
whateverElement.dispatchEvent(mouseoverEvent);
This worked for me in IE9 at least. Should be cross-browser compatible or close to it...
function FireEvent( ElementId, EventName )
{
if( document.getElementById(ElementId) != null )
{
if( document.getElementById( ElementId ).fireEvent )
{
document.getElementById( ElementId ).fireEvent( 'on' + EventName );
}
else
{
var evObj = document.createEvent( 'Events' );
evObj.initEvent( EventName, true, false );
document.getElementById( ElementId ).dispatchEvent( evObj );
}
}
}
For onmouseover example, call the function like this
FireEvent( ElementId, "mouseover" );
For me following worked:
document.getElementById('xyz').dispatchEvent(new MouseEvent('mouseover', { 'bubbles': true }));
Also:
document.getElementById('xyz').dispatchEvent(new MouseEvent('mouseover', { 'view': window, 'bubbles': true, 'cancelable': true }));
Without going into too much detail, I had an img with rollovers, i.e. mouseout/overs that set the img src to hidden form values (or this could have done in a different context with gloabl variables). I used some javascript to swap both of my over/out image values and I called the called FireEvent( ElementId, "mouseover" ); to trigger the change. My javascript was hiding / displaying elements on the page. This caused the cursor to sometimes be over the img I used to trigger the event - which was the same as the one I was swapping out, and sometimes the cursor was not over the img after the click.
Mouseover/out does not fire unless you exit and re-enter an element, so after my event was triggered the mouseover/out needed "retriggering" to account for the new cursor position. Here is my solution. After I hide / display various page elements, and to do my img src swapping as described, I call the function RefreshMouseEvents( ElementId ) instead of FireEvent( ElementId, "mouseover" ).
This works in IE9 (not sure about other browsers).
function RefreshMouseEvents( ElementId )
{
FireEvent( ElementId, 'mouseover' );
setTimeout( "TriggerMouseEvent( '" + ElementId + "' )" , 1 );
}
function TriggerMouseEvent( ElementId )
{
if( IsMouseOver( ElementId, event.clientX, event.clientY ) )
FireEvent( ElementId, 'mouseover' );
else
FireEvent( ElementId, 'mouseout' );
}
function IsMouseOver( ElementId, MouseXPos, MouseYPos )
{
if( document.getElementById(ElementId) != null )
{
var Element = document.getElementById(ElementId);
var Left = Element.getBoundingClientRect().left,
Top = Element.getBoundingClientRect().top,
Right = Element.getBoundingClientRect().right,
Bottom = Element.getBoundingClientRect().bottom;
return ( (MouseXPos >= Left) && (MouseXPos <= Right) && (MouseYPos >= Top) && (MouseYPos <= Bottom))
}
else
return false;
}
function FireEvent( ElementId, EventName )
{
if( document.getElementById(ElementId) != null )
{
if( document.getElementById( ElementId ).fireEvent )
{
document.getElementById( ElementId ).fireEvent( 'on' + EventName );
}
else
{
var evObj = document.createEvent( 'Events' );
evObj.initEvent( EventName, true, false );
document.getElementById( ElementId ).dispatchEvent( evObj );
}
}
}
I had to revise my RefreshMouseEvents set of functions after more testing. Here is the seemingly perfected version (again only IE9 tested):
function RefreshMouseEvents( ElementId )
{
FireEvent( ElementId, 'mouseover' );
setTimeout( "TriggerMouseEvent( '" + ElementId + "', '" + event.clientX + "', '" + event.clientY + "' )", 1 );
}
function TriggerMouseEvent( ElementId, MouseXPos, MouseYPos )
{
if( IsMouseOver( ElementId, (1*MouseXPos), (1*MouseYPos) ) )
FireEvent( ElementId, 'mouseover' );
else
FireEvent( ElementId, 'mouseout' );
}
function IsMouseOver( ElementId, MouseXPos, MouseYPos )
{
if( document.getElementById(ElementId) != null )
{
var Element = document.getElementById(ElementId);
var Left = Element.getBoundingClientRect().left,
Top = Element.getBoundingClientRect().top,
Right = Element.getBoundingClientRect().right,
Bottom = Element.getBoundingClientRect().bottom;
return ( (MouseXPos >= Left) && (MouseXPos <= Right) && (MouseYPos >= Top) && (MouseYPos <= Bottom))
}
else
return false;
}
function FireEvent( ElementId, EventName )
{
if( document.getElementById(ElementId) != null )
{
if( document.getElementById( ElementId ).fireEvent )
{
document.getElementById( ElementId ).fireEvent( 'on' + EventName );
}
else
{
var evObj = document.createEvent( 'Events' );
evObj.initEvent( EventName, true, false );
document.getElementById( ElementId ).dispatchEvent( evObj );
}
}
}
I needed to do something similar, but I'm using jQuery, and I found this to be a better solution:
Use jQuery's trigger function.
$j('#top-div' ).trigger( 'mouseenter' );
You can also add parameters to it if you need to. See the jQuery documentation on .trigger.
<a href="index.html" onmouseover="javascript:alert(0);" id="help">help</a>
document.getElementById('help').onmouseover();
I was working with Angular and trying to do a similar thing.
I fall on this answer from StackOverflow Click here
Basically the idea is to add and remove the hover class
public addHoverOnClick() {
const yourElement = document.getElementById('elementID') as HTMLElement;
yourElement .classList.add('hover')
}
public removeHoverOnClick() {
const yourElement = document.getElementById('elementID') as HTMLElement;
yourElement .classList.remove('hover')
}
You would do it something like this:
document.getElementById('top-div').onmouseover();
However, as mentioned in the comments, it would be worth testing before being considered an issue.