html - How can I use jQuery to create a csv of all checked checkboxes associated text? -
i got of way need answer question here: how can value of labels associated checkboxes (and did break jsfiddle)?
...but have related question, namely, "how can use jquery create csv of checked checkboxes associated text?"
what i've got far, missing piece commented, here: js fiddler link
the html is:
<button id="btndept">select depts</button> <div id="dialog" title="select depts want include in report" style="display:none;"> <div> <section class="breakafter"> <label for="ckbxselectall">select all</label> <input type="checkbox" id="ckbxselectall" /> <label for="ckbxdeselectall">deselect all</label> <input type="checkbox" id="ckbxdeselectall" /> </section> <label for="ckbx2">2</label> <input type="checkbox" id="ckbx2" /> <label for="ckbx3" id="lbl3">3</label> <input type="checkbox" id="ckbx3" /> </div> </div>
the css is:
.breakafter { display:block; }
the jquery is:
var deptsselected = ''; $("#btndept").click(function () { $("#dialog").dialog({ modal: true }); $("input:checkbox").click(function () { var checkedval = $("label[for='" + this.id + "']").text(); if (checkedval == "select all") { $(":checkbox").prop("checked", true); $("#ckbxdeselectall").prop("checked", false); // how can add of vals deptsselected (except "select all" , "deselect all")? } else if (checkedval == "deselect all") { $(":checkbox").prop("checked", false); $("#ckbxdeselectall").prop("checked", true); deptsselected = ''; } else { if (deptsselected.indexof(checkedval) < 0) { deptsselected += $("label[for='" + this.id + "']").text() + ','; } } alert(deptsselected); }); });
iow, need loop through, think, label elements, appending text value , comma (and lop final comma off end).
update
i updated jsfiddle include checkboxes need:
i created rest of checkboxes in c# utility:
private void button1_click(object sender, eventargs e) { string s = string.empty; (int = 4; < 100; i++) { s += string.format("<label for=\"ckbx{0}\">{0}</label><input type=\"checkbox\" id=\"ckbx{0}\" />", i); } textbox1.appendtext(s); }
you can use join
function generate csv
map
of checked checkboxes excluding 'select all' checkbox
.
following can do:
deptsselected = $.map($(':checkbox:not(#' + this.id + '):checked'), function(elem, index) { return $("label[for='" + elem.id + "']").text(); }).join(',');
and here fiddle shows this: http://jsfiddle.net/bakyh/
here documentation 2 new functions i've used:
map()
: http://api.jquery.com/jquery.map/
join()
: https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/join
Comments
Post a Comment