dynamically creating select elements and populating options from sharepoint list

限于喜欢 提交于 2020-01-14 03:13:36

问题


The code I wrote works, but it could be better. I am writing out the same function three times, one for each of the combo box elements. I am stuck on how to make this more efficient. I have looked at creating an object and putting each of the variables in an array, but I was not able to successfully get it working.

    var csCategory = <%=csCategoryArray%>,
        csKeyword = <%=csKeywordArray%>,
        csEntity = <%=csEntityArray%>;

 addOption = function (selectbox, text, value) {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

$(function () {
    // Temp test stuff to populate option list
    var selectObj = document.getElementById("combobox1")
    if (selectObj) {
        for (var i=0; i < csCategory.length;++i){    
            addOption(selectObj, csCategory[i], csCategory[i]);
        }
    }
}); 

$(function () {
    // Temp test stuff to populate option list
    var selectObj = document.getElementById("combobox2")
    if (selectObj) {
        for (var i=0; i < csKeyword.length;++i){    
            addOption(selectObj, csKeyword[i], csKeyword[i]);
        }
    }
});  

$(function () {
    // Temp test stuff to populate option list
    var selectObj = document.getElementById("combobox3")
    if (selectObj) {
        for (var i=0; i < csEntity.length;++i){    
            addOption(selectObj, csEntity[i], csEntity[i]);
        }
    }
});

回答1:


The obvious first step is to refactor out the shared code. So:

$(function () {
  // Temp test stuff to populate option list
  var selectObj = document.getElementById("combobox2")
  if (selectObj) {
    for (var i=0; i < csKeyword.length;++i){    
        addOption(selectObj, csKeyword[i], csKeyword[i]);
    }
  }
});  

( ... etc ... )

becomes:

function populate(id, collection) {
  var selectObj = document.getElementById(id)
  if (selectObj) {
    for (var i=0; i < collection.length;++i){    
        addOption(selectObj, collection[i], collection[i]);
    }
  }
}

$(function () {
  populate ("combobox1", csCategory);
  populate ("combobox2", csKeyword);
  populate ("combobox3", csEntity);
});

I can't see any significant advantage at this stage of putting combobox1 and its siblings into an array, but it may be worthwhile revisiting this code if more comboboxes are added in the future.



来源:https://stackoverflow.com/questions/18645896/dynamically-creating-select-elements-and-populating-options-from-sharepoint-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!