首页 > 解决方案 > 在 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>

标签: javascriptjqueryhtml

解决方案


给你的标记,实际上不需要添加任何类或使用 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');
        }
    });
});

而且,老实说,通过更好地了解您的项目范围,可能可以编写更高效、可重用的脚本片段。


推荐阅读