将值放在具有相同类别的输入框中,分别来自已选中的复选框

时间:2017-08-23 01:36:21

标签: javascript jquery html checkbox

如何将已选中复选框的值放入类不相同的输入框中。现在,checked复选框的值可以是具有相同类的所有输入框的值。我需要根据第一个选中的复选框在输入框中输入值。

例如:

我有七个复选框,我检查第二个复选框,然后它的值将在第一个输入框中,然后当我选中另一个复选框时,它的值将被放入具有相同类的下一个输入框中,依此类推。

JSFIDDLE:https://jsfiddle.net/aice09/nwqpkr0h/

var senate = $('.senators');
    var limit = 3;
    $('input.single-checkbox').on('change', function (evt) {
        if ($(this).siblings(':checked').length >= limit) {
            this.checked = false;
        }
        senate.val(getSelectedSenators());
    });

    function getSelectedSenators() {
        var senators = "";
        $('input[type="checkbox"]').each(function (i, cb) {
            if ($(this).is(":checked")) {
                senators += $(this).val() + " ";
            }
        });
        return senators;
    }
 <!--JQUERY-->
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
    <!--Bootstrap 3.3.7-->
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <div class="col-lg-8">  
     <div class="pricing-levels-3">
        <p><strong>CHECK BOXES(LIMIT 3)</strong></p>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Senator 1">Senator 1<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Senator 2">Senator 2<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Senator 3">Senator 3<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Senator 4">Senator 4<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Senator 5">Senator 5<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Senator 6">Senator 6<br>
        <input class="single-checkbox" type="checkbox" name="vehicle" value="Senator 7">Senator 7<br>
    </div>
    </div>
    <div class="col-lg-4">
    <br>

    <input class="senators" id="senators" placeholder="SENATORS" />
    <input class="senators" id="senators1" placeholder="SENATORS" />
    <input class="senators" id="senators2" placeholder="SENATORS" />
 </div>
    

1 个答案:

答案 0 :(得分:2)

您必须根据所选索引单独设置每个输入,如下所示:

@Configuration
var senate$ = $('.senators');
var limit = senate$.length;
$('input.single-checkbox').on('change', function (evt) {
    var index = $(this).siblings(':checked').length;
    var value = $(this).val();
    if (index >= limit) {
       this.checked = false;
    } else {
       $(senate$[index]).val(this.checked ? value : null);
    }
});