如何使用javascript重置字段值
如果如何使用javascript重置字段值,javascript,Javascript,如果quantity中的值无效,我想将其显示为1 <input type = "number" id = "quantity" value="1" onchange="Validatequantity()" /> 函数Validatequantity(){ var num=document.getElementById('quantity')。值; 如果(数值10){ 警报(“无效票号…应介于1-10之间”); num=1;//重置部分在这里(不工作) } } 函数Vali
quantity
中的值无效,我想将其显示为1
<input type = "number" id = "quantity" value="1" onchange="Validatequantity()" />
函数Validatequantity(){
var num=document.getElementById('quantity')。值;
如果(数值<1 | |数值>10){
警报(“无效票号…应介于1-10之间”);
num=1;//重置部分在这里(不工作)
}
}
函数Validatequantity(){
var num=document.getElementById('quantity')。值;
如果(数值<1 | |数值>10){
警报(“无效票号…应介于1-10之间”);
num=1;//重置部分在这里(不工作)
document.getElementById('quantity')。value=1;//将输入值设置为1
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
}
如果要使用变量,请将其作为对元素的引用,而不是其值:
function Validatequantity() {
var num = document.getElementById('quantity');
if (num.value < 1 || num.value > 10 ) {
num.value = 1;
}
}
函数Validatequantity(){
var num=document.getElementById('quantity');
如果(数值<1 | |数值>10){
数值=1;
}
}
它与num=1
不一样吗?因为num=document.getElementById('quantity').value
它不是live node
,我想你可以给我一个关于它的文章链接,这样我就可以了解它的工作原理了btw@user2650277元素是活动的
,但不是值
function Validatequantity() {
var num = document.getElementById('quantity').value;
if (num < 1 || num > 10 ) {
alert('Invalid ticket number ...Should be between 1-10');
num = 1; // reset part is here(don't work)
document.getElementById('quantity').value = 1; // Set input value to 1
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
}
function Validatequantity() {
var num = document.getElementById('quantity');
if (num.value < 1 || num.value > 10 ) {
num.value = 1;
}
}