Why do I get "_fg_" instead of "fg_"? - javascript

document.addEventListener("keydown", (evt) => {
if (evt.keyCode >= 65 && evt.keyCode <= 90) {
let command = document.getElementById("cmdInput").textContent;
let str2 = command.substring(0, command.length - 1) + evt.key + "_";
console.log(str2);
document.getElementById("cmdInput").textContent = str2;
}
});
<div id="cmdInput">_</div>
As you can see, I get "_fg_" instead of "fg_". Why? Why isn't the leading underscore not moving as of my typing?

Related

why is the keypress not working on mobile?

Good day, the following code works on desktop but not mobile. When I switch to keyup or keydown instead of keypress it doesn't work anywhere.
function attribUppercase(e)
{
var charInput = e.keyCode;
if((charInput >= 97) && (charInput <= 122)) { // lowercase
if(!e.ctrlKey && !e.metaKey && !e.altKey) { // no modifier key
var newChar = charInput - 32;
var start = e.target.selectionStart;
var end = e.target.selectionEnd;
e.target.value = e.target.value.substring(0, start) + String.fromCharCode(newChar) + e.target.value.substring(end);
e.target.setSelectionRange(start+1, start+1);
e.preventDefault();
}
}
}
window.onload = function() {
var element = document.getElementById("attrib-108-0");
if(typeof(element) != 'undefined' && element != null){
document.getElementById("attrib-108-0").addEventListener("keypress", attribUppercase, false);
}
}

I want to perform different operation processes alternately in order with the same key operation

For example, you can start with a specific key and stop with a click or another key,
// Alt + Shift + ↓ Auto scroll
document.addEventListener("DOMContentLoaded", (l) => {
var m;
setInterval(m);
$(window).keydown((e) => {
//pattern 1
if (e.altKey && e.shiftKey && e.keyCode == 40) {
if (!m) {
m = setInterval((s) => {
scrollBy(0, s || 1);
}, 35);
}
}
$(document).on('click', () => {
clearInterval(m);
m = undefined;
});
//pattern 2
setInterval(m);
if (e.altKey && e.shiftKey && e.keyCode == 40) {
if (!m) {
m = setInterval((s) => {
scrollBy(0, s || 1);
}, 35);
}
}
if (e.keyCode == 96) { //ten key of「0」key
clearInterval(m);
m = undefined;
}
//}, false);
});
});
like this:
Attempting to process start and stop with the same key will not work.
In the example below
Start with Alt + Shift + ↓,
Stop as well
I want to do it with Alt + Shift + ↓. How can I correct it to implement the desired function?
The operating environment uses a third-party extension of the Chrome WEB store.
if i have understood what you want, you want to use the same keys to start and stop so, to do that you have to use a sort of toggle:
var timer;
var last_state = "keyup";
var param = 10;
$(window).on("keydown keyup", (e) => {
if (e.type == "keyup" && e.which == 40) {
last_state = "keyup";
}
if (e.type == "keydown" && e.type != last_state && e.altKey && e.shiftKey && e.which == 40) {
last_state = e.type;
if (!timer) {
timer = setInterval(() => {
scrollBy(0, param || 1);
}, 35);
} else {
clearInterval(timer);
timer = undefined;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Javascript charCodeAt() not returning correct codes.. or is it?

I'm trying to find the keycodes (if that's even what I need) and to change the character to the incremented keycode (this is just for a coding challenge) and it's not working
function LetterChanges(str) {
var newString = "";
var keyCode;
for(var i = 0; i < str.length; ++i)
{
keyCode = str.charCodeAt(i);
console.log(keyCode);
if( keyCode > 57 && keyCode < 122)
{
//add 1 to the keycode
newString += String.fromCharCode(i+1);
//console.log(String.fromCharCode(i+1));
}
else if(keyCode === 90)
{
//if it's a z being examined, add an a
newString += "a";
}
else
//it is a symbol, so just add it to the new string without change
newString += str[i];
}
return newString.toUpperCase();
}
console.log(LetterChanges("Charlie"));
change
newString += String.fromCharCode(i+1);
to
newString += String.fromCharCode(keyCode+1);
Jsfiddle: http://jsfiddle.net/techsin/pnbuae83/1/
function codeIncreaser(input) {
var str='', code=null;
Array.prototype.forEach.call(input, function (e) {
code = e.charCodeAt();
if ((code>64 && code<90) || (code>96 && code<122)) {
code++;
} else if (code == 90) {
code = 65;
} else if (code == 122) {
code = 97;
}
str += String.fromCharCode(code);
});
return str;
}
var text = codeIncreaser('abczABC');
console.log(text);
This accommodates lowercase letters as well.
and if you wanna make code somewhat compact you could do something like this...
function $(i) {
var s='', c;
Array.prototype.forEach.call(i, function (e) {
c = e.charCodeAt();
((c>64&&c<90)||(c>96&&c<122))?c++:((c == 90)?c=65:(c==122&&(c=97)));
s += String.fromCharCode(c);
});
return s;
}
console.log($('abczABC #-#'));

Javascript dashes in phone number

I tried to research the answer to this question but I'm lost. I am trying to make a one search bar that automatically puts a dash in the phone number. I've solved that.
The next part is the challenging part. How can I make it always do XXX-XXX-XXXX, even if the characters pasted were something like 555 555 1212 or 555---555-1212, where it will only reel back the number and output with 555-555-1212. It shouldn't count the spaces or extra dashes as a character.
I found: http://www.jotform.com/answers/15202-can-I-add-script-to-my-form-that-will-automatically-add-hyphens-in-between-the-3-digit-area-code-and-also-the-3-digit-prefix
I changed it just a bit by adding:
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
<input id="input_4" class="form-textbox" maxlength="15" name="atn" size="25" onBlur='addDashes(this)' />
Right now, this works only if the user puts 5555555555 and automatically turns it into 555-555-5555. I'm trying to figure out how to take something like 5-55555-5555 and turn it into 555-555-5555. Currently, it makes it 5-5-555-5-5555.
See my dilemma? lol. It can't be php or any server side scripting as this must be able to run on a desktop.
Resolution:
<SCRIPT LANGUAGE="JavaScript">
function addDashes(f)
{
f.value = f.value.replace(/\D/g, '');
f.value = f.value.slice(0,3)+"-"+f.value.slice(3,6)+"-"+f.value.slice(6,15);
}
</SCRIPT>
First, clean your input by deleting all chars that are not numbers (ref.: Regex to replace everything except numbers and a decimal point)
Then, you put your dashes.
function addDashes(f)
{
f_val = f.value.replace(/\D[^\.]/g, "");
f.value = f_val.slice(0,3)+"-"+f_val.slice(3,6)+"-"+f_val.slice(6);
}
I have a strong tendency to treat phone numbers as a straight string of 10 digits with no formatting (so I can apply formatting to them on-the-fly, as needed and so searching and comparison is simpler), although that may change if I ever have to deal with international phone numbers. If all you're dealing with is US phone numbers, this will work nicely (formats it as it's typed):
function addDashes(f) {
var r = /(\D+)/g,
npa = '',
nxx = '',
last4 = '';
f.value = f.value.replace(r, '');
npa = f.value.substr(0, 3);
nxx = f.value.substr(3, 3);
last4 = f.value.substr(6, 4);
f.value = npa + '-' + nxx + '-' + last4;
}​
Here's a fiddle: http://jsfiddle.net/EYuk5/
transform with string method replace
let phone = '0884332212'.replace(/^(\d{3})(\d{3})(\d{4})/, '$1-$2-$3')
console.log(phone)
// => 088-433-2212
I did this
function addDashesToNumber(number){
const numWithoutDashes = number.replace(/[^0-9]/g, '')
if(numWithoutDashes.length > 10) return number.slice(0, -1)
const dashPlaces = [3, 6]
return numWithoutDashes
.split('')
.reduce((acc, curr, i) => dashPlaces.includes(i) ? [...acc, '-', curr] : [...acc, curr], [])
.join('')
}
Try this:
function dashedNumber(value){
const afterIndices = [3,6,8];
const length = value.length;
let newValue = ''
for(let i=0; i<length; i++){
if(afterIndices.includes(i))
newValue+='-'
newValue+=value[i];
}
return newValue;
}
Here's a fiddle: https://jsfiddle.net/v9gq5jkw/.
<input id="phone">
function phone_formatting(ele, restore) {
var new_number,
selection_start = ele.selectionStart,
selection_end = ele.selectionEnd,
number = ele.value.replace(/\D/g, '');
if (number.length > 2) {
new_number = number.substring(0, 3) + '-';
if (number.length === 4 || number.length === 5) {
new_number += number.substr(3);
} else if (number.length > 5) {
new_number += number.substring(3, 6) + '-';
}
if (number.length > 6) {
new_number += number.substring(6);
}
} else {
new_number = number;
}
ele.value = (new_number.length > 12) ? new_number.substring(0, 12) : new_number;
if (new_number.slice(-1) === '-' && restore === false &&
(new_number.length === 8 && selection_end === 7) ||
(new_number.length === 4 && selection_end === 3)) {
selection_start = new_number.length;
selection_end = new_number.length;
} else if (restore === 'revert') {
selection_start--;
selection_end--;
}
ele.setSelectionRange(selection_start, selection_end);
}
function phone_number_check(field, e) {
var key_code = e.keyCode,
key_string = String.fromCharCode(key_code),
press_delete = false,
dash_key = 189,
delete_key = [8, 46],
direction_key = [33, 34, 35, 36, 37, 38, 39, 40],
selection_end = field.selectionEnd;
if (delete_key.indexOf(key_code) > -1) {
press_delete = true;
}
if (key_string.match(/^\d+$/) || press_delete) {
phone_formatting(field, press_delete);
} else if (direction_key.indexOf(key_code) > -1) {} else if (dash_key === key_code) {
if (selection_end === field.value.length) {
field.value = field.value.slice(0, -1)
} else {
field.value = field.value.substring(0, (selection_end - 1)) + field.value.substr(selection_end)
field.selectionEnd = selection_end - 1;
}
} else {
e.preventDefault();
phone_formatting(field, 'revert');
}
}
document.getElementById('phone').onkeyup = function(e) {
phone_number_check(this, e);
}
Beside adding dashes, you will need to deal with the position of the cursor, especially in case of deletion.
This AMD module does exactly that: https://github.com/whenyoubelieve2014/us-telephone-input

Changing the charCode of the key pressed

In following example I am attempting to change the charCode of the key pressed but it does not change. When I press "a" I want it to type "b". What am I doing wrong?
$("#target").keypress(function(event) {
if ( event.which == 97 ) {
//alert('pressed a');
//event.preventDefault();
event.keyCode = 98;
event.charCode = 98;
event.which = 98;
}
});
You can't override the keycode in the event object...
Look at this snippet:
$('#target').keypress(function(e){
if (e.which == 97)
this.value = this.value + String.fromCharCode(98)
else
this.value = this.value + String.fromCharCode(e.which)
....
return false;
})
replace comma and dash to slash.
$('.pdate').on('keypress', function (e) {
var ch = String.fromCharCode(e.keyCode);
$("div").text(e.keyCode)
if (!((ch >= '0' && ch <= '9') ||
ch == '/' || ch == ',' || ch == '-')) {
return false;
}
if (ch == ',' || ch == '-')
{
var val = $(this).val();
var s = this.selectionStart;
val = val.slice(0, s) + "/" + val.slice(s, val.length);
$(this).val(val)
this.selectionStart = s +1;
this.selectionEnd = s +1;
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="pdate" />
<div></div>

Categories