How can I get each selected checkbox and put it inside an input?

4

I have some checkboxes and I want you to click on a button, all the names of those selected, go to an input separated by ",".

I tried to do this, but it did not work:

<input type="checkbox" name="cbx-1">
<input type="checkbox" name="cbx-2">
<input type="checkbox" name="cbx-3">

<input type="text" id="text">

<button type="button" id="bt-ok">Ok</button>

<script type="text/javascript">
$('#bt-ok').click(function() {
    $("input:checkbox[name=type]:checked").each(function(){
        $("#text").val($(this).val());
    });
});
</script>

Example on Jsfiddle .

Where am I going wrong?

    
asked by anonymous 16.01.2018 / 18:16

3 answers

5

Taking advantage of what you were doing, you can do the following:

var vals;
$('#bt-ok').click(function() {
    vals = [];
    $("input[type='checkbox']:checked").each(function(){
        vals.push($(this).prop('name'));
    });
    $("#text").val(vals.join(', '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox" name="cbx-1">
<input type="checkbox" name="cbx-2">
<input type="checkbox" name="cbx-3">

<input type="text" id="text">

<button type="button" id="bt-ok">Ok</button>
    
16.01.2018 / 18:26
1
$('#bt-ok').click(function() {
  $("#text").val('');
  $("input:checkbox:checked").each(function(){
    //cbx_selecionados.push($(this).val());
    $("#text").val($("#text").val() + $(this).attr('name') + ', ');
  });
});
    
16.01.2018 / 18:27
0

I did not realize what content you want by but your select "[name = type]" does not make any sense. I think this is your goal!

$('#bt-ok').click(function() {
    var temp;
    $("input:checkbox:checked").each(function(){
        //cbx_selecionados.push($(this).val());
    console.log(this);
    temp +=$(this).val()+",";

    });
    temp = temp.slice(0, -1);
    $("#text").val(temp);
});
    
16.01.2018 / 18:28