我需要使用javascript验证许多不同的文本框,我不希望每个文本框都有getElementById。在提交按钮之前,您如何确认每个文本框中都有一个单词?
<table id="inputTable">
<tr>
<td>
<P>Verb: <input type="text" required id="varA"></p>
<P>Adjective: <input type="text" required id="varB"></p>
<P>Noun (plural): <input type="text" required id="varC"></p>
<P>Adjective: <input type="text" required id="varD"></p>
<P>Verb enging in "ing": <input type="text" required id="varE"></p>
<P>Verb: <input type="text" required id="varF"></p>
<P>Number: <input type="text" required id="varG"></p>
<P>Adjective: <input type="text" required id="varH"></p>
</td>
<td>
<P>Noun (plural): <input type="text" required id="varI"></p>
<P>Noun (plural): <input type="text" required id="varJ"></p>
<P>Noun (plural): <input type="text" required id="varK"></p>
<P>Relative (plural): <input type="text" required id="varL"></p>
<P>Adjective: <input type="text" required id="varM"></p>
<P>Adjective: <input type="text" required id="varN"></p>
<P>Noun (plural): <input type="text" required id="varO"></p>
<P>Verb: <input type="text" required id="varP"></p>
</td>
</tr>
答案 0 :(得分:1)
function submit_form() {
all_input = document.querySelectorAll('input[type="text"]');
console.log(all_input);
for (var i = 0; i < all_input.length; ++i) {
if (all_input[i].value.trim().match(/\w/) == null) {
alert("You need to enter a word in each text box");
return
}
}
}
document.getElementById('fm').addEventListener('click',submit_form)
<form >
<table id="inputTable">
<tr>
<td>
<P>Verb:
<input type="text" required id="varA">
</p>
<P>Adjective:
<input type="text" required id="varB">
</p>
<P>Noun (plural):
<input type="text" required id="varC">
</p>
<P>Adjective:
<input type="text" required id="varD">
</p>
<P>Verb enging in "ing":
<input type="text" required id="varE">
</p>
<P>Verb:
<input type="text" required id="varF">
</p>
<P>Number:
<input type="text" required id="varG">
</p>
<P>Adjective:
<input type="text" required id="varH">
</p>
</td>
<td>
<P>Noun (plural):
<input type="text" required id="varI">
</p>
<P>Noun (plural):
<input type="text" required id="varJ">
</p>
<P>Noun (plural):
<input type="text" required id="varK">
</p>
<P>Relative (plural):
<input type="text" required id="varL">
</p>
<P>Adjective:
<input type="text" required id="varM">
</p>
<P>Adjective:
<input type="text" required id="varN">
</p>
<P>Noun (plural):
<input type="text" required id="varO">
</p>
<P>Verb:
<input type="text" required id="varP">
</p>
</td>
</tr>
<button type='submit' id="fm">SUbmit</button>
</form>
答案 1 :(得分:0)
您可以为每个文本框使用$('input[type=text]')
而不是getElementByI ..
答案 2 :(得分:0)
将此属性添加到每个输入:pattern="^[a-zA-Z]+$"
- 如果字段中包含除字母字符以外的任何内容,则会阻止提交表单 - 假设这是在html form
中。< / p>
答案 3 :(得分:0)
HTML5表单验证允许pattern
属性中的正则表达式。请参阅MDN的数据表单验证](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Data_form_validation)
答案 4 :(得分:0)
您可以使用document.querySelectorAll
返回文档中元素的列表。
使用现有代码尝试此脚本:
var txtbox = document.querySelectorAll("input[type=text]");
for(var i = 0;i<txtbox.length;i++)
{
alert("Enter Text");
}