![](/img/trans.png)
[英]for input type="number" how to set default value to 0
[英]What is the default type of input field value when particularly specified to type=“number”?
我在React钩子和上下文Api中使用reactJs,在正常的html形式中,我必须输入类型为text的标签,当我试图了解我们在javascript中使用“ typeOf”函数获取的值的类型时。 输入字符串值时得到字符串类型,但是输入数字时显示未定义。
const [name, setName] = useState('');
const [price, setPrice] = useState('');
const [movies , setMovie] = useContext(MovieContext)
const updateName = (e) => {
setName(e.target.value)
}
const updatePrice = (e) => {
setPrice(e.target.price);
}
const addMovie = (e) => {
e.preventDefault();
setMovie(prevMovies => {
return [...prevMovies, { name: name, price: price }]
})
console.log(typeof(price)) //getting undefined
console.log(typeof(name)) //getting string
}
return (
<div>
<form onSubmit={addMovie}>
<input type="text" name="name" value={name} onChange={ updateName }/>
<input type="text" name="price" value={price} onChange={ updatePrice } />
<button>Submit</button>
</form>
</div>
);
您应该将值解析为数字,因为您没有price
属性来存储值,因此您可以将值解析为数字。
setPrice(Number(e.target.value));
另外,您也可以将输入的类型更改为数字
HTML仅具有一种数据类型:文本(字符串)。
从HTML元素提取的所有值都是字符串。 如果您需要对值进行区别对待,则取决于您的JavaScript来转换类型。 对于数字数据,有几种方法,但最简单的方法可能是在算术运算符前添加值, 例如+
。
let input = document.querySelector("input"); input.addEventListener("blur", function(){ console.log("Data is: " + typeof input.value); console.log("Converted type is: " + typeof +input.value); });
Enter a number and press TAB: <input type="number">
如果您的数据以数字开头,但后面还有非数字字符,则parseInt()
和parseFloat()
将提取该数字,并在找到非数字值时停止:
let input = document.querySelector("input"); input.addEventListener("blur", function(){ console.log("Data is: " + typeof input.value); // It's a best-practice to always specify the second argument for parseInt() // to ensure the correct conversion. console.log("Converted type is: " + typeof parseInt(input.value, 10)); });
Enter a number and press TAB: <input type="number">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.