我有一个包含 3 个输入(2 个文本和一个下拉选择)的搜索表单,并且我制作了一个 jQuery 预验证代码,除非在这些输入上键入内容,否则禁用提交按钮。代码如下所示:
// Search button is disabled until something is typed.
$(document).ready(function () {
$('input[type="submit"]').prop('disabled', true);
$('input[type="text"]').keyup(function () {
if ($(this).val() != '') {
$(':input[type="submit"]').prop('disabled', false);
} else {
$(':input[type="submit"]').prop('disabled', true);
}
});
$('#dropdown').on("change", function () {
if ($(this).val() == '') {
$(':input[type="submit"]').prop('disabled', true);
} else {
$(':input[type="submit"]').prop('disabled', false);
}
});
});
该代码在网络/桌面上完美运行。然后,我想为移动设备个性化页面,所以我将与这 3 个输入完全相同的表单添加到 d-block d-sm-none
Bootstrap 4 类中 - div 将是仅在用户使用移动设备时显示。
代码在移动设备上响应,它在前两个输入(文本输入)上完成其工作,但下拉选择不起作用。即使我从列表中选择了某些内容,该按钮仍处于禁用状态。
下拉代码在两个版本(桌面和移动)中都是这样的:
<select class="custom-select" name="status" id="dropdown">
<option selected="selected" value="">Find by status</option>
@foreach($status as $sts)
<option value="{{$sts->id}}">{{$sts->name}}</option>
@endforeach
</select>
有什么想法吗?谢谢!
最佳答案
您需要使用 class 而不是 id 来选择下拉列表:
$(document).ready(function () {
$('input[type="submit"]').prop('disabled', true);
$('input[type="text"]').keyup(function () {
if ($(this).val() != '') {
$(':input[type="submit"]').prop('disabled', false);
} else {
$(':input[type="submit"]').prop('disabled', true);
}
});
$('.custom-select').on("change", function () {
if ($(this).val() == '') {
$(':input[type="submit"]').prop('disabled', true);
} else {
$(':input[type="submit"]').prop('disabled', false);
}
});
});
当您使用 $('#dropdown')
时,您的代码将仅应用于 DOM 中的第一个 Select
关于jquery - 禁用/启用提交按钮不适用于移动类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56644718/