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
Related
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.
In Chrome (55.x) if a user attempts to enter mismatched type into an input (in my case a number input) nothing outwardly appears to happen. To enhance usability I'd like to display a popup to let users know they're trying to enter invalid data rather than have them thinking the input is 'broken'.
This is easily achieved with pure JS in FF (which allows mismatched type to be entered, it just isn't valid):
input.addEventListener('input', function() {
if (!this.checkValidity()) {
this.value = '';
console.log('please enter a number!');
}
}
Because Chrome doesn't actually input anything, however, the validity check always passes as the input is empty; it doesn't appear to do anything with the incorrect input except ignore it.
Is there any way to override this behaviour, or otherwise achieve the intended effect?
Sure, you could do a listener for keyup and it will give you the key that was pressed.
<script>
var numInput = document.getElementById("num");
numInput.addEventListener("keyup", function(e) {
if (isNaN(String.fromCharCode(e.which))) {
alert("Must be a number");
}
});
</script>
How about setting a last input value and check like this?
let input = document.querySelector('input');
let lastInput = input.value;
input.addEventListener('input', (e) => {
if (e.target.value === lastInput) {
alert("Input must be a number");
}
lastInput = e.target.value;
});
I'm trying to create a note system. Whatever you type into the form gets put into a div. When the user hits Enter, they submit the note. However I want to make it so when they hit Shift + Enter it creates a line break a the point where they're typing (like skype). Here's my code:
$('#inputpnote').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode=='13' && event.shiftKey){
$("inputpnote").append("<br>");
}
else if(keycode == '13'){
var $pnote = document.getElementById("inputpnote").value;
if ($pnote.length > 0) {
$("#pnotes-list").append("<div class='pnote-list'><li>" + $pnote + "</li></div>");
$('#inputpnote').val('');
}
}
});
#inputpnote is the form where the user enters their note and #pnotes-list is the place where the notes are being appended to. Thank you in advance!
I think for this you'd have to set two global variables, 1 for shitftKeyPress and 1 for enterKeyPress and then you'd need a keydown and a keyup to set those values and then you check to see if they are both true, because your logic is saying, when a key is pressed, execute this code, if you press a key and then press another key, the only that will happen is the function will be called twice.
EDIT:
Example code of what it should look like:
var hasPressedShift = false;
var hasPressedEnter = false;
$('#inputpnote').keydown(function(event){
if(shiftkey) {
hasPressedShift = true;
}
if(enterKey) {
hasPressedEnter = true;
}
});
$('#inputpnote').keyup(function(event){
if(shiftkey) {
hasPressedShift = false;
}
if(enterKey) {
hasPressedEnter = false;
}
});
$('#inputpnote').keypress(function(event){
if(hasPressedShift && hasPressedEnter) {
// Do something
}
});
This was a quick mock up, but it's similar to how it should look
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.
On blur of field1, field2 is set to READONLY but the cursor on my page then defaults to field2 and the cursor is located at the END of the value and when the user clicks the backspace button the value can be erased. I would like the ability to have the cursor move to the next NON-READONLY or ENABLED field on the page. Is that do-able with jQuery?
Any help/direction would be appreciated.
Here is my code:
$(function() {
$("#ARTransferForm\\:fromAccountAmt").blur(function() {
var origAccountAmount = $("#ARTransferForm\\:fromAccountAmt").val();
var fromAccountAmount = $("#ARTransferForm\\:fromAccountAmt").val();
// Call validation "r2" function
var modFromAccountAmount = r2(fromAccountAmount);
//alert("modFromAccountAmount = " + modFromAccountAmount);
fromAccountAmount = $("#ARTransferForm\\:fromAccountAmt").val(modFromAccountAmount).val();
//alert ("modified fromAccountAmount = " + fromAccountAmount);
if (modFromAccountAmount != "N.aN") {
var firstChar = fromAccountAmount.charAt(0);
var fromAcctAmtLen = $("#ARTransferForm\\:fromAccountAmt").val().length;
if (firstChar == "-") {
var revFromAcctAmt = fromAccountAmount.substring(1, fromAcctAmtLen);
$("#ARTransferForm\\:toAccountAmt").val(revFromAcctAmt);
$("#ARTransferForm\\:toAccountAmt").attr("readonly", "readonly");
} else {
$("#ARTransferForm\\:toAccountAmt").val("-"+fromAccountAmount);
$("#ARTransferForm\\:toAccountAmt").attr("readonly", "readonly");
}
} else {
$("#ARTransferForm\\:fromAccountAmt").val(origAccountAmount);
$("#ARTransferForm\\:fromAccountAmt").select();
alert("Invalid From Amount Format. Use ##.## (NO commas or $ sign)");
}
});
});
Have you tried modifying tabindexes onblur, before RETURN TRUE, to control where the cursor goes? It's kind of a hack, but there you go.
Also, you could use a delegated event (perhaps on the form) to intercept and return false on any keypress events that would modify the value of any readonly input. Something like:
$('#ARTransferForm *[readonly]').live("keypress", function(event) {
// compare keycode to blacklist: backspace, perhaps delete too?
if(bKeyIsBlacklisted) {
event.preventDefault();
return false;
}
});
(Note: that is pretty pseudocodeonous. You'll want to double-check the syntax for sizzle's attribute selectors, as well as jquery's event delegation signature. And be real careful about how wide you cast your "no keys" net: try to avoid disallowing Copy and other operations performed with keyboard shortcuts. You will need to check for a modifier key to distinguish between the user trying to type "c" and Ctrl+C.
Which browser(s) are you testing this in?