RScott RScott - 7 days ago 5
Javascript Question

Creating a select class dynamically

I'm struggling with modifying some code I have that dynamically creates a select box based on column values from a sharepoint list.

at the moment the code:

function getAjaxFilter(name, internalName) {
$.ajax({
url: $().SPServices.SPGetCurrentSite() + '/_layouts/filter.aspx?ListId=' + listID + '&FieldInternalName=' + internalName + '&ViewId=' + viewID + '&FilterOnly=1&Filter=1' + filterFieldsParams,
success: function(data) {

$('#filterField' + internalName).html(name).append($("<div></div>").append(data).find("select"));
//clear current onChange event
$("#diidFilter" + internalName).attr("onchange", '');
// add change event
$("#diidFilter" + internalName).change(function() {
FilterField(viewID, internalName, encodeURIComponent(this.options[this.selectedIndex].value), this.selectedIndex);
});
}


Creates the following html:

<div id="filterFieldSub_Category">
Sub Category
<select title="Filter by Sub_Category" id="diidFilterSub_Category">
<option>(All)</option>
<option>(Empty)</option>
<option value="Test">Test</option>
</select>




What I'm trying to achieve is to get it to produce a select class so I can apply it to a 3rd party selectbox styler like bootstrap select. so It needs to look like:

<select class="selectpicker" id= "filterFieldSub_Category">
<option>(all)</option>
<option>(empty)</option>
<option>test</option>
</select>


I'm not sure where to start, so if anyone could point me in the right direction that would be a huge help :)

Answer

You could add the class using addClass() :

$("#diidFilter" + internalName).addClass('selectpicker');

Hope this helps.

Comments