Google site search catch search submit and trigger function - javascript

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.

Related

Autosuggest textarea when press key on virtual keyboard using javascript

I'm working on virtual keyboard with autosuggestion. I found hundreds of ready made example on internet. But all these autocomplete javascript code working only on keyboard key press. I'm very new to javascript. Can anyone help me to show autosuggest when i press mouse on a virtual keyboard button's key. My code is given below which is working good in keyboard key press.
$(function() {
var availableTags = [
"computer",
"keyboard",
"mouse",
];
var minWordLength = 1;
function split(val) {
return val.split(' ');
}
function extractLast(term) {
return split(term).pop();
}
$("#note-textarea")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: minWordLength,
source: function(request, response) {
// delegate back to autocomplete, but extract the last term
var term = extractLast(request.term);
if (term.length >= minWordLength) {
response($.ui.autocomplete.filter(availableTags, term));
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(" ");
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Can we stop checkout process on woocommerce using javascript manually?

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!

Javascript Error /[qwertyuiopasdfghjklzx-cvbnm?.//:&#!]/: Range out of order in character class

So when i type it into the console this error pointing to /[qwertyuiopasdfghjklzx-cvbnm?.//:&#!]/: Range out of order in character class . I tried pressing i and it would come up with the same thing. This is a script for https://web.roblox.com. I'm using the replace() on a string and that where the error is.
/*
Version 0.1
Press i to get id
Please read the settings
*/
//Settings
//Welcome Message
var welcomemsg = "Off";//Write On or Off
//Functions
function welcome()
{
if (welcomemsg == "On") {
window.alert("Welcome id getter loaded press i when on an id page to get item id")
}
else if (welcomemsg == "Off") {
console.log("Welcome id getter loaded press i when on an id page to get item id")
}
}
(function () { var script = document.createElement('script'); script.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js'); document.body.appendChild(script);}());
window.onload = function() {
load()
};
function load()
{
$( "body" ).on( "keydown", function( event ) {
if (event.type === "keydown" && event.which === 73){
get();
}
$( "#log" ).html( event.type + ": " + event.which );
});
}
function get()
{
var id = window.location.href.split("=").pop().replace(/[qwertyuiopasdfghjklzx-cvbnm?.//:&#!"]/g, "")
if (id == "") {
alert("Your not into an profile, model ,gear page or place!")
}
else {
window.prompt("Id:", id)
}
}
//Running functions
welcome()
You have a "-" character in there, and "x-c" is interpreted as a range (which is, for obvious reasons, invalid). Try escaping the - with a backslash ().

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

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