I am trying to capture the search query from google.com when the "enter" key is pressed.
I am using the following code to test that the event is actually being triggered:
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
This does not work when the focus is in the query box, but works fine otherwise I assume this is because an event is not being bubbled up by the auto-complete JS? Any ideas what might be happening, and how I can get the keypress event to fire when the focus is on the query box, which is the case when a query is being entered?
You can try $(window).on('keyup', function() {}); of you can bind the same handler to the search input.
Use "hashchange" event
It is triggered when triggered "auto-complete JS"
$(window).on("hashchange", function() {
var query = getKeywordsFromUrl(document.location.href);
} );
function getKeywordsFromUrl(href) {
var reStr = "google.com/search.*[&?]q=(.*?)(&.*)?$";
var rx = new RegExp(reStr, 'm');
if (rx.test(href)) {
var parts = rx.exec(href);
if (parts[1]) {
var terms = decodeURI(parts[1]).split("+");
return terms;
}
}
return null;
}
Related
I have this function of jquery for validation, how can it be changed to use with keypress events ?
function validate() {
var stateID = $("#purpose").val();
// var stateID = $(this).val();
if (stateID == '') {
var validformula = true;
var validweightq1 = true;
var newpar = true;
validformula = checkEmpty($("#formula"));
validweightq1 = checkEmpty($("#weg"));
newpar = checkEmpty($("#newparameter"));
$("#btn-submit").attr("disabled",true);
if(validweightq1 && validformula && newpar) {
$("#btn-submit").attr("disabled",false);
}
}
how to combine with on keypress ?
$(document).ready(function() {
$('#purpose').on('keypress', function(key) {})
})
You can make your function run when the keypress event is fired with:
$("#purpose").on('keypress', validate);
However, using the keypress event on a text input is generally a bad idea. It doesn't work on mobile devices, and it doesn't trigger when Backspace or Delete is pressed or text is pasted or cut in or out of the input. You should probably use the input event instead:
$("#purpose").on('input', validate);
$('#purpose').keyup(validate);
This is a complete revision of my initial question, all unnecessary resources and references were deleted
I am tying the same event listener to 2 different elements: a button and Enter key, and it looks like the following:
var funcelement = function(){
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click');
}
})
What I am trying to do is to prevent propagation of the enter key press if focus is on the submit button(#buttonID) by using preventDefault().
So I tried various combinations to make it work. The following is the latest result on my attempts
$('#inputID').keyup(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
After I enter a text into an input box and press Enter key, a confirmation window with yes/cancel buttons pops up with focus on yes button. Once I press Enter again, another window confirming that changes were made pops up with Ok button focused on it. Once I press Enter again, everything I need is being made.
However, there is one problem: after the last step is done, I am going back to the if (!hasfocus) line.
How do I prevent that from happening? Once the stuff I need is done - I don't want to go into that line again.
You can pass a parameter to into the function and stop the propagation there like so:
var funcelement = function(event, wasTriggeredByEnterKey){
if (wasTriggeredByEnterKey && $('#buttonID').is(':focus')) {
event.stopPropagation;
}
//function code
};
$('#buttonID').click(funcelement);
$('#inputID').keyup(function () {
if (event.which == 13) {
$('#buttonID').trigger('click', [true]);
}
}
)
UPDATE
In order to answer your revised issue, you should use the "keydown" event rather than "keyup" when working with alerts. This is because alerts close with the "keydown" event but then you are still triggering the "keyup" event when you release the enter key. Simply change the one word like this:
$('#inputID').keydown(function () {
var hasfocus = $('#buttonID').is(':focus') || false;
if (event.which == 13) {
if (!hasfocus) {
event.preventDefault();
$('#buttonID').trigger('click');
//hasfocus = true;
}
else {
//event.preventDefault();
//$('#buttonID').trigger('click');
}
}
})
I have created a simple code to handle keypress event:
var counter = 0;
$('input').on('keypress', function () {
$('div').text('key pressed ' + ++counter);
});
JSFiddle.
But keypress event handler is not raised on mobile browser (Android 4+, WindowsPhone 7.5+).
What could be the issue?
I believe keypress is deprecated now. You can check in the Dom Level 3 Spec. Using keydown or keyup should work. The spec also recommends that you should use beforeinput instead of keypress but I'm not sure what the support of this is.
Use the keyup event:
// JavaScript:
var counter = 0;
document.querySelector('input').addEventListener('keyup', function () {
document.querySelector('div').textContent = `key up ${++counter}`;
});
// jQuery:
var counter = 0;
$('input').on('keyup', function () {
$('div').text('key up ' + ++counter);
});
Use jQuery's input event, like this:
$( 'input' ).on( 'input', function() {
...
} );
With this you can't use e.which for determining which key was pressed, but I found a nice workaround here: http://jsfiddle.net/zminic/8Lmay/
$(document).ready(function() {
var pattForZip = /[0-9]/;
$('#id').on('keypress input', function(event) {
if(event.type == "keypress") {
if(pattForZip.test(event.key)) {
return true;
}
return false;
}
if(event.type == 'input') {
var bufferValue = $(this).val().replace(/\D/g,'');
$(this).val(bufferValue);
}
})
})
Yes, some android browser are not supporting keypress event, we need use to only keydown or keyup but will get different keycodes, to avoiding different key codes use the following function to get the keycode by sending char value.
Eg:
function getKeyCode(str) {
return str && str.charCodeAt(0);
}
function keyUp(){
var keyCode = getKeyCode("1");
}
I think it is bad idea to use other events in place of 'keypress'.
What you need to do is just include a jQuery file into your project.
A file named jQuery.mobile.js or quite similar (ex. jQuery.ui.js) of any version can help you.
You can download it from : https://jquerymobile.com/download/
I know we can use bind paste event as below:
$('#id').bind('paste', function(e) {
alert('pasting!')
});
But the problem is, that it will call before the pasted text paste. I want a function to be triggered after the right click -> paste text pasted on the input field, so that I can access the pasted value inside the event handler function.
.change() event also doesn't help. Currently I use .keyup() event, because I need to show the remaining characters count while typing in that input field.
Kind of a hack, but:
$("#id").bind('paste', function(e) {
var ctl = $(this);
setTimeout(function() {
//Do whatever you want to $(ctl) here....
}, 100);
});
Why not use the "input" event?
$("#id").bind('input', function(e) {
var $this = $(this);
console.log($this.val());
});
This will stop user from any pasting, coping or cutting with the keyboard:
$("#myField").keydown(function(event) {
var forbiddenKeys = new Array('c', 'x', 'v');
var keyCode = (event.keyCode) ? event.keyCode : event.which;
var isCtrl;
isCtrl = event.ctrlKey
if (isCtrl) {
for (i = 0; i < forbiddenKeys.length; i++) {
if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
return false;
}
}
}
return true;
});
This one will do the same for the mouse events:
$("#myField").bind("cut copy paste",function(event) {
event.preventDefault();
});
Even though the above one will not prevent right clicks, the user will not be able to paste, cut or copy from that field.
To use it after the event, like you wondered on your question, you must use JavaScript Timing Event
setTimeout(function() {
// your code goes here
}, 10);
I had the same issue, I opted to replicate the paste action through javascript and use that output instead:
var getPostPasteText = function (element, pastedData) {
// get the highlighted text (if any) from the element
var selection = getSelection(element);
var selectionStart = selection.start;
var selectionEnd = selection.end;
// figure out what text is to the left and right of the highlighted text (if any)
var oldText = $(element).val();
var leftPiece = oldText.substr(0, selectionStart);
var rightPiece = oldText.substr(selectionEnd, oldText.length);
// compute what the new value of the element will be after the paste
// note behavior of paste is to REPLACE any highlighted text
return leftPiece + pastedData + rightPiece;
};
See IE's document.selection.createRange doesn't include leading or trailing blank lines for source of the getSelection function.
No need to bind :
$(document).on('keyup input', '#myID', function () {
//Do something
});
I just wrote this nifty little function which works on the form itself...
$("#form").keypress(function(e) {
if (e.which == 13) {
var tagName = e.target.tagName.toLowerCase();
if (tagName !== "textarea") {
return false;
}
}
});
In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?
You can mimic the tab key press instead of enter on the inputs like this:
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.
Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:
<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
Here is a modified version of my function. It does the following:
Prevents the enter key from working
on any element of the form other
than the textarea, button, submit.
The enter key now acts like a tab.
preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.
So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
}
From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.
The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.
<body OnKeyPress="return disableKeyPress(event)">
The javascript code should be:
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">
Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.
By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.
In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.
$(document).on( 'keypress', '.input_class', function (e) {
if (e.charCode==13) {
$(this).parent('.container').children('.button_class').trigger('click');
return false;
}
});
In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.
Note that the input and the button have to be in the same container.
The previous solutions weren't working for me, but I did find a solution.
This waits for any keypress, test which match 13, and returns false if so.
in the <HEAD>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.which == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
I prefer the solution of #Dmitriy Likhten, yet:
it only worked when I changed the code a bit:
[...] else
{
if (focusNext){
$(this).focus();
return false; } //
}
Otherwise the script didn't work.
Using Firefox 48.0.2
I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.
$(document).ready(function () {
$("#item-form").keypress(preventEnterSubmit);
});
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
if (this === e.target) {
focusNext = true;
} else {
if (focusNext) {
$(this).focus();
return false;
}
}
});
return false;
}
}
}