我的所有内容都在我的表单上工作,除了验证已经选择了选择菜单中的选项..它显示错误但是一旦选择了某些内容就不会消失
html
<div id="budget_input">
<label for="budget">Budget</label>
<select name="mydropdown">
<option value="" id="mydropdown"> -- choose one --</option>
<option value="firstchoice">$0 - $1,000</option>
<option value="secondchoice">$1,000 - $2,000</option>
<option value="thirdchoice">$3,000 +</option>
</select>
</div>
PHP
$name = trim(stripslashes(htmlspecialchars($_POST['name'])));
$email = trim(stripslashes(htmlspecialchars($_POST['email'])));
$mydropdown = trim(stripslashes(htmlspecialchars($_POST['mydropdown'])));
$error_message = '';
$reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,4}$/";
if (!preg_match($reg_exp, $email)) {
$error_message .= "<p>A valid email address is required.</p>";
}
if (empty($name)) {
$error_message .= "<p>Please provide your name.</p>";
}
if (empty($mydropdown)) {
$error_message .= "<p>Please select an item from the list.</p>";
}
js部分显示为客户端
var valid = '';
var required = ' is required.';
var name = $('form #name').val();
var email = $('form #email').val();
var mydropdown = $('form #mydropdown').val();
if (name == '' || name.length <= 2) {
valid = '<p>Your name' + required +'</p>';
}
if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>Your email' + required +'</p>';
}
if (mydropdown == '') {
valid += '<p>An item from the list' + required +'</p>';
}
答案 0 :(得分:2)
请用这个代码替换你的代码希望它能够正常工作。
<div id="budget_input">
<label for="budget">Budget</label>
<select name="mydropdown" id="mydropdown">
<option value="" > -- choose one --</option>
<option value="firstchoice">$0 - $1,000</option>
<option value="secondchoice">$1,000 - $2,000</option>
<option value="thirdchoice">$3,000 +</option>
</select>
</div>
答案 1 :(得分:2)
更改您的MARKUP
<div id="budget_input">
<label for="budget">Budget</label>
<select id="mydropdown">
<option value=""> -- choose one --</option>
<option value="firstchoice">$0 - $1,000</option>
<option value="secondchoice">$1,000 - $2,000</option>
<option value="thirdchoice">$3,000 +</option>
</select>
</div>
更改您的JS代码
var valid = '';
var required = ' is required.';
var name = $('form #name').val();
var email = $('form #email').val();
var mydropdown = $('form #mydropdown').val();
if (name == '' || name.length <= 2) {
valid = '<p>Your name' + required +'</p>';
}
if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<p>Your email' + required +'</p>';
}
if (mydropdown == '') {
valid += '<p>An item from the list' + required +'</p>';
}
只需添加您的选择框ID,因为它用于检查Jquery是否选择了任何项目。
编辑#1 - 添加屏幕截图
答案 2 :(得分:1)
您可能需要使用id = mydropdown才能使js验证正常工作
<select id="mydropdown">
现在您只需在选择框中设置name="mydropdown"