我有一个带有 <select>
的表单,有两个选项和一个 <input>
. 默认情况下, <input>
不需要提交表单 . 当 <select>
中的所选选项的值为 pizza
时,我想将 required
属性添加到 <input>
. 如果用户切换到另一个 <select>
选项,我也希望将其删除 .
$(function() {
var paymentType = $("#paymentType option:selected").val();
if (paymentType == 'pizza') {
$("firstName").prop('required', true);
} else {
$("firstName").prop('required', false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="paymentType" name="paymentType" required>
<option value="" hidden>Select Payment Type</option>
<option value="pizza">Pizza</option>
<option value="highFive">High Five</option>
</select>
<input type="text" id="firstName" name="firstName" placeholder="First Name">
<input type="submit">
</form>
1 回答
你需要给
select
一个change
处理程序,并使用正确的选择器firstName
(在前面放#
来选择id
):