开发者

Need to take the values from slected checkboxes an place into an input file, separated by commas

开发者 https://www.devze.com 2023-01-12 01:12 出处:网络
I\'m trying to take a series of selected checkboxes and create a comma separated list inside an input field. This is a bit beyond my jQuery skills.

I'm trying to take a series of selected checkboxes and create a comma separated list inside an input field. This is a bit beyond my jQuery skills.

Here is a sample of the HTML:

<input type="checkbox" value="Bill" id="CAT_Custom_173676_0" name="CAT_Custom_173676" />Bill<br />
<input type="checkbox" value="Dan" id="CAT_Custom_173676_1" name="CAT_Custom_173676" />Dan<br />
<input t开发者_StackOverflow社区ype="checkbox" value="Francis" id="CAT_Custom_173676_2" name="CAT_Custom_173676" />Francis<br />

I need to take the values from these checkboxes and insert them into this field

<input type="text" class="cat_textbox" id="CAT_Custom_172786" name="CAT_Custom_172786" maxlength="1024"  />

So, if all the checkboxes above are checked, the value of the input field would be "Bill,Dan,Francis".

This event can happen when the form is submitted.

Any help would be appreciated.


You can use map() here to create a new jQuery object containing the values of checked checkboxes, then use get() to obtain an array, then use join(",")nb to create a comma-separated string of those values:

var arr = ​$("input:checked").map(function () { return this.value; }​);
$("#CAT_Custom_172786").val(arr.get().join(","));

Example

nb: you can actually omit join(), because an array converted to a string is automatically joined with comma separation. Personal preference comes into play here.


Also this will return all selected checkboxes that have the name "CAT_Custom_173676"

alert($("input[name=CAT_Custom_173676]:checked").map(function () {
return this.value;}).get().join(","));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号