I'm trying to get a value from <select>
<option>
tag. Select tag is like this
<select name="pref" className="XXXX" onChange={getValue}>
{areaData.map((area, index) => (
<option key={index} value={area.areaCode}>XXXXX</option>
))}
</select>
I gave a number here in value={area.areaCode}
Then, getting value function is like this
const getValue = function (e: any) {
const areaCodeString = e.target.value
const areaCodeNumber = e.target.valueAsNumber
console.log(areaCodeString);
console.log(areaCodeNumber);
}
but Output said areaCodeString is "1" (string) and areaCodeNumber is "undefined" I want to get this value as number but it doesn't work. How can I get the value as number? I thought e.target.valueAsNumber was only solution.
CodePudding user response:
You can simply parse it as Number
.
const areaCodeNumber = Number(areaCodeString)
Alternatively, you can use parseInt
or parseFloat
.
Note: You don't have valueAsNumber
property in e.target
, that's why it gives you undefined
.
Refer: https://stackoverflow.com/a/12813049/11566161
https://cullenwebservices.com/javascript-numbers-number-parseint-parsefloat/
CodePudding user response:
You can try
const areaCodeNumber = Number(e.target.value)