假设我有两个输入。 当我在 input1 中键入值(例如 0.4)并满足要求时,input2 将删除只读属性。同时如果我在input1中输入的值为0.3,那么input2属性将再次变为只读。
这不起作用。也许我在这里错过了任何东西
$(".input1").keydown(function() {
var dInput = $(this).val();
if (dInput >= 0.4 && dInput <= 0.6) {
$(".input2").attr('readonly', true);
} else {
$(".input2").removeAttr("readonly");
}
});
function isNumberKey(e) { // stub
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" onkeypress="return isNumberKey(event)" id="input1" name="input1" value="" />
<input type="text" class="input2" onkeypress="return isNumberKey(event)" id="input2" name="input2" value="" readonly />
最佳答案
1:使用 keyup
函数,因为该值稍后会填充到字段中,并且您尝试在 keydown
处捕获
2:我已根据您的描述切换了 if 和 else block 语句。您的原始代码与您在这里所说的相矛盾。
$(".input1").keyup(function() {
var dInput = $(this).val();
if(dInput >= 0.4 && dInput <= 0.6)
{
$(".input2").removeAttr("readonly");
}
else
{
$(".input2").attr('readonly',true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="input1" o id="input1" name="input1" value="" />
<input type="text" class="input2" id="input2" name="input2" value="" readonly />
关于javascript - 如果输入值满足要求则添加html属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58619292/