我正在尝试创建一个表单,根据选中的复选框更改输入字段的属性。我在另一个问题中看到我们可以创建一个具有类似功能的元素及其属性,但是当我将其调整为这种形式时,它不起作用,任何人都可以帮助我做到这一点吗?我知道使用 JQuery 更容易,但我需要用纯 JS 完成此操作。
<!DOCTYPE html>
<html>
<body>
<form role="search" method="get" action="">
<input type="checkbox" id="check-minor" name="check-minor" onclick="searchFunc()"> <label for="check-minor">Menor</label>
<input type="text" name="qt" id="qt" placeholder="Write your Shop Code" required pattern="[0-9A-Za-z]{7,9})" size="30">
</div>
<button type="submit" class="btn btn-default" id="submit-button">Search</button>
</form>
<script>
function setAttributes(elements, attributes) {
Object.keys(attributes).forEach(function(name) {
element.setAttribute(name, attributes[name]);
})
}
var qtpie = document.getElementById("qt");
function searchFunc() {
if (document.getElementById("check-minor").checked){
setAttributes(qtpie, {
required pattern: "[0-9]{11}",
placeholder: "Shop Code for Minors"
})
} else {
document.getElementById("qt").placeholder= "Write your Shop Code"
}
</script>
</body>
</html>
最佳答案
这里,您的代码中存在一些拼写错误问题并且缺少大括号
function setAttributes(elements, attributes) {
Object.keys(attributes).forEach(function (name) {
elements.setAttribute(name, attributes[name]);
})
}
var qtpie = document.getElementById("qt");
function searchFunc() {
if (document.getElementById("check-minor").checked) {
setAttributes(qtpie, {
required: "",
pattern: "[0-9]{11}",
placeholder: "Shop Code for Minors"
})
} else {
document.getElementById("qt").placeholder = "Write your Shop Code"
}
}
<!DOCTYPE html>
<html>
<body>
<form role="search" method="get" action="">
<input type="checkbox" id="check-minor" name="check-minor" onclick="searchFunc()">
<label for="check-minor">Menor</label>
<input type="text" name="qt" id="qt" placeholder="Write your Shop Code" required pattern="[0-9A-Za-z]{7,9})" size="30">
<button type="submit" class="btn btn-default" id="submit-button">Search</button>
</form>
</body>
</html>
关于javascript - 如何为一个Element设置变化属性?使用 JS 而不是 JQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51765859/