when i try to log idCalc it only returns the keycode from the first character from the input
My Code
function log(){
var input = document.getElementById("inputBox");
var inputValue = input.value;
var idCalc = inputValue.toUpperCase().char;
console.log('idCalc')
}
should return the keycode from all the characters inside the input
2
Answers
Loop over the input value’s characters, put the output into an array, format the array.
According to the MDN docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt using
charAt()
(which is what I’m assuming you’re using on line 4 of your example code:var idCalc = inputValue.toUpperCase().char;
should bevar idCalc = inputValue.toUpperCase().charAt();
) will return a new string consisting of the single UTF-16 code unit at the given index.However, in your example you don’t provide a index value. As the docs state, if index is undefined then it is converted to 0, which is the first index. Hence, why you only get the first character’s code unit.
To get all of the code units you need to apply this function to each character by looping over the characters. There are many ways you can do this depending on your needs. For one example, on line 4 do:
Consider also that the
console.log
in your example code is logging the string "idCalc", not the value of the variable calledidCalc
.(An additional technical note: according to the docs, "
charAt()
always indexes the string as a sequence of UTF-16 code units, so it may return lone surrogates. To get the full Unicode code point at a given index, usecodePointAt()
andfromCodePoint()
.")