Put checkbox values into hidden input with jQuery

前端 未结 2 1590
执念已碎
执念已碎 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: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

      
      
      
      
    

    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

提交回复
热议问题