How make an action run only when the field becomes unselected? - javascript

Right now the value of an input text field changes upon the successful match in my code. It looks like this:
if(jsonResponse.id != null) {
document.getElementById('product_id').value = jsonResponse.id;
}
The problem is that if, i.e., I have a product with id=200 and a product with id=2003, then when a user wants to search for 2003, the moment the typed value is 200 - the input field text will change with the corresponding answer for 200, instead of 2003. This is not convenient.
So my goal is to add some additional check (or something like that), that will allow document.getElementById('product_id').value = jsonResponse.id; only after the cursor is not anymore in the input text field (when the field is not selected anymore).

To run a function when a text field loses focus, you can use jQuery's blur event handler:
$('.mytextfield').blur(function(){
var value = $(this).val();
// use value
});
jsbin example

You wait for user to press enter, as soon as user press the enter then process the text.
document.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
if (charCode==13) { //ENTER PRESSED
/* your code */
}
};

You can do also like this:
<input type="text" name="name" value="" onblur="yourFunction();"/>
Or by Jquery.

Related

Delete input.value when key is pressed

I have an HTML input on my page. The user is able to type text into it. When he types in a command, that I specified, and presses enter, the page outputs information into the input.value. If the user types in something random and confirms his input, the page just outputs: "Unknown command.", again into to input.value.
I made a striped down Fiddle here: JSFiddle
The Problem:
When I type in: test and press enter, the value changes to: This is kind of working…. I know want to type in something new, but I first have to highlight, or delete the This is kind of working… text, which is really not intuitive.
Is there a way to change my script, so that when I'm in the input and I press any button, that is not button Nr.13 aka "Enter", the page just makes the value of the input, the button, that has been pressed? So that the user can just start typing in something new, after receiveing a value and doesn't have to delete the value that I put in there.
I tried adding an additional .onkeypress function, but it destroyed everything, so I didn't do it the right way.
This is my current JS:
var clInput = 0;
document.querySelector("#inputMain").onkeypress = function(e){
if (!e) e = window.event;
if (e.keyCode == '13'){
clInput = document.querySelector("#inputMain").value;
switch (clInput) {
case "test":
test();
break;
default:
document.querySelector("#inputMain").value = "Unknown command.";
}
return false;
}
}
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
}
HTML:
<input id="inputMain" name="inputMain" autofocus>
I have updated your code a bit to do exactly what you want. What was essentially done was to:
Keep track of when you pressed 13 - Enter.
Then if 13 - Enter was previously pressed, just make sure to clear the input.
You can check the demo here: https://jsfiddle.net/nh6c7ugf/
var clInput = 0; // Note: Ignore Upper- / Lower-Case in input?
var isEntered = false;
document.querySelector("#inputMain").onkeypress = function(e){
if (!e) e = window.event;
// clear the value
if (isEntered) {
isEntered = false;
document.querySelector("#inputMain").value = '';
}
if (e.keyCode == '13'){
clInput = document.querySelector("#inputMain").value;
isEntered = true;
switch (clInput) {
case "test":
test();
break;
default:
document.querySelector("#inputMain").value = "Unknown command.";
}
return false;
}
}
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
}
Sorry if I don't understand what you are trying to say
but if you want that the user can just start typing in something new, after receiving value and doesn't have to delete the value that you put in there.
you can do
function test() {
document.querySelector("#inputMain").value = "This is kind of working…";
document.querySelector("#inputMain").selct();
}
This will select all the text of the input field and when the user will type something the previous value of the field will be deleted

Validate contenteditable on enter and not on clicking

I'm using contenteditable so as people can edit a text.
So when you edit the text thas has contenteditable = true, if you click somewhere else in the page, it will "validate" your text and replace the older.
That's not the comportment I'd like it to have because the user has no way to get back to the older text except by refreshing the page.
To me, it should validate the text only if you press the Enter Key and not if you click somewhere else. If you click somewhere else then it should get back to the older text.
Any idea how to make it ?
Thanks ! :)
When the user clicks the box, you can store its value into a var, and when they click away, reset the box to that var.
If the Enter key doesn't already validate, here's some pseudocode as to what you could do:
var oldvalue = "";
function OnClickBox() {
oldvalue = (yourelement).value;
}
function OnClickAway() {
(yourelement).value = oldvalue;
}
function Validate() {
(yourelement).value = yourvalidationfunction(yourelement.value);
}
document.onkeydown = function (e) {
key = e.which || e.KeyCode;
if (e.keyCode === 16) { //enter key
Validate();
}
}
Then you assign the box's onclick to OnClickBox(), and unselecting the box to OnClickAway().
And for future posts, please include some code as to what you have tried already, and for better context as to your question.

Need to evoke an enter keypress on textarea?

I have this obfuscated webpage that contains a text-area,
When a user manually inserts text and presses Enter key while editing the text area an event that changes the DOM launches.
I need to pragmatically launch that event,
I know how to get to the text-area itself (using getElementsByName)
and I'm basically inserting text via textArea.value = ''
How do I get that event to launch?
Could you call a function when enter is pressed, and then also just call that function when you want to simulate enter being pressed?
element.addEventListener("keypress", function(event){
if (event.keyCode == 13) {
// Enter has just been pressed.
enterPressed();
}
});
function enterPressed(){
// Do whatever you do when enter is pressed.
}
// Somewhere else off in your code when you want to "trigger" the enter press event:
enterPressed();
is this what you want
document.getElementById("id_of_your_textarea").addEventListener("keydown", function(e) {
if (!e) { var e = window.event; }
e.preventDefault(); // sometimes useful
// Enter is pressed
if (e.keyCode == 13) { document.getElementById("id_of_your_textarea").value = '' }
}, false);
EDIT: based on your comment, you can use the trigger
if you can use jQuery.
$('#textArea').trigger('keydown');

Stop page refreshing when 'enter' is pressed in input text element

Is there a way to stop a webpage from refreshing completely when the enter button is pressed in a input text element?
I'm looking to create a search field that I can get the text from when enter is pressed to filter objects and only display the ones that contain text from the search field.
I've tried the following to try and catch the enter button but it does not work.
function setupSearchField() {
document.getElementById("searchField").onKeyDown = function(event) {
var holder;
if (window.event) {
holder = window.event.keyCode;
} else {
holder = event.which;
}
keyPressed(holder);
}
}
function keyPressed(key) {
if (key == 13) {
event.cancelBubble = true;
return false;
}
}
If the input element is inside a form, and that form is not actually being submitted to the server, remove the form.
The reason your code doesn't work is becaue the onkeydown event should be in lowercase, and you aren't actually returning something in it (try return keyPressed(holder); - or just move the keyPressed function's code into setupSearchField, since it seems kind of pointless to me to have it as a separate function).
This happens when there is only one text input, regardless of whether your button (if any) has type="submit" or not. It's documented here.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2
So, as suggested by other people earlier, you then have to simply stop this default behavior.
Is your search field inside a element ? Then hitting 'enter' fires a submit event to the form element.
In this case you could process your filtering by defining onsubmit on the form element.
<form id="searchForm">
<input type="text" name="search" />
</form>
<script>
document.getElementById('searchForm').onsubmit = function() {
var searchValue = this.search.value;
// process
return false;
}
</script>
Something like this maybe.
Just add the following javascript code to your Visualforce page:
<script type='text/javascript'>
function stopRKey(evt)
{
var evt=(evt) ? evt : ((event) ? event : null);
var node=(evt.target)?evt.target:((evt.srcElement)?evt.srcElement:null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>

Disabling enter key for form

I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The code is in my head section and seems to be correct from other sources.
disableEnterKey: function disableEnterKey(e){
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
},
if you use jQuery, its quite simple. Here you go
$(document).keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
}
});
Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. Here it is:
<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>
This code works great because, it only disables the "Enter" keypress action for input type='text'. This means visitors are still able to use "Enter" key in textarea and across all of the web page. They will still be able to submit the form by going to the "Submit" button with "Tab" keys and hitting "Enter".
Here are some highlights:
It is in pure javascript (no library required).
Not only it checks the key pressed, it confirms if the "Enter" is hit on the input type='text' form element. (Which causes the most faulty form submits
Together with the above, user can use "Enter" key anywhere else.
It is short, clean, fast and straight to the point.
If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...
In your form tag just paste this:
onkeypress="return event.keyCode != 13;"
Example
<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">
This can be useful if you want to do search when typing and ignoring ENTER.
/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)
try this ^^
$(document).ready(function() {
$("form").bind("keypress", function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
Hope this helps
For a non-javascript solution, try putting a <button disabled>Submit</button> into your form, positioned before any other submit buttons/inputs. I suggest immediately after the <form> opening tag (and using CSS to hide it, accesskey='-1' to get it out of the tab sequence, etc)
AFAICT, user agents look for the first submit button when ENTER is hit in an input, and if that button is disabled will then stop looking for another.
A form element's default button is the first submit button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)
https://www.w3.org/TR/html5/forms.html#implicit-submission
However, I do know that Safari 10 MacOS misbehaves here, submitting the form even if the default button is disabled.
So, if you can assume javascript, insert <button onclick="return false;">Submit</button> instead. On ENTER, the onclick handler will get called, and since it returns false the submission process stops. Browsers I've tested this with won't even do the browser-validation thing (focussing the first invalid form control, displaying an error message, etc).
The solution is so simple:
Replace type "Submit" with button
<input type="button" value="Submit" onclick="this.form.submit()" />
this is in pure javascript
document.addEventListener('keypress', function (e) {
if (e.keyCode === 13 || e.which === 13) {
e.preventDefault();
return false;
}
});
Here's a simple way to accomplish this with jQuery that limits it to the appropriate input elements:
//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', ':input:not(textarea):not([type=submit])', function (e) {
if (e.which == 13) e.preventDefault();
});
Thanks to this answer: https://stackoverflow.com/a/1977126/560114.
Just add following code in <Head> Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.
<script type="text/javascript">
function stopEnterKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
document.onkeypress = stopEnterKey;
</script>
You can try something like this, if you use jQuery.
$("form").bind("keydown", function(e) {
if (e.keyCode === 13) return false;
});
That will wait for a keydown, if it is Enter, it will do nothing.
I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form.
You need to attach disableAllInputs to onload of the page or via jquery ready()
/*
* Prevents default behavior of pushing enter button. This method doesn't work,
* if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
* the input. So method should be attached directly to the input 'onkeydown'
*/
function preventEnterKey(e) {
// W3C (Chrome|FF) || IE
e = e || window.event;
var keycode = e.which || e.keyCode;
if (keycode == 13) { // Key code of enter button
// Cancel default action
if (e.preventDefault) { // W3C
e.preventDefault();
} else { // IE
e.returnValue = false;
}
// Cancel visible action
if (e.stopPropagation) { // W3C
e.stopPropagation();
} else { // IE
e.cancelBubble = true;
}
// We don't need anything else
return false;
}
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
try {
var els = document.getElementsByTagName('input');
if (els) {
for ( var i = 0; i < els.length; i++) {
els[i].onkeydown = preventEnterKey;
}
}
} catch (e) {
}
}
I think setting a class to a form is much better. so I coded that:
HTML
<form class="submit-disabled">
JS
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('submit', function (e) {
e.preventDefault()
});
/**
* </End>
* Submit Disabled Form
*/
And also if you want to disable submitting only when Enter Key press:
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('keypress', function (e) {
if (e.keyCode === 13) {
e.preventDefault()
}
});
/**
* </End>
* Submit Disabled Form
*/
in HTML file:
#keypress="disableEnterKey($event)"
in js file:
disableEnterKey(e) {
if (e.keyCode === 13) {
e.preventDefault();
}
}
First you need to disable the form on submit, but re-enable it when clicked on the button. which or keycode is not used in this case, avoiding some problems with compatibility.
let formExample = document.getElementbyId("formExample");//selects the form
formExample.addEventListener("submit", function(event){ //must be used "submit"
event.preventDefault();// prevents "form" from being sent
})
To reactivate and submit the form by clicking the button:
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateButton); //calls the function "activateButton()" on click
function activateButton(){
formExample.submit(); //submits the form
}
a variation of this would be
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateBtnConditions); //calls the function "activateBtnConditions()" on click
function activateBtnConditions(){
if(condition){
instruction
}
else{
formExample.submit()
}
}
Here is a modern, simple and reactive solution which works in:
React, Solidjs, JSX etc.
is written in Typescript
supports server-side rendering (SSR)
all modern browsers
does NOT require jQuery
blocks ALL Enter keys outside of <textarea> where you want to allow Enter
// avoids accidential form submission, add via event listener
function blockEnterKey(e: KeyboardEvent) {
if (e.key == "Enter" && !(e.target instanceof HTMLTextAreaElement)) {
e.preventDefault()
}
}
// add the event listener before the rendering return in React, etc.
if (typeof window !== undefined) {
window.addEventListener("keydown", blockEnterKey)
// the following line is for Solidjs. React has similar cleanup functionality
// onCleanup(() => document.body.removeEventListener("keydown", blockEnterKey))
}
return(
<form>
...
</form>
)
The better way I found here:
Dream.In.Code
action="javascript: void(0)" or action="return false;" (doesn't work on me)

Categories