I tried sendkeys plugin and others.
Is there a way to simulate Enter key pressed without element?
$("div.myclass").click(); // Put focus on my element - works
$("div.myclass span").sendkeys("Test"); // using sendkeys plugin send the input - works.
setTimeout(function(){
console.log('trigger');
//$("div._1mf").trigger({type: 'keydown', key: 'enter'}); // this one just insert new line...
e = jQuery.Event("keypress")
e.which = 13
$("div.myclass").keypress(function(){ // this one doesn't work
}).trigger(e)
},2000);
I have already element focused and input inserted, I need just simulate Enter press key to send the text, how that can be done?
I think what you might want to do is instead, submit the form that your input resides in?
Related
I'm trying to fire off a search programatically having populated the input.
Can't find a clear Javascript example of that though. Jquery not really an option as i want to keep this a lightweight Chrome Extension.
Emitting the 'Enter' event just seems to return a true with no search actually beginning.
HTML
<form id="form">
<input type="text" placeholder="Search Foo" />
</form>
Javascript
const input = document.querySelector(`input[placeholder="Search Foo"]`);
// ^^ targets element successfully
input.value = "this is my search term";
// ^^ adds value to input fine.
input.dispatchEvent(new Event('focus'));
// ^^ appears to focus correctly
input.dispatchEvent(new KeyboardEvent('keyup',{'keyCode': 13}));
// ^^ returns 'true' in console but nothing happens.
const form = document.getElementById("form");
form.submit();
// ^^ triggers a full page refresh, not an 'enter' / submit action.
I have tried a few variations around this (deprecated KeyEvents syntax mostly).
Why can't I actually fire off 'Enter' / submit on the input/form?
You could also put the input in a form element and then call form.submit() on the form element.
Pressing even is triggering an event you need to find what event the code is listening to the below would work for keyup event
var evt = new CustomEvent('keyup');
evt.which = 13;
evt.keyCode = 13;
input.dispatchEvent(evt);
Have a look at this answer it might help https://stackoverflow.com/a/29720843/13335890
I'm trying to create a simple submit form in WYSIWYG Web Designer 10 but I have a BIG problem with Enter key. There are several edit boxes on the form and I'd like to have the following functionality (via JavaScript):
1. Enter key on an Edit Box should not submit the form.
2. Enter key on an Edit Box should set focus to the following element (edit box or a submit button). Submit button is the last element in tabIndex order.
3. To submit the form user must:
either click the submit button,
or press Enter when the submit button has the focus.
4. Must work in any browser.
This is a snippet that works quite good (it sets focus to the next element):
var elem = document.activeElement;
var tidx = +(elem.getAttribute('tabindex')) +1,
elems = document.getElementsByTagName('input');
for (var i=elems.length; i--;)
{
var tidx2 = elems[i].getAttribute('tabindex');
if (tidx2 == tidx) elems[i].focus();
}
The only problem I have is Enter key (keyCode) validation which should precede the code to change focus. I have been testing in FF 32, PaleMoon 25 (FF clone), Chrome 38 & IE 10.
Thank you very much for your time in advance.
P.S. I'm a newbie in JavaScript. I use to work with MS Access where similar problem would be solved within two minutes.
I have spent several hours on this simple task but no luck. I have tried many examples that I've found on the web (incl. stackoverflow.com). As to event handling (where I'm trying to test the keyCode) various browsers behave differently.
I tried and mixed a lot of found in web and created this one.
So far it's working for me... just give it a try
$(document).on('keypress', 'input, select, checkbox, radio, button', function (e) {
return focusNextOnEnter(e, this);
})
and the function somewhere in your JS file.
function focusNextOnEnter(e, selector) {
var longSelector = 'input:visible:enabled:not([readonly="readonly"]), textarea:visible:enabled:not([readonly="readonly"]), select:visible:enabled, button:visible:enabled';
var keyCode = e.keyCode || e.which;
if ($(selector).is(':not(textarea)') // it's not a textarea - enter in text area
&& keyCode === 13 // it's enter key
&& !($(selector).attr('id') === 'submitButton')) // it's not submitButton, save-on-enter here
{
e.preventDefault();
$(longSelector)[$(longSelector).index($(selector)) + 1].focus();
return true;
}
}
instead of the last check
$(selector).attr('id') === 'submitButton'
you can always check
$(selector).is('[type="submit"]')
this will hopefully return what you are looking for i.e. submit on enter on submit button
I have the following input element on my page:
<input class="input" name="custom_fields[new]" placeholder="Enter placeholder" type="text">
I have a Twitter Flight event listener on this element that looks like this:
this.on('keyup', {
inputsSelector: this.updateViewInputs
});
Which triggers this method:
this.updateViewInputs = function(ev) {
var isDeletionKeycode = (ev.keyCode == 8 || ev.keyCode == 46);
// Remove field is user is trying to delete it
if (isDeletionKeycode && this.shouldDeleteInput(ev.target.value, this.select('inputsSelector').length)) {
$(ev.target.parentNode).remove();
}
// Add another field dynamically
if (this.select('lastInputsSelector')[0] && (ev.target == this.select('lastInputSelector')[0]) && !isDeletionKeycode) {
this.select('inputsContainer').append(InputTemplate());
}
// Render fields
that.trigger('uiUpdateInputs', {
inputs: that.collectInputs()
});
}
And finally triggers uiUpdateInputs:
this.after('initialize', function() {
this.on(document, 'uiUpdateInputs', this.updateInputs)
});
this.updateInputs = function(ev, data) {
// Render all inputs provided by user
this.select('inputListSelector').html(InputsTemplate({ inputs: data.inputs }));
}
All of this functionality works as expected on Chrome and Firefox. Users can type into the input and see the page change in 'real time'. Users also get additional fields that they can enter text into and see the page change.
The issue in question arises when using Safari, as a user enters text into the described input field the text in the input field becomes highlighted (selected) and when they enter the next character all the content is replaced with that single character. This results in the user not being able to enter more than 1 or 2 characters before having them all replaced by the next entered character.
I have tried several approaches to fix this problem but none have worked, they include:
Using a setTimeout to delay the code run on the keyup event
Using Selection to try to disable the selection of the text using collapseToEnd.
Using click,focus,blur events to try to remove the selection from the entered text
Triggering a right arrow key event to try to simply move the cursor forward so they user does not delete the selected text
Using setInterval to routinely remove selections made by the window
I am very confused why this is happening and I am wondering if this is a bug in webkit with Flight. I see no issue with the Firefox or Chrome versions of this page. Thanks for any help!
This seems to be an issue with certain versions of Safari. When listening for the keyup function in javascript it will automatically select all of the text in the box and subsequently delete it all when the next key is typed. To prevent this from happening call preventDefault on the event object that is passed to the keyup function.
this.on('keyup', function(e) {
e.preventDefault()
});
I need to have an input textbox in which I can click and the cursor starts blinking but the user cannot change any text inside it.
I tried using "readonly" or "disabled" attributes, but they do not allow the cursor to be inside the textbox. So, I was thinking of a solution to implement in JavaScript on a normal textbox. Is there a plugin that already do this? How do I implement this?
EDIT: Thanks for all the answers, but I wanted to make the textarea/input type text as uneditable but selectable at the same time. Pressing Ctrl + A inside the textbox doesn't work. Is it possible to get the changed value and the old value and compare them and then return false if the values are different, but in all other cases return true so that the Ctrl + A, Shift + end, etc. combinations work?
Something like this:
<textarea onkeydown="javascript:return false;"></textarea>
would do the trick. (jsfiddle)
You can also do that at runtime if you want to:
<textarea class="readonly"></textarea>
with
$(".readonly").keydown(function() false);
The onkeydown callback captures keystroke events and cancels them using return false;.
Depending on what you are trying to do, you may want to prevent other kind of events, since it is still possible to change the contents with the mouse, for instance.
Your callback function can accept or cancel events depending of the kind of keystroke. For example, to enable only ctrl-a and ctrl-c (with jQuery):
function keydown(e) {
if(!e.ctrlKey) return false; // Cancel non ctrl-modified keystrokes
if(e.keyCode == 65) return true;// 65 = 'a'
if(e.keyCode == 67) return true;// 67 = 'c'
return false;
}
$(function(){
$("inputSelector").keydown(function(){ return false; });
});
You cannot rely on disabling a <textarea> as a user input, as it's trivial to remove any sort of HTML or javascript disabling with firebug, or other tools. Remember that forms aren't limited to the fields you give them, anyone can submit any data to a page.
Disabled inputs are not submitted with a form anyway, bearing that in mind my advice would be to not use a textarea and just print it out.
I'm developing a Javascript virtual keyboard, and I would like it to appear everytime a user press enter on a text fields. But how can I know if a text (or any input) field is selected?
--clarification
I have to information or control over the page that will be loaded. I just want that, if a input field is selected and the user press enter, my virtual keyboard shows up.
--update
Does it makes any difference if what I'm trying to do is a firefox extension? (I think it shouldn't)
use jQuery and add the following
$(document).ready(function() {
//apply action to input elements by class
//$("#.input_class").keypress(function(e) {
//apply action to all input elements ( input, textarea, select and button )
$(':input').keypress(function(e) {
if(e.keyCode==13){
// Enter pressed... do anything here...
alert($(this).val());
} else {
//make shure you get the desired action for other keys pressed
xTriggered++;
}
//do not submit the form
return false;
});
});
bind it to the onfocus event. That event is triggered when the input element gets the focus. You could remove the keyboard again on the onblur event if you want to hide it again.
To get notified that a text field is selected, you could attach an event handler to onfocus of the fields you're interested in.
Example in jQuery (jQ chosen for brevity, the event works in plain JS):
$('input[type="text"]').focus(function(event){
// do something here
});
If you only care to capture the "enter" key, you don't need to worry about focus, just attach to the onkeypress event of the textfields (see #poelinca's answer).
Despite of what jquery apologetes say, there is no hassle to instrument all fields without resorting to large and slow external library:
for (var i = 0; i < document.forms.length; i++)
for (var j = 0; j < document.forms[i].elements.length; j++)
if (document.forms[i].elements[j].tagName.match(/^INPUT$/i))
if (document.forms[i].elements[j].type.match(/^TEXT$/i))
document.forms[i].elements[j].addEventListener('focus', function(){/* your stuff here */}, false);
My solution, for now, was use a specified key just to open the virtual keyboard when the user request.