【问题标题】:how to change the value of a text box according to checkboxes如何根据复选框更改文本框的值
【发布时间】:2016-12-25 20:49:44
【问题描述】:

我根据选中的文本框中的文本更改了 5 个复选框。但是可以同时选中所有复选框。我希望一次只选中一个复选框。

$(".check").change(function(){
        var text = "";
        $(".check:checked").each(function(){ 
            text += text != "" ? "^" : "";
            if ($(this).prop("checked"))
                text += $(this).val();
        });
        $(".text").val(text);
    });


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="checkbox" class="check" value="Text1" />
    <input type="checkbox" class="check" value="Text2" />
    <input type="checkbox" class="check" value="Text3" />
    <input type="checkbox" class="check" value="Text4" />
    <input type="checkbox" class="check" value="Text5" />
    <br/>
    <input type="text" class="text" />

【问题讨论】:

  • 如果您只想一次检查一个,为什么要使用复选框而不是单选按钮?
  • 我只想要复选框
  • 最简单的方法是使用单选按钮...您尝试使复杂的事情变得容易完成。顺便说一句,这行得通吗?
  • 我之前没有使用单选按钮..请指导是的,这是按规定工作的
  • 如果您坚持它们是复选框,那么只需将复选框更改为收音机并格式化收音机,使其显示为复选框:stackoverflow.com/a/8079482/1033684

标签: jquery checkbox


【解决方案1】:

我不是 JS 专家,所以我愿意接受建议、编辑、评论、澄清......

这个想法是禁用其他复选框并将所选值附加到文本框。

var text = "";
// text += text != "" ? "^" : "";
$('.check').click(function() {
    var $inputs = $('.check');
    if ($(this).is(':checked')) {
        $inputs.not(this).prop('disabled', true);
        if ($(this).prop("checked")) {
            if (text !== "") {
                text += "^";
            }
            text += $(this).val();
            $(".text").val(text);
        }
    } else {
        $inputs.prop('disabled', false);
    }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="check" value="Text1" />
<input type="checkbox" class="check" value="Text2" />
<input type="checkbox" class="check" value="Text3" />
<input type="checkbox" class="check" value="Text4" />
<input type="checkbox" class="check" value="Text5" />
<br/>
<input type="text" class="text" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多