Array to SELECT


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

This function automates the creation of the s of a element. It's ideal for your AJAX apps when you create display elements using Javascript

It accepts to different kind of arrays:

An array of key:values…

var arrDirs = {
"a1":"Sede central",
"a2":"Envíos",
"a4":"Facturación",
"b1":"Sucursal"
};


An array of arrays, where each of the child arrays have the sintax 'ID': value, 'LABEL': text…

var arrDirs = {
"0":{"ID":"a1","LABEL":"Sede central"},
"1":{"ID":"a2","LABEL":"Envíos"},
"2":{"ID":"a4","LABEL":"Facturación"},
"3":{"ID":"b1","LABEL":"Sucursal"}
};

Note that the ID part can be a number or an string.


Copy this code and paste it in your HTML
  1. /**
  2.  
  3.   @param objSelect an object returned by document.getElementById('myselect') or your favourite library function.
  4.   @param arrDatos is an array or an array of arrays.
  5.   @param numCurOption is the key of the option we need to be SELECTED.
  6.   @param boolEmpty should be true if we need a first element without value and label.
  7. */
  8. function array2select(objSelect, arrDatos, numCurOption, boolEmpty) {
  9. var elOptNew;
  10. objSelect.length = 0;
  11. if(boolEmpty) {
  12. elOptNew = document.createElement('option');
  13. elOptNew.value = elOptNew.text = '';
  14. addOption(objSelect, elOptNew);
  15. }
  16. for(var id in arrDatos) {
  17. if(typeof(arrDatos[id]) == 'object') {
  18. var arrResultado = arrDatos[id];
  19. var strValue = arrResultado.ID;
  20. var strText = arrResultado.LABEL;
  21. } else {
  22. var strValue = id;
  23. var strText = arrDatos[id];
  24. }
  25. elOptNew = document.createElement('option');
  26. if(numCurOption == strValue) {
  27. elOptNew.selected = true;
  28. }
  29. elOptNew.value = strValue;
  30. elOptNew.text = strText;
  31. addOption(objSelect, elOptNew);
  32. }
  33. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.