Implode Form Element Array


/ Published in: JavaScript
Save to your folder(s)

I frequently pass an array of elements from an HTML form to PHP, normally a list of checkboxes for removing database records. This will loop through an array of checkbox's with the same name & build a delimited string from the checked values. After I have the values in a delimited string I normally have a hidden field which holds the string & explode it on the PHP side.


Copy this code and paste it in your HTML
  1. // implodeFormArray(form name : String, form element name : String, delimiter : String);
  2. function implodeFormArray(f, e, del) {
  3. var form = document.forms[f];
  4. if (typeof(form.elements[e].value) != "undefined") {
  5. if (form.elements[e].checked) return form.elements[e].value;
  6. else return '';
  7. } else {
  8. var output = '';
  9. var len = form.elements[e].length;
  10. for(var i=0;i<len;i++) {
  11. if (form.elements[e][i].checked) {
  12. output+= (output == '' ? '':del) + form.elements[e][i].value;
  13. }
  14. }
  15. return output;
  16. }
  17. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.