Change variable from input field - javascript

I've been learning some jQuery and using w3schools. My intention is to allow the user to bind any key on their keyboard to the currently hardcoded key. I tried creating a variable and having that changed based on the input of the text field to change the keycode but haven't had any luck (Just like how you see in some games when they allow you to map a key to another). I was researching on w3schools and I believe I could use switch case, but I believe that would be too long and not tidy?
Here is what I have so far. (Alert doesn't seem to work here, going to the actual JSFiddle via the hyperlink works though)
$('input').bind("binding", function(e) {
alert("Backspace"); //Pop up to see
});
$('input').keyup(function(e) {
if (e.keyCode == 8) { // 8 = backspace
$(this).trigger("binding"); //will allow the message to be displayed
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try it here <input type="text"> Change the input <input class type="text">
Any suggestions are grateful. Thank you

You can try this for binding one key to backspace. It takes input from the first input element and the key pressed is then bounded to the backspace and only that key will function as a backspace key
$('#try').bind("binding", function(e) {
alert("Backspace"); //Pop up to see
});
var a;
$('#change').keyup(function(e) {
a = e.keyCode;
$(this).prop('disabled', true);
});
$('#try').keyup(function(e) {
if (e.keyCode == a) {
$(this).trigger("binding"); //will allow the message to be displayed
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Press the key you want to bind to backspace <input type="text" id="change"><br> Change the input <input id="try" type="text">

By default the binded key will be Backspace. You can change the key by typing something in the first input. It will take only one character.
Then when that key is input in the second input field the message will be triggered.
Explanation:
The keycode of the key entered in the first input is saved in the key_code variable and used later on in the other key_up event to check whether it matches
var key_code = 8
$('#changekey').keyup("input", function(e) {
key_code = e.keyCode;
});
$('input').on("binding", function(e) {
alert("Backspace"); //Pop up to see
});
$('#text').keyup(function(e) {
if (e.keyCode == key_code) //8 = backspace
{
$(this).trigger("binding"); //will allow the message to be displayed
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Try it here <input type="text" id="changekey" maxlength = 1 > Change the input <input class type="text" id="text">

Related

How to stop backspace or delete key to delete text before the cursor

I am trying to stop cursor from deleting the word before it if the word before is "Hi Harry" in input type text . I am trying to restrict cursor from deleting text, if user started deleting text and
text before it matches "Hi Harry" before it then stop deleting this text. The user also should not override the "Hi Harry text" by selecting and typing another character. "Hi Harry" must not be deleted or replaced by user by any action.
Any solution that fulfills the requirement may help.
.html
<input id="target" type="text" value="Hi Harry">
js
$( "#target").keydown(function(e) {
if (e.which == 8 && e.target.value === "Hi Harry") {
// backspace or delete key
return false;
// here I want to stop cursor from deleting if user started deleting text and
//text before it if matches "Hi Harry" then stop deleting this text.
}
});
As you may know by now, to prevent the user from deleting with backspace or delete, you can preventDefault on the events for e.which == 8 or e.which == 46.
What if the user selects the text or clicks in between "Hi Harry?" You need to also handle some text selection events. See the snippet below[1]:
// monitor key down function
var initialValue = $("#target").val();
$("#target").keydown(function(e) {
if (e.target.selectionStart < initialValue.length) {
//prevent user from typing stuff in between "Hi Harry"
e.preventDefault();
return;
}
if ((e.which == 8 || e.which == 46) && e.target.value === initialValue) {
// backspace or delete key
// backspace is 8, delete is
e.preventDefault();
}
});
// monitor text selection and force to deselect
function handleSelections(e) {
e.preventDefault();
var endPoint = initialValue.length;
if (e.target.selectionEnd > initialValue.length + 1) {
endPoint = e.target.selectionEnd;
}
if (e.target.selectionStart < initialValue.length) {
e.target.setSelectionRange(initialValue.length, endPoint);
};
}
// prevent any selection of text until after "Hi Harry"
$("#target").get(0).addEventListener('select', handleSelections);
// prevent cursor positioning anywhere within "Hi Harry"
$("#target").get(0).addEventListener('click', handleSelections);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="target" type="text" value="Hi Harry">
[1] Tested on Google Chrome 78
You could just call the preventDefault method of the event argument that is passed to the callback function when these conditions are met :
BACKSPACE (e.which === 8) is being pressed.
the input's value is currently equals to Hi Harry.
a better approach is to store the initial value of input thus you'll be able to write anything as its initial value.
const inp = $("#target"), /** referening the input **/
initVal = inp.val(); /** store its initial value **/
/** keydown event handler **/
inp.on('keydown', e => {
e.which == 8 && inp.val() == initVal && e.preventDefault();
/**
* backspace and current value is the same as the initial value then just don't allow the backpace functionnality at this moment.
* if the conditions aren't met, simply the line won't work thus allow inputing.
**/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="target" type="text" value="Hi Harry">

My function that detects keydown and value does not work

So I have an input bar, where text can be typed in.
I am trying to get the console.log to run as soon as the user clicks on backspace and because of that leaves the input with no value.
Right now the console.log only runs if the backspace is clicked while there isn't any value in the input.
GOAL - The console should ONLY run if clicking on backspace CAUSES the input to be empty.
$("#friendsNames").keydown(function(event){
if (event.keyCode == 8) {
if ($("#friendsNames").val() == "") {
console.log("Works!");
}
}
});
<input type="text" name="namesOfFriend" id="friendsNames" value="" />
I'd recommend not tracking key strokes at all, but monitoring the content of the box using the input event which fires when that content changes:
$("#friendsNames").on('input', function(event) {
if (this.value.length === 0) {
console.log("Works!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="namesOfFriend" id="friendsNames" value="" />
This ensures that any interaction that results in the input becoming empty will trigger your code.
Try to make event on keyup coz if input field empty and you're going to enter first character in it console.log() calls. So try this code or go through mention link JSFiddle
JAVASCRIPT Code -
$("#friendsNames").keyup(function(event) {
if (event.keyCode == 8 && $(this).val() == "") {
console.log("Works!");
}
});
$("#friendsNames").keypress(function(event) {
if (event.keyCode == 8 || $(this).val() != "") {
alert("Works!");
}
});
As I understand, you want console.log to execute only where this is any value in the input box, else it shouldn't execute, right? Based on this, below is the code:
$("#friendsNames").on('input', function(){
var inputValue = $(this).val();
if(inputValue.length == 0)
console.log("Works!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="namesOfFriend" id="friendsNames" value="" />

How do I convert Enter to Tab (with focus change) in IE9? It worked in IE8

I have a text input with an onkeydown event handler that converts <Enter> to <Tab> by changing the event's keyCode from 13 to 9.
<input type="text" onkeydown="enterToTab(event);" onchange="changeEvent(this);"
name="" value="" />
<!-- Other inputs exist as created via the DOM, but they are not sibling elements. -->
Javascript:
function enterToTab(myEvent) {
if (myEvent.keyCode == 13) {
myEvent.keyCode = 9;
}
}
function changeEvent(myInput) { var test = "hello"; }
In IE8, this caused the onchange event to fire, but that doesn't happen in IE9. Instead, the input field retains focus. How I can I make that happen? (It works in Firefox 3.6 and Chrome 10.0.) This even works in Browser Mode IE9 if I set the Document Mode to "IE8 standards". But it won't work with a Document Mode of "IE9 standards". (My DocType is XHTML 1.0 Transitional.)
Since it works in IE7 & 8, could this be a bug in IE9 that will get fixed?
Please note: I cannot use input.blur() or manually set a new focus, which is advised by all the other solutions that I've read. I've already tried onkeypress and onkeyup with no luck. I need a generic solution that will cause the web app to literally behave as though I'd hit <Tab>. Also, I don't have jQuery, however, Dojo 1.5 is available to me.
Also note: I KNOW this is "wrong" behavior, and that Enter ought to submit the form. However, my client's staff originally come from a green screen environment where Enter moves them between fields. We must retain the same UI. It is what it is.
UPDATE: I found a difference between IE8 & IE9. In IE8, my setting of myEvent.keyCode holds. In IE9, it does NOT. I can update window.event.keyCode, and it will hold, but that won't affect what happens later. Argh... Any ideas?
Looks like IE9 events are immutable. Once they've been fired you can't change the properties on them, just preventDefault() or cancel them. So you best option is to cancel any "enter" events and re-dispatch a new DOM event from the text input.
Example
function enterToTab(event){
if(event.keyCode == 13){
var keyEvent = document.createEvent("Event");
// This is a lovely method signature
keyEvent.initKeyboardEvent("onkeydown", true, true, window, 9, event.location, "", event.repeat, event.locale);
event.currentTarget.dispatchEvent(keyEvent);
// you may want to prevent default here
}
}
Here's the MSDN documentation around IE9 DOM events:
Event Object - http://msdn.microsoft.com/en-us/library/ms535863(v=vs.85).aspx
createEvent - http://msdn.microsoft.com/en-us/library/ff975304(v=vs.85).aspx
initialize a Keyboard Event - http://msdn.microsoft.com/en-us/library/ff975297(v=vs.85).aspx
Here is a different idea; change the on submit so that it calls a function instead of processing the form. in the function check all the fields to see if they are blank, then focus on the next field that doesn't have a value.
So they type a value into field 1, hit enter, and the function runs. it sees that field 1 is full, but field 2 isn't, so focus on field 2.
Then when all the fields are full, submit the form for processing.
If the form has fields that can be blank, you could use a boolean array that would keep track of which fields received focus using the onfocus() event.
Just an outside the box idea.
The previous IE-version allowed the non standard writable event.keyCode property, IE9 now conforms to the standards.
You may want to consider the functionality you are after: you want to make the enter key behave like the tab key, i.e. moving the focus to the next (text) input field. There are more ways to do that. One of them is using the tabindex attribute of the text input fields. If you order the fields in your form using this tabindex attribute, the functions I present here may yield the same result as your previous keyCode method. Here are two functions I tested in this jsfiddle. An (text) input field now looks like:
<input type="text"
onkeypress="nextOnEnter(this,event);"
name="" value=""
tabindex="1"/>
the functions to use for tabbing:
function nextOnEnter(obj,e){
e = e || event;
// we are storing all input fields with tabindex attribute in
// a 'static' field of this function using the external function
// getTabbableFields
nextOnEnter.fields = nextOnEnter.fields || getTabbableFields();
if (e.keyCode === 13) {
// first, prevent default behavior for enter key (submit)
if (e.preventDefault){
e.preventDefault();
} else if (e.stopPropagation){
e.stopPropagation();
} else {
e.returnValue = false;
}
// determine current tabindex
var tabi = parseInt(obj.getAttribute('tabindex'),10);
// focus to next tabindex in line
if ( tabi+1 < nextOnEnter.fields.length ){
nextOnEnter.fields[tabi+1].focus();
}
}
}
// returns an array containing all input text/submit fields with a
// tabindex attribute, in the order of the tabindex values
function getTabbableFields(){
var ret = [],
inpts = document.getElementsByTagName('input'),
i = inpts.length;
while (i--){
var tabi = parseInt(inpts[i].getAttribute('tabindex'),10),
txtType = inpts[i].getAttribute('type');
// [txtType] could be used to filter out input fields that you
// don't want to be 'tabbable'
ret[tabi] = inpts[i];
}
return ret;
}
If you don't want to use tabindex and all your input fields are 'tabbable', see this jsfiddle
[EDIT] edited functions (see jsfiddles) to make use of event delegation and make it all work in Opera too. And this version imitates shift-TAB too.
The code above causes problems. Here's some code that will help you. Works on IE9, FF5 etc.
function getNextElement(field) {
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
return form.elements[++e % form.elements.length];
}
function tabOnEnter(field, evt) {
if (evt.keyCode === 13) {
if (evt.preventDefault) {
evt.preventDefault();
} else if (evt.stopPropagation) {
evt.stopPropagation();
} else {
evt.returnValue = false;
}
getNextElement(field).focus();
return false;
} else {
return true;
}
}
And then you should just create your input texts or whatever
<input type="text" id="1" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="2" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="3" onkeydown="return tabOnEnter(this,event)"/>
<input type="text" id="4" onkeydown="return tabOnEnter(this,event)"/>
A <button> element on a page will cause this problem.
In IE9 a <button> element takes the focus when Enter is pressed. Any submit or reset button will cause the problem too. If you are not using submit/reset then you can fix this by changing all buttons to <input type="button"> or by setting the button's type attribute to button. i.e.
<button type="button">Click me!</button>
Alternatively as per KooiInc's answer, you can edit your javascript to use event.preventDefault(); to prevent the Enter key acting this way, and explicitly call focus() on the next element in the tab order.
Here is some test code I wrote that demonstrates the problem with the button element (note the blue focus ring on button3 in IE9):
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>IE problem with Enter key and <button> elements</title>
</head>
<body>
<script>
function press(event) {
if (event.keyCode == 13) {
document.getElementById('input2').focus();
// In IE9 the focus shifts to the <button> unless we call preventDefault(). Uncomment following line for IE9 fix. Alternatively set type="button" on all button elements and anything else that is a submit or reset too!.
// event.preventDefault && event.preventDefault();
}
}
</script>
<input id="input1" type="text" onkeypress="press(event)" value="input1. Press enter here." /><br />
<input id="input2" type="text" value="input2. Press enter here." /><br />
<input id="button1" type="button" value='I am an <input type="button">' /><br />
<button id="button2" type="button">I am a <button type="button"></button><br />
<button id="button3">I am a <button>. I get focus when enter key pressed in IE9 - wooot!</button><span>As per Microsoft docs on <a target="_tab" href="http://msdn.microsoft.com/en-us/library/ms534696%28v=vs.85%29.aspx">BUTTON.type</a> it is because type defaults to submit.</span>
</body>
</html>
Mike Fdz's code is superb. In order to skip over hidden fields, you may want to change the line
return form.elements[++e % form.elements.length];
to this:
e++;
while (form.elements[e % form.elements.length].type == "hidden") {
e++;
}
return form.elements[e % form.elements.length];
Use onpaste along with onkeypress like
Consider you have wrriten a javascript function which checks the text lenght so we will need to validate it on key press like as below
<asp:TextBox ID="txtInputText" runat="server" Text="Please enter some text" onpaste="return textboxMultilineMaxNumber(this,1000);" onkeypress="return textboxMultilineMaxNumber(this,1000);"></asp:TextBox>
onkeypress will work in both FF and IE
but if you try to do ctr+V in textbox then onpaste will handle in IE in FF onkeypress takes care of it
This is what I have done with what I found over the internet :
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") || (node.type=="radio")))
{
getNextElement(node).focus();
return false;
}
}
function getNextElement(field)
{
var form = field.form;
for ( var e = 0; e < form.elements.length; e++) {
if (field == form.elements[e]) {
break;
}
}
e++;
while (form.elements[e % form.elements.length].type == "hidden")
{
e++;
}
return form.elements[e % form.elements.length];;
}
To prevent a "submit event" triggered by Enter-Keyboard in your Form in IE9, retire any button inside the form area. Place him (button) in outside of form's area.
function enterAsTab() {
var keyPressed = event.keyCode; // get the Key that is pressed
if (keyPressed == 13)
{
//case the KeyPressed is the [Enter]
var inputs = $('input'); // storage a array of Inputs
var a = inputs.index(document.activeElement);
//get the Index of Active Element Input inside the Inputs(array)
if (inputs[a + 1] !== null)
{
// case the next index of array is not null
var nextBox = inputs[a + 1];
nextBox.focus(); // Focus the next input element. Make him an Active Element
event.preventDefault();
}
return false;
}
else {return keyPressed;}
}
<HTML>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onKeyPress="return enterAsTab();">
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
</body>
</HTML>

problem in addEventListener for keypress event... for restricting the input charcters only

I have placed one textbox.... I want to put restriction on it ..
that digits and special characters should not be allowed to input in textbox...
how can i do using onkeypress event in Javascript ???
my code is ...
<script>
function event()
{
document.getElementById("TX1").addEventListener("keypress", handleKeyPress, false);
}
function handleKeyPress(e)
{
var restricted = "0123456789_#!";
var key = e.keyCode || e.which;
var i=0;
for(;i<restricted.length;i++)
{
if (restricted.charCodeAt(i) == key)
{
e.returnValue = false;
}
return true;
}
</script>
<body onLoad="event();">
<input type="text" name="T1" id="TX1" size="27" maxlength="35" >
</body>
that digits and special characters should not be allowed to input in textbox...
Don't do this through keypress filtering. It's user-hostile, confusing, messes up other control keypresses and is easy to defeat by using other methods of input, such as copy/paste, drag/drop, form fillers, spellcheckers, IMEs...
Instead, have a warning that visibly directs the user when they've put something unexpected in, eg.:
<input type="text" name="T1" id="TX1"/>
<div id="TX1_help">
Please do not use numbers or ‘!’, ‘_’ or ‘#’ characters in this field.
</div>
<script type="text/javascript">
var tx1= document.getElementById('TX1');
var tx1help= document.getElementById('TX1_help');
function checkTX1() {
var isok= /^[^0-9_#!]*$/.test(tx1.value);
tx1help.style.display= isok? 'none' : 'block';
}
checkTX1();
// Re-check the field every time a key is pressed or other change event.
// To ensure it is still checked in a timely fashion in the case of
// non-keyboard events, add a timer as well.
//
tx1.onchange=tx1.onkeyup= checkTX1;
setInterval(checkTX1, 500);
</script>
You can use addEventListener for the event attachment if you want to, but be aware this won't work in IE<9, for which you would need the attachEvent model. (event.returnValue is specific to the IE attachEvent model and will not work with addEventListener, which uses event.preventDefault() instead.)
Try the following:
document.getElementById('TX1').addEventListener('keypress', function(event) {
if (event.keyCode == 13) {
handleKeyPress();
}
});

Prevent form submission with enter key

I just wrote this nifty little function which works on the form itself...
$("#form").keypress(function(e) {
if (e.which == 13) {
var tagName = e.target.tagName.toLowerCase();
if (tagName !== "textarea") {
return false;
}
}
});
In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?
You can mimic the tab key press instead of enter on the inputs like this:
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.
Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:
<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
Here is a modified version of my function. It does the following:
Prevents the enter key from working
on any element of the form other
than the textarea, button, submit.
The enter key now acts like a tab.
preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.
So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
}
From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.
The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.
<body OnKeyPress="return disableKeyPress(event)">
The javascript code should be:
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">
Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.
By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.
In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.
$(document).on( 'keypress', '.input_class', function (e) {
if (e.charCode==13) {
$(this).parent('.container').children('.button_class').trigger('click');
return false;
}
});
In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.
Note that the input and the button have to be in the same container.
The previous solutions weren't working for me, but I did find a solution.
This waits for any keypress, test which match 13, and returns false if so.
in the <HEAD>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.which == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
I prefer the solution of #Dmitriy Likhten, yet:
it only worked when I changed the code a bit:
[...] else
{
if (focusNext){
$(this).focus();
return false; } //
}
Otherwise the script didn't work.
Using Firefox 48.0.2
I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.
$(document).ready(function () {
$("#item-form").keypress(preventEnterSubmit);
});
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
if (this === e.target) {
focusNext = true;
} else {
if (focusNext) {
$(this).focus();
return false;
}
}
});
return false;
}
}
}

Categories

Resources