Home > Net >  how to enter text and then convert It to other values via java script
how to enter text and then convert It to other values via java script

Time:07-02

I made a script that converts letters into numbers using "var". What is the best way to make a html page to input the text and then translate it to numbers using the script bellow.

var a='1*'
var b="2*"
var c="3*"
var d="4*"
var e="5*"
var f="6*"
var g="7*"
var h="8*"
var i="9*"
var j="10*"
...
var output= [a b].join('');

CodePudding user response:

You need a function that translate the letters to numbers then you can call it from an input. The result of translation can be displayed in a span for example.

function translateLetterToNumber(event) {
  const value = event.target.value;

  let translatedText = value.charCodeAt(0) - 96;

  if (value.length > 1) {
    const splittedValue = value.split('');
    const translatedLetters = splittedValue.map(letter => letter.charCodeAt(0) - 96);
    translatedText = translatedLetters.join('');
  }

  document.getElementById('result').textContent = translatedText;
}
<input type="text" onkeyup="translateLetterToNumber(event)" />
<span id="result"></span>

CodePudding user response:

You can get the letter you like and use charCodeAt(letter) to get the Unicode number for that letter. In Unicode for a is 97. So if a = 1, b = 2 you have to subtract it by 96:

var letter = document.querySelector('input');

letter.addEventListener('change', function() {
  let number = letter.value.charCodeAt(0) - 96;
  console.log(`${letter.value} => ${number}`);
})
<input type="text" maxLenght="1"><label>type a single letter</label>

  • Related