Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two checkboxes and a div in the body and I would like to display the selected value of data-valuetwo inside the div, "contents".

$(document).ready(function() {
    $('.chkbx').click(function() {
        var selected = "";
        $('.chkbx:checked').each(function() {
            selected += $('.chkbx').attr('data-valuetwo') + ',';
        });
        selected = selected.substring(0, selected.length - 1);
        $('.selecteditems').val(selected);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input chkbx" value="654321" data-valuetwo="Mike" id="customCheck1" name="choice[]">
    <label class="custom-control-label" for="customCheck1">Mike</label>
</div>

<div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input chkbx" value="654321" data-valuetwo="Jason" id="customCheck2" name="choice[]">
    <label class="custom-control-label" for="customCheck2">Jason</label>
</div>

<div class="contents">
    <h3>Options Selected: </h3>
    <textarea id="selecteditems">
    </textarea>
</div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have two issues in your code:

1) You have to use this keyword to target the current check box and

2) You are using class symbol (.) instead of id (#);

$(document).ready(function() {
    $('.chkbx').click(function() {
        var selected = "";
        $('.chkbx:checked').each(function() {
            selected += $(this).attr('data-valuetwo') + ',';
        });
        selected = selected.substring(0, selected.length - 1);
        $('#selecteditems').val(selected);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input chkbx" value="654321" data-valuetwo="Mike" id="customCheck1" name="choice[]">
    <label class="custom-control-label" for="customCheck1">Mike</label>
</div>

<div class="custom-control custom-checkbox">
    <input type="checkbox" class="custom-control-input chkbx" value="654321" data-valuetwo="Jason" id="customCheck2" name="choice[]">
    <label class="custom-control-label" for="customCheck2">Jason</label>
</div>

<div class="contents">
    <h3>Options Selected: </h3>
    <textarea id="selecteditems">
    </textarea>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...