javascript - 在 input type=radio 检查时,添加一个类到 input=text
问题描述
如何链接单选按钮和填充的文本输入,以便在选择单选时,输入文本区域中的文本也将更改为可以说...红色粗体?
我知道逻辑是:
选中 radio-A 和 input-text-A 时,将 CSS 类添加到 input-text-A。未选中时删除类。如果选择了 radio-B,则更改 input-text-B,依此类推...
但是现在这个简单的脚本针对所有的文本输入。
$('input[type=text]').addClass('red');
.red {
color: red;
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-inline">
<label class="" for="">
<input class="" type="radio" name="answer-Q1" value="option1"> A. </label>
<input type="text" name="answers" class="" placeholder="" required>
</div>
<br>
<div class="form-inline">
<label class="">
<input class="" type="radio" name="answer-Q2" value="option1"> B. </label>
<input type="text" name="answers" class="" placeholder="" required>
</div>
解决方案
给你的标记,实际上不需要添加任何类或使用 javascript,你可以用纯 CSS 做你想做的事:
input[type="radio"]:checked + input[type="text"] {
color: red;
font-weight: bold;
}
至于如何使用 jQuery 添加类,我倾向于编写“健壮”的解决方案,这些解决方案可能会更长一些,但不会那么“脆弱”(意思是:如果标记发生了一点变化,脚本仍然可以工作)。我写这个的方式 - 假设无法控制标记 - 将使用 jQuery 的最接近并找到来定位目标文本输入:
// no-conflict-save document ready shorthand
jQuery(function($) {
// bind to the "change" event of all inputs that are radio buttons
jQuery('input[type="radio"]').on('change', function() {
// find the text input
var $text_input = $(this).closest('div').find('input[type="text"]');
// if there isn't one, get out
if ( ! $text_input.length ) {
return;
}
// if the radio button is checked, add the class
if ($(this).is(':checked')) {
$text_input.addClass('red');
} else {
// otherwise, remove the class
$text_input.removeClass('red');
}
});
});
但是,如果我确实可以控制标记,我会向无线电输入元素添加一个类,并使用它来使脚本更“一般”有用,并缩小绑定输入的范围(将允许相同的脚本在复选框+文本输入上有效地工作):
// no-conflict-save document ready shorthand
jQuery(function($) {
// bind to the "change" event of any inputs with the "watch-change" class
jQuery('input.watch-change]').on('change', function() {
// find the text input. Note, this would find multiple text inputs if they existed.
var $text_input = $(this).closest('div').find('input[type="text"]');
// if there isn't a text input to work with, get out
if ( ! $text_input.length ) {
return;
}
// if the radio button is checked, add the class
if ($(this).is(':checked')) {
$text_input.addClass('red');
} else {
// otherwise, remove the class
$text_input.removeClass('red');
}
});
});
而且,老实说,通过更好地了解您的项目范围,可能可以编写更高效、可重用的脚本片段。
推荐阅读
- powershell - GetEventLog - 如何在一行中扩展“消息”属性
- azure-active-directory - 如何在非交互式工作流中通过浏览器对 Azure AD 进行身份验证?
- angular - ReferenceError:调用以太坊合约方法时“未定义originalStackTrace”
- android - 在后台运行的 Android 应用不需要 Activity
- instagram - 如何从 instaloader 下载主题标签的热门帖子
- c# - 有没有办法从 gridview 列计算增值税(增值税 = 15%)?
- jmeter - 在 JMeter 中参数化源文件夹目录或文件路径
- python - 如果在 Python 中加载此文件的时间超过 X 秒,如何中断加载命令?
- c++ - Autotools:如何覆盖中间构建产品目录?
- sql-server - 传递动态视图名称和条件