use jQuery to get values of selected checkboxes

后端 未结 12 2704
旧巷少年郎
旧巷少年郎 2020-11-27 14:44

I want to loop through the checkboxgroup \'locationthemes\' and build a string with all selected values. So when checkbox 2 and 4 are selected the result would be: \"3,8\"

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 15:39

    A bit more modern way to do it:

    const selectedValues = $('input[name="locationthemes"]:checked').map( function () { 
            return $(this).val(); 
        })
        .get()
        .join(', ');
    

    We first find all the selected checkboxes with the given name, and then jQuery's map() iterates through each of them, calling the callback on it to get the value, and returning the result as a new jQuery collection that now holds the checkbox values. We then call get() on it to get an array of values, and then join() to concatenate them into a single string - which is then assigned to the constant selectedValues.

提交回复
热议问题