Put checkbox values into hidden input with jQuery

前端 未结 2 1572
执念已碎
执念已碎 2021-01-14 23:08

I\'d like to populate a hidden input with the values of selected checkboxes with a space between these values. I\'ve tried the following which in theory should work but it i

相关标签:
2条回答
  • 2021-01-14 23:33

    You just need to change your selector and attach your script to some event. For example:

    $('input[type=checkbox]').change(function() {
    
        var vals = $('input[type=checkbox]:checked').map(function() {
            return $(this).val();
        }).get().join(',');
    
        $('#tags').val(vals);
    
    });​
    

    See this DEMO.

    0 讨论(0)
  • 2021-01-14 23:34

    :checkbox is deprecated

    Instead of

    $(':checkbox:checked')
    

    Use

    $('input[type="checkbox"]:checked')
    

    Also none of the checkboxes are checked when the document is Ready .. Set them first and then try ...

    HTML

      <input type="checkbox" value="test1" id="test1" checked><label>Test</label>
      <input type="checkbox" value="test2" id="test2" checked><label>Test2</label>
      <input type="checkbox" value="test3" id="test3"><label>Test3</label>
      <input type="text" value="" id="tags">
    

    Javascript

    function Populate(){
        vals = $('input[type="checkbox"]:checked').map(function() {
            return this.value;
        }).get().join(',');
        console.log(vals);
        $('#tags').val(vals);
    }
    
    $('input[type="checkbox"]').on('change', function() {
        Populate()
    }).change();
    

    Check Fiddle

    0 讨论(0)
提交回复
热议问题