How to remap keyboard within the same textarea - javascript

Currently i am doing a project with remapping characters to words by detecting the keyup function. Unfortunately, i have only been able to retrieve the first character and remap to the word i want. In my project, i need to directly retrieve all of my keyboard input and directly convert it to the word that i want within the same textarea. For example when i type in the textarea, it will convert to "are" directly. I don't know why it stopped retrieving the second character and remapping not function. Below is my code, hope someone can tell me my error. Thank you.
<textarea class="width-100" id="translated-text" onkeyup="myFunctionkey(event);" rows="10"></textarea>
<script>
function myFunctionkey(e) {
conversion();
}
function conversion(){
var x = document.getElementById('translated-text');
if(x.value == 'a'){
x.value='yes';
}
if(x.value == 'q'){
x.value = 'are';
}
}
</script>

From what I understand, you only want to grab the input and replace a key stroke with a complete word.
Maybe this will do. I've changed onkeyup to onkeypress because this is more reliable from what I remember.
<textarea id="translated-text" cols="50" rows="10" onkeypress="replaceInputChar(event);"></textarea>
<script type="text/javascript">
//create replacement map
var map = {
"a": "and",
"b": "bold",
"c": "change"
};
function replaceInputChar(e)
{
var ctl = document.getElementById("translated-text"); //control
var char = String.fromCharCode(e.keyCode); //typed char
if (char in map) //check if letter is defined in map
{
//insert replacement instead of letter
if("selectionStart" in ctl)
{
//in modern browsers we can easily mimic default behavior at cursor position
var pos = ctl.selectionStart;
ctl.value = ctl.value.substr(0, pos) + map[char] + ctl.value.substr(ctl.selectionEnd);
ctl.selectionStart = pos + map[char].length;
ctl.selectionEnd = ctl.selectionStart;
}
else
ctl.value += map[char];
if ("preventDefault" in e) //modern browser event cancelling
e.preventDefault();
else
{
//old browser event cancelling
e.returnValue = false; //IE8
return false;
}
}
}
</script>

You should use comparison operator '==' instead of assignment operator '=' while remapping the value, like this:
x.value=='a'
Edit:
You should check the updated code for your problem here:
https://jsfiddle.net/o4coLr5t/1/
Now, the characters you choose to remap in javascript will display the string, that you map the character to. Otherwise it will display nothing on pressing keys. So, try and add all the character keycodes to the javascript code. Hope that helps.

Related

How to get the -real- last character typed in input with maxlength?

I wanted to know which character the user is typing into an input:
I have an input:
<input maxlength="20"/>
and a script that returns the last typed char:
var eingabe;
$('form').on('keypress', function(event) {
/// if no whitespace:
if (String.fromCharCode(event.keyCode).replace(/\s/g, "").length > 0) {
eingabe = String.fromCharCode(event.keyCode);
$('#eingabe').html("<div>Eingabe : "+ eingabe +"</div>");
}
});
My question is:
because my input has a maxlength attribute, the last typed character on the keyboard is sometimes not the last -real- typed character into the input because the input is "full". How can I get the last character typed into the input?
I haven't tried it, but it must work...
Set onkeypress= or onkeydown= on the Input element and store the key value in a LastChr variable.
I had a similar problem. I wanted to call a function if the user types a specific character into my input field. I solved it with the following:
var input = document.getElementById('myInput');
input.addEventListener('input', function() {
// Get cursor position
var start = this.selectionStart;
// Get last typed character
var lastChar = String.fromCharCode(this.value.charCodeAt(start - 1));
if(lastChar === '[YOURCHARHERE]') {
// do something
}
});
Please keep in mind, that 'input' is only supported down to IE8, but if you don't care about a proprietary browser, you should be fine. I hope this helps.
Inside your function, use the value of the input element to get the last character like $('#input_field').val().substr($('#input_field').val().length - 1) or use your best coding skill to accomplish something similar without accessing the field twice, wink wink.
Use keyup instead:
$('form').on('keyup', function(event) {
var cursorPos = event.target.selectionStart;
var lastTypedChar = elem.target.value[cursorPos - 1];
});

Interactively, don't allow the first character in a text input to be a space, or group of spaces

Firstly, This is NOT a repeat question. Most of the similar questions, I've come across, don't preform the desired action interactively (e.g. "onkeydown", "onkeyup", etc.). I need a pure JavaScript (i.e. NO jQuery) function to disallow the first character of a text-based input to be a space or group of spaces given just the elements ID. Here is what I have:
<script type="text/javascript">
/* Don't allow the first character of a "text-based" input element
* (e.g. text-box, text-area, editable-div's) to be a space, given
* the elements ID ([ eID ]). [BEGIN]
*/
function noPrecedingSpace ( eID )
{
var elmt = document.getElementById(eID);
elmt.addEventListener("keydown", function(event)
{
var strg = elmt.value;
var lastChar = strg.charAt(strg.length - 1);
if ((lastChar == " ")||(lastChar == " ")||(strg == ""))
{
return event.which !== 32;
};
});
};
/* Don't allow the first character of a "text-based" input element
* (e.g. text-box, text-area, editable-div's) to be a space, given the
* elements ID ([ eID ]). [END]
*/
</script>
Any ideas as to why this is not working?
What am I doing wrong?
Please Note: "Paste" is already accounted for, and disallowed on the field by another javascript, that, by the way, is working perfectly.
JSFiddle
Returning true/false is the "old" way of managing event propagation. Better now is to use preventDefault()
var elmt = document.getElementById('noSpaces');
elmt.addEventListener('keydown', function (event) {
if (elmt.value.length === 0 && event.which === 32) {
event.preventDefault();
}
});
This just checks... if the current input length is zero then a space is not allowed.
Also see the fiddle.
You can add/modify to check for non-breaking spaces also, if that's really a problem -- match with a regex like Dave's answer, but only if elmt.value.length is > 0
This, however, would let you type non-spaces, then back-up to the start of the field and insert spaces.
A revised fiddle trims leading whitespace as you're typing, but this also won't entirely solve the problem.
var elmt = document.getElementById('noSpaces');
elmt.addEventListener('keydown', function (event) {
if (event.which === 32) {
elmt.value = elmt.value.replace(/^\s+/, '');
if (elmt.value.length === 0) {
event.preventDefault();
}
}
});
You can keep refining it, even taking the current caret position and the currently selected text into account, but ultimately you must .trim() the string you receive on the server, since I (for one) can send you anything I want to send despite all of your javascript efforts to make me enter a "legal" string.
You can test the value of the input with a regular expression to see if it starts with a space and if so remove the spaces from the start of the value;
var input = document.getElementById('noSpaces');
input.addEventListener('keyup', function(event) {
if(/^\s/.test(input.value)) {
input.value = input.value.replace(/^\s+/,'');
}
});
JSFiddle
Thanks to #StephenP, I have come up with this final answer, which is just perfect for my needs ("visitors_name" field):
<script type="text/javascript">
/* Don't allow the first character of a "text-based" input element (e.g. text-box, text-area, editable-div's, etc.) to be a space, given the elements ID ([ eID ]). Also, don't allow more than one space between adjacent words. [BEGIN] */
/* Usage Example: noPrecedingOrDoubleSpace ("visitors_name"); */
function noPrecedingOrDoubleSpace ( eID )
{
var elmt = document.getElementById(eID);
elmt.addEventListener("keydown", function(event)
{
var strg = elmt.value;
var lastChar = strg.charAt(strg.length - 1);
if ((lastChar == " ")||(lastChar == " ")||(strg == ""))
{
if (event.which === 32)
{
event.preventDefault();
};
};
});
};
/* Don't allow the first character of a "text-based" input element (e.g. text-box, text-area, editable-div's, etc.) to be a space, given the elements ID ([ eID ]). Also, don't allow more than one space between adjacent words. [END] */
</script>
Keep in mind that if you just need no space, only at the beginning of the input, #StephenP's answer is probably more practical, and is the real answer to this question, given the title.
Also remember, that just as #StephenP mentioned, real validation is best done in the server-side script (e.g. php). This JavaScript is just to encourage correct input formatting. Nothing more, nothing less.
Big kudos to #StephenP
Thanks!
Final JSFiddle.

use of Regular expression

While using Javascript, I'm making a limit for the product number in front-end.
The product number should be xxxxx 5 digits number or xxx-xxx style 6 numbers.
What I planned was replacing non-correct text characters to "" for each keypress
and called in front like this onkeypress = "checkonlynumdash();"
for the function, my code is like below.
function checkonlynumdash() {
e = window.event;
var keypress = String.fromCharCode(e.keycode);
var numdashkey = "";
numdashkey = /^[-]|[^0-9-]/;
return numkey.test(keypress);
}
while using window.event, I tried to control the real time keypress, but it
does not seem working with replace. Hope someone can point out missing part.
I see two issues:
e.keycode
I would change to
e.charCode
and use another regex: /[\d-]/, it is more simple.
So the result might be:
function checkonlynumdash() {
e = window.event;
var keypress = String.fromCharCode(e.charCode);
var numdashkey = /[\d-]/;
return numdashkey.test(keypress);
}
Also I can't understand your original regexp: /^[-]|[^0-9-]/ symbol ^ means 'in the beginning of the string' or 'not'.
You can try Simple Mask, it is jQuery plug-in to make masks on input fields.
Usage:
$('input').simpleMask({
'mask': ['####-####','#####-####']
});
Demo

Changing content of DOM text node

Say I have the following HTML:
<div>Some text</div>
I'm wanting to remove the last character from the text each time the user hits the backspace key. Is there a way to actually remove a character from a text node? Or do I have to do something like obj.innerText = 'Some tex' (i.e. trim the last char myself and replace the whole thing).
var div = document.getElementById('my-div');
document.addEventListener('keydown',
function(e) {
if (e.which === 8) {
div.textContent = div.textContent.substring(0, div.textContent.length - 1);
}
}, false);
You may also want to support IE8. In that case, use document.attachEvent() and div.innerText.
Best method I can think of off the top of my head is to use the substring method for Strings.
var s = obj.innerText
// Then On backspace event listener
s = s.substring(0, s.length - 1) // returns s without the last character in the original string.
obj.innerTezt(s) // set the inner HTML back to s
Edit: thanks Jonathan, Dennis for the correction on this answer!
// Get the element
var el = document.queryString("...")
// Get the text contents
var text = el.firstChild
if (text.nodeType === Node.TEXT_NODE) {
// Delete the last character
text.deleteData(text.length - 1, 1)
}
See the CharacterData DOM interface for details of deleteData

Find the first character of input in a textbox

I am stuck in implementing the following:
User starts typing in a textbox.
The javascript on page captures the first character typed, validates that it is an english alphabet (a-z,A-Z) and converts it to lowercase (if necessary).
Make an XMLHttp request based on the input (i.e. if first input character is a, get a.xml, if b get b.xml and so on).
I know how to do the last part (make the xmlhttp request) but am kind of stuck on how to capture the first character and validate it (in a way that works on all browsers). Please guide. Thanks.
Clarification: This is to create a Google Suggest like autocomplete-drop-down menu without the need for server side programs.
Something like this should work:
HTML:
<input type="text" id="myField" />
And in JS:
window.onload = function() {
document.getElementById('myField').onkeyup = function() {
// Validate that the first letter is A-Za-z and capture it
var letter = this.value.match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
this.value = letter + this.value.substring(1);
// Do the request
}
}
}
My vanilla-JS skills are a bit rusty but this should do the trick. Just for the heck of it, here's the same using jQuery:
$(function() {
$('#myField').keyup(function() {
var letter = $(this).val().match(/^([A-Za-z])/);
// If a letter was found
if(letter !== null) {
// Change it to lowercase and update the value
letter = letter[0].toLowerCase();
$(this).val(letter + $(this).val().substring(1);
// Do the request
}
});
});
What part of the problem do you not know how to do? Here's an approach that you can follow. Very likely to need adjustments, but a good starting point
if our text field's id is 'txt'
document.getElementByID('txt').onkeypress = function(e) {
var textInField = this.value;
if (textInField.length == 1) {
var firstChar = textInField.charAt(0);
if (/[a-zA-Z]/.test(firstChar)) {
sendXHR(textInField.value.toLowerCase())
}
} else {
// What do you do if there is one or more chars???
}
}
Note that the other answers here mention onchange, that doesn't fire until the focus leaves the field, which I don't think is what you want

Categories

Resources