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

Asked

Viewed 324 times

4

I have some checkbox and I want, when clicking a button, all the names of these selected, to go to an input separated by ",".

I tried to do it this way, but it didn’t 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 in Jsfiddle.

Where am I going wrong?

3 answers

5


Taking advantage of what you were doing, here’s what you can do:

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>
<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>

  • 1

    Perfect @Miguel. Just one question, why it could not be stated var vals = [];? It would be for some good programming practice?

  • 1

    @jsnow because we want to delegate an empty array to each btn click, otherwise it would be buggy if you clicked more than once: https://jsfiddle.net/4xafkufd/, if we don’t declare the empty variable will continue to be populated, then it doesn’t make sense

  • 1

    Got it. Thank you very much!

1

$('#bt-ok').click(function() {
  $("#text").val('');
  $("input:checkbox:checked").each(function(){
    //cbx_selecionados.push($(this).val());
    $("#text").val($("#text").val() + $(this).attr('name') + ', ');
  });
});
  • Thanks, it worked too. But just one detail: when you only have a checkbox marked, it adds the comma, too.

  • It was just an example, it would improve now with more time, but the @Miguel answer clarifies better.

0

I didn’t realize what content you wanted by but your select "[name=type]" doesn’t 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);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.