Can we stop checkout process on woocommerce using javascript manually? - javascript

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!

Related

KeyDown event for CKeditor

In my application I have an instance of a CKEditor. While the user is entering text into the editor the first latter should be in uppercase. For that I wrote a jQuery keydown event handler, like this:
$(document).ready(function () {
CKEDITOR.instances.CKEditor1.on('contentDom', function () {
CKEDITOR.instances.CKEditor1.document.on('keydown', function (event) {
if (this.selectionStart == 0 && event.keyCode >= 65 && event.keyCode <= 90 && !(event.shiftKey) && !(event.ctrlKey) && !(event.metaKey) && !(event.altKey)) {
var $t = $(this);
event.preventDefault();
var char = String.fromCharCode(event.keyCode);
$t.val(char + $t.val().slice(this.selectionEnd));
this.setSelectionRange(1, 1);
}
});
});
});
It gives an runtime error i.e,
0x800a138f - JavaScript runtime error: Unable to get property 'on' of undefined or null reference
How can I create keydown event for ckeditor.(the above code I wrote in .aspx page)
You can achieve this with the following code.
CKEDITOR.replace( 'editor1', {
on: {
instanceReady: function() {
alert( this.name ); // 'editor1'
},
key: function() {
setTimeout(function(){
console.log('key pressed');
},1);
}
}
});
Without the setTimeout function the editor cannot capture the last key pressed.
CKEditor version 4.x
I believe you're registering the contentDom event the wrong way.
To instantiate CKEDITOR and register the contentDom event you'd do
CKEDITOR.replace( 'editor1', {
on: {
instanceReady: function() {
alert( this.name ); // 'editor1'
var editor = this;
editor.on( 'contentDom', function() {
var editable = editor.editable();
editable.attachListener( editable, 'click', function() {
console.log( 'The editable was clicked.' );
});
});
}
}
} );
Your code is trying to access the CKEDITOR instance before it has finished instantiating.
More information can be found at http://docs.ckeditor.com/#!/api/CKEDITOR.config and http://docs.ckeditor.com/#!/api/CKEDITOR.editor-event-contentDom

Google site search catch search submit and trigger function

I have a page with just a searchbox on provided by google
<gcse:search></gcse:search>
Now when I type in the search box and hit enter I would like to trigger my script to run as the search results gets returned.
Things I have tried sofar
Here I tried to use the submit event to trigger my script
$(document).on('submit', 'input', function(e) {
alert('trig');
}
Here I tried to catch the enter key as I have removed the search button
$(document).keypress(function(e) {
alert('triggered');
});
Here I tried to catch the focus on the form id
$('#gsc-i-id1').focus().trigger(function(e) {
alert('triggered');
});
All unsuccessfull
Here is a list of id's and classes the gcse tag creates
#___gcse_0
.gsc-control-cse .gsc-control-cse-en
.gsc-control-wrapper-cse
.gsc-search-box .gsc-search-box-tools
.gsc-search-box
.gsc-input
#gsc-iw-id1
#gs_id50
#gs_tti50
#gsc-i-id1
Using the following CODE snippet you'll be able to capture keyboard event on enter key press in the search input field and mouse click event on the search button.
Note: This answer only captures keyboard enter & search button click events (as asked in the original question). I've added another answer that is similar, but also auto re-populates search result on every valid keystroke.
(function($, window) {
var elementName = '';
var initGCSEInputField = function() {
$( '.gcse-container form.gsc-search-box input.gsc-input' )
.on( "keyup", function( e ) {
if( e.which == 13 ) { // 13 = enter
var searchTerm = $.trim( this.value );
if( searchTerm != '' ) {
console.log( "Enter detected for search term: " + searchTerm );
// execute your custom CODE for Keyboard Enter HERE
}
}
});
$( '.gcse-container form.gsc-search-box input.gsc-search-button' )
.on( "click", function( e ) {
var searchTerm = $.trim( $( '.gcse-container form.gsc-search-box input.gsc-input' ).val() );
if( searchTerm != '' ) {
console.log( "Search Button Click detected for search term: " + searchTerm );
// execute your custom CODE for Search Button Click HERE
}
});
};
var GCSERender = function() {
google.search.cse.element.render({
div: 'gcse_container',
tag: 'search'
});
initGCSEInputField();
};
var GCSECallBack = function() {
if (document.readyState == 'complete') {
GCSERender();
}
else {
google.setOnLoadCallback(function() {
GCSERender();
}, true );
}
};
window.__gcse = {
parsetags: 'explicit',
callback: GCSECallBack
};
})(jQuery, window);
(function() {
var cx = '017643444788069204610:4gvhea_mvga'; // Insert your own Custom Search engine ID here
var gcse = document.createElement('script'); gcse.type = 'text/javascript'; gcse.async = true;
gcse.src = 'https://www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gcse-container" id="gcse_container">
<gcse:search enableAutoComplete="true"></gcse:search>
</div>
The above CODE snippet uses Google Custom Search element control API.

Unsure how to perform action if all form inputs do NOT contain specific values

This is more of a question on how to approach this scenario.
I have a form, and I need to perform an action if any form input contains ".ca", "canada" or "canadian", but I also need to reverse that action if the fields do NOT contain these strings. Ideally, this would action would trigger (if needed) as the form is completed rather than when submit is clicked.
My code to check for ".ca", "canada", or "canadian"
var optInFieldIsVisible = false;
var optInField = jQuery( 'input[name*="email"]' );
jQuery("*").find('input').bind('input propertychange', function() {
if (/.ca$|canada|canadian/i.test( jQuery(this).val() ) ) {
optInFieldIsVisible = true;
optInField.closest( '.formField' ).show();
// show special form field because reference to canada is present
}
else {
if (optInFieldIsVisible == false) {
optInField.closest( '.formField' ).hide();
// hide special form field because reference to canada is removed
}
});
The problem with the above code is that it has no condition that is ever valid for the special field will never re-hide once it is activated.
If I remove the "if (optInFieldIsVisible == false)" under the else-condition the field will show and hide properly if the user works within the currently selected input, BUT it will then re-hide as soon as anything is typed into the next input (since the regex returns false in the now-selected new form input).
Clearly a flag variable isn't the solution, and some sort of counter variable I also can't see as working here. Does anyone have pointers?
EDIT:
See live demo http://jsbin.com/toyin/1/edit
I'm not sure I understand you correctly, but this may be what you want:
var optInFieldIsVisible = false;
var optInField = jQuery( 'input[name*="email"]' );
jQuery("*").find('input').bind('input propertychange', function() {
if (/.ca$|canada|canadian/i.test( jQuery(this).val() && !optInFieldIsVisible ) ) {
optInFieldIsVisible = true;
optInField.closest( '.formField' ).show();
// show special form field because reference to canada is present
}
else if (optInFieldIsVisible){
optInFieldIsVisible = false;
optInField.closest( '.formField' ).hide();
// hide special form field because reference to canada is removed
}
});
Checkout the fiddle, is it the thing you want to do?
var optInFieldIsVisible = false;
var optInField = jQuery( 'input[name*="opt-in"]' );
optInField.closest( 'div.formField' ).hide();
jQuery("*").find('input').bind('input propertychange', function() {
if (/.ca$|canada|canadian/i.test( jQuery(this).val() ) ) {
optInFieldIsVisible = true;
optInField.closest( 'div.formField' ).show();
}
else {
optInFieldIsVisible = false;
optInField.closest( 'div.formField' ).hide();
}
});
This is what I came up with to address this. Added a new function:
/* clear required field on focusout if triggers are removed from all fields */
jQuery("*").find('input').focusout(function(){
var eList = [];
jQuery("*").find('input').each( function() {
if ( /.ca$|canada|canadian/i.test( jQuery(this).val() ) == false ) {
eList.push(false);
}
else {
eList.push(true);
}
})
if ( jQuery.inArray(true, eList )==-1 ) {
optInField.closest( '.formField' ).hide();
}
})
Also removed the else statement from my original code, as that was no longer needed with the above added. See http://jsbin.com/toyin/3/edit

Handling "onclick" event with pure JavaScript

This is really straight forward but I'm still fairly new to JavaScript and just found JSFiddle. I'm trying to find the element with the getElementById() to disable and enable a button. What am I missing?
<form name="frm" >
<div id="chkObj">
<input type="checkbox" name="setChkBx" onclick="basicList.modifyAndEnableButton(this)"></input>
</div>
<div id="Hello">
<input type="button" name="btn" value="Hello"></input>
</div>
</form>
This is a list that I am using to add checkboxes because there is going to be more than one:
var basicList = {
'items': {},
'modifyAndEnableButton': function(obj1) {
var element = document.getElementsByName("btn");
if (obj1.checked == true && element.getAttribute('disabled') == false) {
element.getAttribute('disabled') = true;
this.addRecord(obj2);
} else if (element.getAttribute('disabled') == true) {
if (hasItems == false) {
element.getAttribute('disabled') = false;
}
}
}
};
http://jsfiddle.net/Arandolph0/E9zvc/3/
All browsers support this (see example here):
mySelectedElement.onclick = function(e){
//your handler here
}
However, sometimes you want to add a handler (and not change the same one), and more generally when available you should use addEventListener (needs shim for IE8-)
mySelectedElement.addEventListener("click",function(e){
//your handler here
},false);
Here is a working example:
var button = document.getElementById("myButton");
button.addEventListener("click",function(e){
button.disabled = "true";
},false);
And html:
<button id='myButton'>Hello</button>
(fiddle)
Here are some useful resources:
addEventListener on mdn
The click event in the DOM specification
Click example in the MDN JavaScript tutorial
Benjamin's answer covers quite everything. However you need a delegation model to handle events on elements that were added dynamically then
document.addEventListener("click", function (e) {
if (e.target.id == "abc") {
alert("Clicked");
}
});
For IE7/IE8
document.attachEvent('onclick', function (e) {
if (window.event.srcElement == "abc") {
alert("Clicked");
}
});
You have a Error here
btnRush should be Rushbtn
This is a example of cross browser event's I just made (not tested) )
var addEvent = function( element, type, callback, bubble ) { // 1
if(document.addEventListener) { // 2
return element.addEventListener( type, callback, bubble || false ); // 3
}
return element.attachEvent('on' + type, callback ); // 4
};
var onEvent = function( element, type, callback, bubble) { // 1
if(document.addEventListener) { // 2
document.addEventListener( type, function( event ){ // 3
if(event.target === element || event.target.id === element) { // 5
callback.apply(event.target, [event]); // 6
}
}, bubble || false);
} else {
document.attachEvent( 'on' + type, function( event ){ // 4
if(event.srcElement === element || event.srcElement.id === element) { // 5
callback.apply(event.target, [event]); // 6
}
});
}
};
Steps
Create a function that accepts 4 values ( self explaining )
Check if the browser supports addEventListener
Add event on the element
else add event on the element for older IE
Check that the (clicked) element is = to the passed element
call the callback function pass the element as this and pass the event
The onEvent is used for event delegation.
The addEvent is for your standard event.
here's how you can use them
The first 2 are for dynamically added elements
onEvent('rushBtn', 'click', function(){
alert('click')
});
var rush = document.getElementById('rushBtn');
onEvent(rush, 'click', function(){
alert('click');
});
// Standard Event
addEvent(rush, 'click', function(){
alert('click');
});
Event Delegation is this basically.
Add a click event to the document so the event will fire whenever & wherever then you check the element that was clicked on to see if it matches the element you need. this way it will always work.
Demo

what could prevent keydown events from being fired in IE8?

I've made an editable implementation which behaviour is:
dblclick on element makes it editable:
an input is created
element contents emptied
input appended to element
attach keydown event handler to input, to disable edition when user presses Enter
idem with blur event
It works fine in decents browsers, but it breaks on IE8.
there are two problems:
input.focus() will call the blur event handler (wtf??)
keystrokes won't generate events intercepted by keydown handler, so my handler to validate when enter is hit don't work
I checked clicks events on the input and they are fine
The thing is it still works if I run the sample in a minimalist sample, but in my application, it won't.
what could prevent those keydown events from being fired / catch ?
here's the implementation:
widget.Editable = function( el, options ) {
this.element = $(el).addClass('editable');
this.value = this.element.text();
var _that = this;
this.element.dblclick( function(e) {
_that.enableEdition();
} );
};
widget.Editable.prototype = {
disableEdition: function( save, e ) {
this.value = this.input.val();
this.input.remove();
this.element.text( this.value ).removeClass('dragDisable');
this.editionEnabled = false;
this.onupdate( e, this.value, this.element );
},
/**
* enables the field for edition. Its contents will be placed in an input. Then
* a hit on "enter" key will save the field.
* #method enableEdition
*/
enableEdition: function() {
if (this.editionEnabled) return;
var _that = this;
this.value = this.element.text();
this.input = $( document.createElement('input') ).attr({
type:'text',
value:this.value
});
this.element
.empty().append( this.input )
.addClass('dragDisable'); //We must disable drag in order to not prevent selection
this.input.keydown( function(e) {
IScope.log('keydown editable:', e );
switch ( e.keyCode ) {
case 13:
_that.disableEdition( true );
break;
default:
break;
}
} );
this.input.click( function() {
console.log('input clicked');
});
//if ( !YAHOO.env.ua.ie )
// this.input.blur( function( e ) {
// IScope.log( "editable blurred", e );
// _that.disableEdition( true );
// });
//this.input.focus();
this.editionEnabled = true;
}
};

Categories

Resources