gpt4 book ai didi

javascript - 选择选项后无法使用 jQuery 禁用输入元素

转载 作者:行者123 更新时间:2023-11-28 16:46:47 25 4
gpt4 key购买 nike

我为此使用了jquery 3.4.1我试图在选择不同的值时禁用输入元素。

$(document).ready(function() {
$('form input[name="spouseName"]').prop("disabled", true);
$('form input[name="children"]').prop("disabled", true);
$("form select option [value='married']").change(function() {
$('form input[name="spouseName"]').prop("disabled", false);
$('form input[name="children"]').prop("disabled", false);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<form>
<select class="form-control" name="maritalStatus" id="maritalStatus">
<option value="Married">Married</option>
<option selected value="UnMarried">UnMarried</option>
<option value="Male Widow">Male Widow</option>
<option value="FeMale Widow">FeMale Widow</option>
<option value="Divorcee">Divorcee</option>
</select>
<input type="text" class="form-control" name="spouseName" id="spouseName" aria-describedby="spName" placeholder="Spose Name">
<input type="text" class="form-control" name="children" id="children" aria-describedby="childrens" placeholder="Children">
</form>

最佳答案

在发生change事件时,您应该检查所选选项的值。另外,要删除该属性,您可以使用 .removeAttr() .

尝试以下方法:

$(document).ready(function(){
$('form input[name="spouseName"]').prop("disabled", true);
$('form input[name="children"]').prop("disabled", true);

$("form select").change(function(){
if($(this).val() == 'Married'){
$('form input[name="spouseName"]').removeAttr("disabled")
$('form input[name="children"]').removeAttr("disabled")
}
else{
$('form input[name="spouseName"]').prop("disabled", true);
$('form input[name="children"]').prop("disabled", true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<select class="form-control" name="maritalStatus" id="maritalStatus">
<option value="Married">Married</option>
<option selected value="UnMarried">UnMarried</option>
<option value="Male Widow">Male Widow</option>
<option value="FeMale Widow">FeMale Widow</option>
<option value="Divorcee">Divorcee</option>
</select>
<input type="text" class="form-control" name="spouseName" id="spouseName" aria-describedby="spName" placeholder="Spose Name">
<input type="text" class="form-control" name="children" id="children" aria-describedby="childrens" placeholder="Children">
</form>

关于javascript - 选择选项后无法使用 jQuery 禁用输入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60463764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com