skip to Main Content

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


  1. Loop over the input value’s characters, put the output into an array, format the array.

    function log(){
        var input = document.getElementById("inputBox");
        var inputValue = input.value.toUpperCase();
        var output = [];
        for(let i = 0; i < inputValue.length; i++) {
          output.push(inputValue.charCodeAt(i));
        }
        document.getElementById("outputBox").value = output.join(" ");
    }
    <input id="inputBox" oninput="log()" autofocus placeholder="enter some text!">
    <br />
    character codes: <input id="outputBox" readonly>
    Login or Signup to reply.
  2. 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 be var 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:

    var upperIntpuValue = inputValue.toUpperCase();
    var uivLength = upperInputValue.length;
    
    for(let i = 0; i < uivLength; i++) {
      console.log(upperInputValue.charAt(i));
    }
    

    Consider also that the console.log in your example code is logging the string "idCalc", not the value of the variable called idCalc.

    (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, use codePointAt() and fromCodePoint().")

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search