問題與研究:我必須在 JavaScript 函式中自動更改 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>
uj5u.com熱心網友回復:
由于該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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/472784.html
標籤:javascript html 形式 输入 占位符
