在Web开发中,有时需要根据用户操作动态禁用或启用表单中的其他输入框。jQuery提供了简单的方法来实现这一功能。
$('input[type="text"]').not(this).prop('disabled', true);
$(this).siblings('input[type="text"]').prop('disabled', true);
$('.text-input').not(this).prop('disabled', true);
<!DOCTYPE html>
<html>
<head>
<title>禁用其他文本框示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="input-group">
<input type="text" class="text-input" placeholder="输入框1">
<input type="text" class="text-input" placeholder="输入框2">
<input type="text" class="text-input" placeholder="输入框3">
</div>
<script>
$(document).ready(function() {
$('.text-input').on('focus', function() {
// 禁用同组中其他文本框
$('.text-input').not(this).prop('disabled', true);
});
$('.text-input').on('blur', function() {
// 重新启用所有文本框
$('.text-input').prop('disabled', false);
});
});
</script>
</body>
</html>
prop()
方法比attr()
更适合用于设置disabled属性如果需要更灵活的控制,可以考虑使用readonly
属性而不是disabled
:
$('input[type="text"]').not(this).prop('readonly', true);
这样文本框看起来是可编辑的,但用户无法修改内容。
没有搜到相关的文章