我是一个完整的菜鸟,对所有内容都很新,基本上按照教程来理解,我正在使用jQuery Form Plugin
我正在尝试制作一个选择“联系人类型”的表单,如果选择“电话”选项,则需要“联系时间”,但如果选择“电子邮件”,那么它会使“联系时间”不是必需的。
*表格html。 *
<form id="askquestion" action="questionprocess.php" method="post">
<td><label for="response type">Method of contact:</label></td>
<td><select name="response_type">
<option value="" selected="selected">-- Please select --</option>
<option value="Phone">Phone</option>
<option value="Email">Email</option>
</select></td>
</tr>
<td><label for="response time">Best time to contact:</label></td>
<td><select name="contact_time">
<option value="" selected="selected">-- Please select --</option>
<option value="morning_noon">Morning to Noon</option>
<option value="noon_afternoon">Noon to afternoon</option>
<option value="evenings">Evenings</option>
</select></td>
</tr>
</form>
jQuery规则:
$(function() {
// Validate the contact form
$('#askquestion').validate({
// Specify what the errors should look like
// when they are dynamically added to the form
errorElement: "label",
wrapper: "td",
errorPlacement: function(error, element) {
error.insertBefore( element.parent().parent() );
error.wrap("<tr class='error'></tr>");
$("<td></td>").insertBefore(error);
},
// Add requirements to each of the fields
rules: {
response_type: {
required:true,
},
contact_time: {
required:true,
},
更新。这是验证表单的结束方式。
// Use Ajax to send everything to form processing file
submitHandler: function(form) {
$("#send").attr("value", "Sending...");
$(form).ajaxSubmit({
success: function(responseText, statusText, xhr, $form) {
$(form).slideUp("fast");
$("#response").html(responseText).hide().slideDown("fast");
}
});
return false;
}
});
});
答案 0 :(得分:7)
rules: {
response_type: {
required: true,
contact_time: {
depends: function () {
return $('#askquestion select[name="response_type"]').val() === 'Phone';
}
}
},
它在文档中:http://docs.jquery.com/Plugins/Validation/validate#code