我要这样做,以便在字段为空时单击“提交”按钮时应显示一条错误消息,告诉用户填写它。但是,不会显示任何错误消息。
我想在表单下方的段落中而不是通过警报显示错误消息。
我已经使用简单的alert(variableName)检查了这些变量是否确实保存了正确的信息,但是我无法使用Alert或.innerHTML来显示错误
虽然,但我无法获得下拉列表的值。
这是HTML:
<!-- This is for the name -->
<p>Name:
<input type="text" name="textfield">
</p>
<!-- This is for the email -->
<p align="left" class="style3">E-mail:
<input type="text" name="textfield">
</p>
<!-- This is for the type of bird -->
<p align="left" class="style3">Bird:
<select name="select" size="1">
<option>Rainbow Lorikeet</option>
<option>Golden Pheasant</option>
<option selected>Hoopoe</option>
<option>Bird of Paradise</option>
<option>Kingfisher</option>
<option>Peacock</option>
<option>Other</option>
</select>
<input type="text" name="textfield">
</p>
<!-- This is for location of bird -->
<p align="left" class="style3">Location:
<input type="text" name="textfield"></p>
<p align="left" class="style3">You must agree to us contacting you to find out about your sighting. Please tick this box to agree to this statement:
<input type="checkbox" name="checkbox" value="checkbox">
</p>
<p align="left" class="style3">
<input onclick='checking()' type="submit" name="Submit" value="Submit">
</p>
<p id='output'></p>
这是JavaScript:
function checking() {
var name = document.getElementsByName('textfield')[0]
var email = document.getElementsByName('textfield')[1]
var otherBird = document.getElementsByName('textfield')[2]
var location = document.getElementsByName('textfield')[3]
var birdSelect = document.getElementsByName('select')[0]
var bird = birdSelect.options[birdSelect.selectedIndex]
if (name.value===null){
document.getElementById('output').innerHTML = 'Please enter your name'
return false
} else if (email.value===null) {
document.getElementById('output').innerHTML = 'Please enter your email'
return false
} else if (location.value===null) {
document.getElementById('output').innerHTML = 'Please enter the location of the bird'
return false
} else if (otherBird.value===null && bird.text==='Other') {
document.getElementById('output').innerHTML = "Please enter a bird's name"
return false
} else {
return true
}
}
在以下情况下应显示错误消息:
如果您需要澄清一些内容,我很乐意这样做。
预先谢谢你
答案 0 :(得分:0)
您需要检查空字符串的值,如下所示:
function check() {
// clear output
document.getElementById('output').innerHTML = ''
// check for null OR empty string
var name = document.getElementsByName('textfield')[0]
if (name.value === null || name.value === '') {
document.getElementById('output').innerHTML = 'Please enter your name'
return false
}
}
<div>
Name: <input type="text" name="textfield">
<input type="button" onclick="check()" value="Check">
</div>
Output:
<p id='output'></p>
也许您甚至可以省略null
比较,但无论如何我还是把它留了下来。