I have a div that is used as user input:
<div id="chat-message-input" contenteditable="plaintext-only">
When the user hits the enter key (and is not holding the shift key), the text from the user is submitted.
<script>
document.querySelector('#chat-message-input').onkeyup = function(e) {
// User hits enter key and is not holding shift
if (e.keyCode === 13 && event.shiftKey != 1) {
//Click submit button
document.querySelector('#chat-message-submit').click();
// Clear input field
document.getElementById('chat-message-input').innerHTML='';
};
</script>
Problem: There is a brief moment where the div creates a new line because the enter key was pressed, before the content in the div is cleared.
I only want a new line to be created under these circumstances:
The user's input text reaches the end of the line
The user holds shift and presses enter
Does anyone know how I can prevent a new line from being created given the above requirements?
As suggested by A Haworth, I also intercepted onkeydown (in addition to onkeyup) and prevented the default. This seemed to work well.
document.querySelector('#chat-message-input').onkeydown = function(e) {
// User hits enter key and is not holding shift
if (e.keyCode === 13 && event.shiftKey != 1) {
e.preventDefault()
}
};
This made the input field really solid, which is necessary for my real-time chat app. Thanks!
Related
I have an input that I want to allow the user to save the text either by pressing enter or by clicking anywhere else on the screen. Getting the code to process when the user presses enter is no problem. But I want to process the same code by triggering the jquery keyup event when the user clicks away just as if they pressed Enter on the input box instead. The theory isn't giving me an issue, but the keycode is either not being passed correctly or interpreted correctly when clicking away. When I alert the interpreted keycode, I get a "1" which doesn't equate to any keypress. What am I doing wrong?
$(document).on("click","body",function(e){
if(e.target.id!="openInput"){ //Indicates user has clicked out away from the input
if($(".attributeEdit")[0]){ //This is a unique class added
var i = $.Event('keyup');
i.which = 13;
$(".attributeEdit").trigger(i); //Have also tried triggering off #openInput, too with no success
}
}
});
$(document).on("keyup",".attributeEdit",function(){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
do stuff;
}
else{
alert("keycode: " + keycode); //This results in a "1" every time user clicks away
}
});
I found a solution to the end objective using Hiren Raiyani's suggestion of a function call. It doesn't actually answer the original question, but since it solved my problem, I'm hoping this will be useful to others that search. I created a function to "do stuff" and that way, I can call that function both after the Enter key is pressed and after the mouse is clicked.
function doStuff(x,y){
do stuff
}
$(document).on("click","body",function(e){
if(e.target.id!="openInput"){ //Indicates user has clicked out away from the input
if($(".attributeEdit")[0]){ //This is a unique class added
doStuff(x,y);
}
}
});
$(document).on("keyup",".attributeEdit",function(){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
doStuff(x,y);
}
});
I have some input fields and a HTML table on my UI to input some data, my HTML table have some input field inside my HTML table and doing some calculations also all that are working fine
What I am doing is:
I have some input fields inside my table so when I press on tab I am focusing one next input field
now there is last input field which is Disc% here after pressing tab I am creating new row (on focus out) , but that's not a good user interface because whenever I am clicking outside the Disc% field it is crating new row which is not correct
What I am trying to do is:
After disc% when I press enter I want to create a new row so that it will be good for user
I have tried doing this but it is not working correctly as when I reach Disc% and press enter it does nothing and when I focus out and again come back to Disc% and press enter then it creates new row but on one press it shows three times, I don't know what's wrong
Please check my Fiddle, as I have so many calculation that's why code is bit lengthier but I have commented the line where the issue is
when target matches disc% I am doing like below
if (e.target.matches('[name=discPercentagetd]')) {
$(document).keypress(function(event) { // here I am trying to create new row when enter is clicked
var keycode = event.keyCode || event.which;
if (keycode == '13') {
alert("presed")
calcDiscount(e.target.parentElement.parentElement)
if ($(row).parent().find('tr').length - $(row).index() === 1) {
rowappend(e.target.parentElement.parentElement.parentElement)
}
}
});
}
I am doing it like $(document).on('focusout', (e) => { because ItemName field in my table is autoComplete and when creating new row I want it to behave like the above.
What you need to do is move the keypress function out of the focusout function that you have. JSFiddle
Because you are checking to see if they have pressed enter inside the focus out function, it is not behaving as you would expect.
After moving it outside of that function it behaves as expected, the alert is only triggered once, and the row is created even when focus is still inside the input element.
$(document).on('focusout', (e) => {
const row = e.target.parentElement.parentElement
if (e.target.matches("[name=itemNametd]")) { // whene focus is out from itemNametd
getValues(e.target.parentElement.parentElement)
}
if (e.target.matches('[name=unitQtytd]')) { //when focus is out from unitQty
calc(e.target.parentElement.parentElement)
}
});
// Move this outside of the above focusout function,
// you will also need to rename all of the e elements to event,
// or the other way around. Also include line where you declare the row variable
$(document).keypress(function(event) {
const row = event.target.parentElement.parentElement
var keycode = event.keyCode || event.which;
if (keycode == '13') {
alert("presed")
calcDiscount(event.target.parentElement.parentElement)
if ($(row).parent().find('tr').length - $(row).index() === 1) {
rowappend(event.target.parentElement.parentElement.parentElement)
}
}
});
Not question related (since you were talking about user experience):
One thing to keep in mind is "How will the user know to press enter to create a new row". It may be good to also include a button to add a row, and maybe a little element that reveals more information on hover that explains they can use enter to make a new row.
Also, consider styling the total row to look like it is apart of the table, that way the user would know what the numbers match up to.
Can you simulate the keystroke shift+ enter in javascript? Basically when a user presses enter on the keyboard while in a div where contenteditable=true I want it to be as if they held down shift and enter at the same time. something like the following:
if(e.which == 13)
simulate shift and enter key being pressed simultaneously
I'm doing this because I want the curser to go to a new line as soon as you press enter and I read this can be achieved by pressing shift+enter. I have the following code now:
$('element[contenteditable="true"]').keypress(function(event) {
if (event.which == 13){
document.execCommand('innerHTML', false, 'p');
$('element').append('<br>');
return false;
}
});
This code replaces auto generated p tags in IE with br tags but does not go to a new line when the enter key is pressed. the cursor only moves to a new line when I press another key after the enter key has been pressed. Any thoughts?
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'm using the below JavaScript function to prevent backspace from going back.
function preventBackspace(e) {
var evt = e || window.event;
if (evt) {
var keyCode = evt.charCode || evt.keyCode;
if (keyCode === 8) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
}
}
I have added onkeydown="preventBackspace();" to all the text boxes.
I have two radio buttons and two textboxes which when checked make the other textbox readonly. When hitting the backspace key it is not going to back page, but I am not able to delete from the editable text box. Please suggest. Thanks!
When the user is currently focused on a textbox, the backspace key does not cause the browser to go back. The backspace in a textbox is used to delete a character - and since you've added preventDefault(), you're stopping that behavior from happening.
If your goal is to prevent the user from accidentally leaving the form before they are finished, you can use window.onbeforeunload to display a warning message that allows the user to cancel navigation:
window.onbeforeunload = function() {
return "Are you sure you want to leave this page? Your current entries" +
" will be lost.";
};