preventDefault() disables text input as well - javascript

edit: I want to use the enter key to clear the text box after I have already typed some text. Sorry for the confusion I have caused
edit 2 The missing event parameter was the key of all this. Sorry, I am a failure as a programmer.
I want to disable the new line/break when I press enter. However, version 1 doesn't work as I won't be able to enter any text at all.
Version 2 works and I am still able to clear the field while continue entering new texts.
From how I interpret this, whether I press the shift key + enter together or not, it should still allow me to type. Why is there such a difference? How does the default option of shift key relate to enabling/disabling input on the textbox? What I would like to do, is to just disable the new line/break when pressing the enter button but I found that it disabled the input part as well, which from my understanding, it shouldn't?
// html
<textarea type="text" id="box">Some text</textarea>
// javascript
document.getElementById('box').addEventListener('keypress', (e)=>{
//version 1
if(e.keyCode == 13){ //why does this version also disable any text input?
e.preventDefault();
document.getElementById('box').value = '';
}
//version 2
if(e.keyCode == 13 && e.shiftKey){
e.preventDefault();
document.getElementById('box').value = '';
}
});

Your code is throwing an error because it doesn't know what the variable e is referring to. You should see that error if you watch the error console. To fix it, you should pass that in to the function. This clears the textbook when you press enter. Is that what you want? I left the line in but commented it out.
document.getElementById('box').addEventListener('keypress', (e)=>{
//version 1
if(e.keyCode == 13){ //why does this version also disable any text input?
e.preventDefault();
document.getElementById('box').value = '';
}
});
<textarea type="text" id="box">Some text</textarea>

Related

How to set listeners to "backspace press" event in Javascript or Jquery?

I have a button that is enabled or disabled if, respectively, there is or is not text inside an input, as shown in the code snippet below:
var input = document.getElementById('myInput');
var btn = document.getElementById('myButton');
$(input).on('keyup', function(){
if((input.value != null) && (input.value != ''))
$(btn).removeClass('btnDisabled');
else
$(btn).addClass('btnDisabled');
});
Using keyup event it is working good in my aplication on an smarthphone with Android 6.0.1. But for some reason, on an tablet with Android 4.4.2 if backspace key are pressed till the begin of input, erasing all the text value, the button is still enabled.
I researched this problem but I'm still not sure if the WebView version interferes with this. I think so.
I used other code snippets to see if the event is triggered by the "backspace" button, as shown below:
$(input).on('keydown', function(event){ //I tried keyup, keydown and keypress
var key = event.keyCode || event.charCode;
console.log("keydown " + key, "length " + input.value.length);
//if(key == 8 && input.value.length == 1) $(btn).addClass('btnDisabled');
});
With this test I saw that the backspace does not trigger the event and the variable key is always equal to 0.
I need to disable the button when input is empty. Where am I going wrong?
Right now, I thank those who help! :D
There is another event that you can use: input
https://developer.mozilla.org/en-US/docs/Web/Events/input
The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.
In this case, change
$(input).on('keydown',
to
$(input).on('input',
See also: https://caniuse.com/#search=input

How to clear a textarea value in jQuery?

I'm trying to validate keycode entry by adding an alert when a user types a key that isn't expected, and then clearing the text area. The alert functions correctly but the text area isn't clearing.
I've checked the documentation here, but I can't see an area with my .val() line. I've also tried this: $("#noteNumberInput").attr('value', "");
Scenario: I type 1-9 in the text box and get no alert (works fine), if I type a letter a-z for example, the alert pops up but the letter remains in the text box.
EDIT:
Something I've noticed is that it does clear the textarea after the first key. If I type the letter 'a' and then 'b', the 'a' is removed and replaced with a 'b'.
HTML:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
JS:
var noteNumberInput = document.getElementById("noteNumberInput");
//VALIDATE NOTE NUMBER TEXTAREA
function validate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if (keycode === 8 || (keycode >= 48 && keycode <= 57)) {
return true;
}
if (keycode < 48 || keycode > 57) {
alert("Please only enter the note number e.g. 1, 2..14 etc.");
$("#noteNumberInput").val("");
return false;
}
}
noteNumberInput.addEventListener("keydown", validate);
When you do $("#noteNumberInput").val('');, it removes all the content of the textarea, so if that's not what is happening, the problem is probably somewhere else.
Change noteNumberInput.addEventListener("keydown", validate); to use keyup
Using $("#noteNumberInput").val() will clear the textarea
EDIT
The problem is the keydown handler. In this case the function will be triggered followed by the display of alert & then the text area will be populated. But on using keyup the function will be triggered on release of the key.So by that time the textarea will be populated with value.
Change the keydown to keyup
var noteNumberInput = document.getElementById("noteNumberInput");
noteNumberInput.addEventListener("keyup", validate);
DEMO
Your only asking for the validate() function to actually execute when you've pressed the next key.
I think that´s not the best idea to trigger key events, because cut and paste and drag and drop can also change the input element.
try this:
Element.addEventListener('input', function(){
this.value=this.value.replace(/[^0-9,.]/g, '');
});
this must be adapted to textarea...

keyup event not triggered for escape key

I have a text input field referred to as $nameEditor. I want to show this text field when a button is pressed, and hide it on blur or when the escape key is pressed.
Hiding the field on blur works every time.
Hiding the field when pressing the escape key works only the first time. Example sequence of events.
Press the button that shows the text input field.
Press escape - text input field hides
Press the button that shows the text input field again.
Press escape - the keyup event is not triggered
Press any other key and the keyup event is triggered
Press escape - the text input field hides
Relevant markup:
<button id="renameButton" title="Rename" data-icon="ui-icon-pencil">Rename</button>
<span id="assemblyNameView">Assembly Name</span>
<input id="assemblyNameEditor" style="display:none" class="ui-corner-all widget">
Relevant script:
var $renameButton = $("#renameButton");
var $nameViewer = $('#assemblyNameView');
var $nameEditor = $('#assemblyNameEditor');
function cancelEdit() {
$nameEditor.hide();
$nameViewer.show();
}
function initEdit() {
$nameViewer.hide();
$nameEditor.val($nameViewer.text()).show().select();
}
function commitEdit(newName) {
// TODO: Update the structure being edited.
$nameEditor.hide();
$nameViewer.text(newName);
$nameViewer.show();
}
$renameButton.click(initEdit);
$nameEditor.blur(cancelEdit);
$nameEditor.keyup(function(e) {
console.log(e);
if (e.keyCode === 13) {
var newName = val();
if (newName === '') {
alert("No name specified.");
$nameEditor.val($nameViewer.text()).select();
e.preventDefault();
return false;
}
commitEdit(newName);
}
else if (e.keyCode === 27) {
cancelEdit();
}
});
Why is the escape key not triggering the keyup event after the input box has been hidden then re-shown?
It's hard to explain what's wrong here. There is a strange effect when both the button and the textbox receive focus? It's impossible in a standard UI interface. In fact when you type keys other than ESC, Enter, Space and maybe more ... the typed characters are shown OK in the textbox and only the textbox receives focus after that. However if you type ESC, Enter, Space... the keystrokes seem to affect on the button and I can even see there is some color effect on the button showing that it's currently focused. This looks like a bug indeed.
However to solve this, I tried using focus() explicitly appended after .select() and it works OK.
function initEdit() {
$nameViewer.hide();
$nameEditor.val($nameViewer.text()).show().select().focus();
}
Demo.

Capturing the Enter key

I am trying to capture the Enter key as follows,
$("#txt1").keypress(function(event){
if(event.which==13) //Also tried using event.keycode
$("#add").load("newjsp.jsp?q="+this.value)
})
But everytime I press enter, The text gets erased and does not show in the form(#add) it should. How can I do this?
Also I encountered a problem in the following code,
$("#txt1").keyup(function(event){
$("#add").load("newjsp.jsp?q="+this.value)
})
<form>
Comment: <input type="text" id="txt1"></input>
</form>
<p><p></p></p>
<form id="add">
</form>
When I run this code, the text in the textbox gets added to my form (#add) but as I press the spacebar key, the text is erased (from the #add form and not from the textbox) and then no more text is added. I have tried using keydown and keypress but same problem remains. I cannot understand where the problem lies since this.value gives me the complete value in the textbox! Including the spaces.
Your first example is the correct one. Except you need to prevent event bubbling after you press 'enter'. Pressing enter by default submits the form. FinalFrag is correct about the spaces
$('#txt1').keypress(function(e){
if (e.which===13) {
e.preventDefault();
e.stopImmediatePropagation();
$("#add").load("newjsp.jsp", {q: $(this).val()} );
}
});
*Editied to reflect Tomalak's comment.
this.value will indeed add the pressed key to the load request. However, your browser might trim the spaces off the requested url turning "q=hello " into "q=hello"
You should escape the value before you use it in the request.
Take a look at the javascript escape() function here: http://www.w3schools.com/jsref/jsref_escape.asp
For the second problem you should use encodeUricomponent() to encode the values so that you can use them in a url:
$("#txt1").keyup(function(event){
$("#add").load("newjsp.jsp?q="+encodeURIComponent(this.value));
})
For the first problem you should prevent the default action and stop the propagation:
$('#txt1').keypress(function(e){
e.preventDefault();
e.stopImmediatePropagation()
if (e.which===13) {
$("#add").load("newjsp.jsp?q=" + $(this).val());
}
});

how to remove the default focus on submit button in HTML form?

I have a HTML form on my page. When i am putting some value in one of the text fields in form and press 'Enter key' the form gets submitted instantly. I think this is happening due to default focus is on submit button. But i try to remove that focus using blur() function, it is not working. I am using Chrome.
Is there any way to avoid this scenario?
All suggestions are welcome. thanks in advance.
The Submit button is not actually focused; Enter in a text field is supposed to submit the form.
You could register a handler for the submit event, and then only allow it if the Submit button was actually focused at the time submit was requested.
However, you'll be deliberately breaking the way that HTML forms work. Not everyone wants to submit the form using the One True Way of actually clicking the Submit button (also, you'll be breaking accessibility and may introduce browser-specific bugs).
No. The focus is still on the text field. Pressing enter there is supposed to submit the form (and bypasses the submit button entirely).
You can suppress the behavior using JavaScript, but since it is normal behavior for the browser, I wouldn't recommend doing so.
try this solution: replace the 'input' with 'button' and add attribute
type equals 'button' and handle the onclick event with submit javascript function
<form name='testForm'>
<input type='text' value="myName" />
<button type='button' onclick='testForm.submit()'/>
</form>
i think it works also with tag input adding the same attribute
Enjoy
Mirco
blur() is the way to go. It works like this:
<button onclick="this.blur();">some button</button>
Note that you should not use JavaScript and DOM-events using Attributes. This is just for demonstration purposes. Try to be unobstrusive.
Maybe it will help you out, the form is "supposed" to be sent with enter in the text box (HTML by design), it is no a matter of focus.
If you want to avoid it, check this out.
This is the proposed script:
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
Good luck, tell me if you need any clarification!
EDIT: I do agree with Piskvor answer, it may bring some bugs
this has nothing to do with the focus, its just the default behavior of you browser. to avoid this, you could try to cath the enter-keypress like this (Source - but there are a lot of other solutions (most working the same way, just using other events like the firms onsubmit instead of the documents onkeypress)):
function catchEnter(e){
// Catch IE’s window.event if the
// ‘e’ variable is null.
// FireFox and others populate the
// e variable automagically.
if (!e) e = window.event;
// Catch the keyCode into a variable.
// IE = keyCode, DOM = which.
var code = (e.keyCode) ? e.keyCode : e.which;
// If code = 13 (enter) or 3 (return),
// cancel it out; else keep going and
// process the key.
if (code == 13 || code == 3)
return false;
else
return true;
}
// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };
Change:
<input type="text" ... >
To:
<textarea ... ></textarea>
You may need to mess around with the attributes a bit, I've left them signified as ....
try to add on the keypress event of your button this javascript function :
function ButtonKeyPress()
{
var code = (window.event.which) ? window.event.which : window.event.keyCode;
if ( code == 13 )
{
event.returnValue = false;
return false;
}
return true;
}
So, you have a form. In this form, you have a text input, and a submit button.
You get in the text input, you type some text, than you press "Enter". This submits the form.
You would like to break this normal behavior.
I think this is not a good idea : The convention says that when your in a text input and press "Enter", it submits the form. If you change this behavior, users could be (I don't find the right word, let's say ~) surprised.
Anyway, if you still want to do this, you should listen for the keypress event on the text input, and than prevent default behaviour shoud do the work.
let's say you use jQuery :
$(input[type=text]).bind('keypress', function(evt) {
if(evt.keyCode == 13) {
evt.preventDefault();
}
});
This should do it. I didn't test it, maybe I made mistakes, but you got the idea, no ?
And maybe keyup is better than keypress... I don't know very well this, not enough practice on key bindings
The easiest way is to set css style like this:
&:focus {
outline: 0 none;
}

Categories

Resources