Home > OS >  Get type of value entered
Get type of value entered

Time:07-17

I have a small piece of code where I need to get the typeof value entered. Right now, i am getting only value entered in the box, but not the typeof. Can anyone help me here?

<p id="res">Value</p><input type="text" id="fname" name="fname"><br><br>

<script>
    document.getElementById('fname').addEventListener('input', function(){
        document.getElementById('res').textContent= this.value;
    });
</script>

CodePudding user response:

You need to use typeof keyword, and if you want to test number vs string then you need to do a check type by using isNaN and Number

I changed your function to arrow function

document.getElementById('fname').addEventListener('input', e => {
  const value = e.currentTarget.value;
  const checkType = isNaN(Number(value)) ? value : Number(value)
  document.getElementById('res').textContent = typeof checkType
})
<p id="res">Value</p><input type="text" id="fname" name="fname"><br><br>

CodePudding user response:

So typeof is not going to help you here. because the input is type="text" everthing typed into it will be casted to a string. exp: some types a 4, will be given to the js as "4". Im assuming you dont care about the type itself and just really want to know if they typed in a number. if thats the case, use the isNaN Function which will return false if a value can be casted to a number

isNaN("4") //false isNaN("hello") //true

PS: NaN stands for not a number

  • Related