如果另一个输入的值大于8,我想更改HTML输入的必需属性。(未提交任何内容(
<input id="inputCheck" name="inputCheck" placeholder="" required="true" value="" type="number">
<input id="inputReact" name="inputReact" placeholder="" required="false" value="" type="text">
基本上,如果inputCheck的值大于8,则将inputReact的rrequired设置为true。我知道如何更改属性,问题是在不提交的情况下检查值。
您可以使用input
侦听器
let checkBox = document.getElementById("inputCheck")
, textBox = document.getElementById("inputReact")
checkBox.addEventListener("input", evt => {
if(evt.target.value > 8) textBox.setAttribute("required", true)
else textBox.removeAttribute("required")
})
<input id="inputCheck" name="inputCheck" placeholder="" required="true" value="" type="number">
<input id="inputReact" name="inputReact" placeholder="" required="false" value="" type="text">
向所需的输入字段添加一个更改事件侦听器。
$('#inputCheck').change(function() {
const value = $(this).val();
const rInput$ = $('#inputReact');
if(value > 8) { // could also use parseInt(value) to convert value into number if it isn't already.
rInput$.attr('required', true);
} else {
rInput$.removeAttr('required');
}
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>keydown demo</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<form>
<input id="inputCheck" name="inputCheck" placeholder="" required="true" value="" type="number">
<input id="inputReact" name="inputReact" placeholder="" required="false" value="" type="text">
</form>
<script>
var xTriggered = 0;
$(document).ready(function()
{
alert("ok");
$( "#inputCheck" ).keydown(function( event ) {
var myLength = $("#inputCheck").val().length;
if((myLength+1) > 8)
{
$("#inputReact").attr("required","true");
}
});
});
</script>
</body>
</html>