[英]Returning Value from JavaScript Function into HTML Form Input Value Attribute
[英]The value of the placeholder in HTML form input cannot be changed with JavaScript from inside of a function
问题与研究:我必须在 JavaScript function 中自动更改 HTML 表单输入的占位符值。我做了一些研究。 给定的代码不适用于我的情况。 我找到了解决方法,但我认为必须有更好的解决方案。 另外,我想知道为什么w3school中给出的代码示例不适用于我的案例。
要求:只有 HTML 和 Vanilla JavaScript
代码:
<body>
<h1>Test JS</h1>
<form id="search">
<div id="input_id">
<input type="text" id="id" name="name" required placeholder="Search...">
</div>
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("id").placeholder = "This works outside of the function"
document.getElementById('search').addEventListener('submit', SearchIt)
async function SearchIt (event) {
event.preventDefault()
var newVal = "123"
document.getElementById("id").placeholder = newVal //This line does not work inside the function, why?
//The following line works but I am looking for a better solution (Vanilla JS only).
document.getElementById("input_id").innerHTML = "<input type='text' id='id' name='name' required placeholder=" + newVal + ">"
}
</script>
</body>
由于required
属性,浏览器在输入为空时阻止提交表单。 但是,如果您在表单中键入内容以满足有效性,占位符将不再可见,因为输入中有文本。
删除required
的属性,或者在设置新占位符时将输入值设置为空字符串,以便查看新占位符。
document.getElementById("id").placeholder = "This works outside of the function" document.getElementById('search').addEventListener('submit', SearchIt) async function SearchIt(event) { event.preventDefault() document.getElementById("id").placeholder = '123'; }
<h1>Test JS</h1> <form id="search"> <div id="input_id"> <input type="text" id="id" name="name" placeholder="Search..."> </div> <button type="submit">Submit</button> </form>
document.getElementById("id").placeholder = "This works outside of the function" document.getElementById('search').addEventListener('submit', SearchIt) async function SearchIt(event) { event.preventDefault() document.getElementById("id").placeholder = '123'; document.getElementById("id").value = ''; }
<h1>Test JS</h1> <form id="search"> <div id="input_id"> <input type="text" id="id" name="name" required placeholder="Search..."> </div> <button type="submit">Submit</button> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.