Creating a select class dynamically - javascript

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 :)

You could add the class using addClass() :
$("#diidFilter" + internalName).addClass('selectpicker');
Hope this helps.

Related

How to update a dropdown list dynamically using JQuery?

I have a dropdown list which is initially empty:
<div>
<label>Boarding Point </label>
<select title="Select pickup city" id="boardingDropdown">
</select>
</div>
I want to update it from the json data obtained from an API.
I can print the data obtained from API in the console, but I cannot
add it to the dropdown using jquery.
here is my jquery code
$.getJSON(busApi, function(boardingPoints) {
$.each(boardingPoints, function(index, value){
let $boardingOption = $("<option>" + value + "</option>");
$("#boardingDropdown").append($boardingOption);
});
});
The dropdown just shows undefined without any other data.
I have tried other similar questions (like this and this) but they did not solve my problem.
Could somebody tell me what am I doing wrong?
Thanks.
Edit:
console.log(value) shows the output
Kathmadnu
Birgunj
Pokhariya
Langadi Chowk
Bhiswa
Birgunj
which is the expected output from the api.
I created a list with this data
let buses=["Kathmadnu",
"Birgunj",
"Pokhariya",
"Langadi Chowk",
"Bhiswa",
"Birgunj"
];
Now the list still show undefined initially, but if I click on it, it shows the dropdown list as expected.
Does it mean there is problem with the API? But I can see the data obtained from the API in the console?
Try this solution:
$.each(items, function (i, value) {
$('#boardingDropdown').append($('<option>', {
value: value_value,
text : text_value
}));
});
The output should be something like this:
<select title="Select pickup city" id="boardingDropdown">
<option value="value_value">text_value</option>
</select>
Instead of:
let $boardingOption = $("<option>" + value + "</option>");
you should use:
let boardingOption= "<option>" + value + "</option>";
And in your code:
$(#boardingDropdown").append($boardingOption);
you missed a quote mark, it should be: $("#boardingDropdown")
Finally, according to my corrections, it should become:
$("#boardingDropdown").append(boardingOption);
Found the problem:
I had given id to the <select> tag and was adding the options to this tag.
<select title="Select pickup city" id="boardingDropdown">
</select>
Instead, what I did was to create a <div> tag above the <select> tag, and append <select>, then <option> and then </select> from the jquery.
<div>
<label>Boarding Point </label>
<div id="boardingDropdown"></div>
</div>
Then in the jquery, I appended the <select> tag as well:
$.getJSON(busApi, function (boardingPoints) {
let opt = '<select>';
$.each(boardingPoints, function (index, value){
opt += '<option value="' + index + '">' + value + '</option>';
});
opt += '</select';
$("#boardingDropdown").append(opt);
});
Now it is working as expected. :)

on change selects not working well

I`m trying to make a simple select which generate the next select box...
but I cant seem to make it work
so, as you can see I'm making divs that have ID and parent, when I'm clicking on the first select the value generate the next select box with the divs and the parent value.
this is the jQuery, but for some reason I cant understand why its not working.
$(document).ready(function() {
var i = 1;
var t = '#ss' + i;
$(t).change(function() {
i++;
t = '#ss' + i;
var pick = $(this).val();
$('#picks div').each(function() {
if ($(this).attr('parent') == pick) {
$('#ss' + i).append('<option value=' + $(this).text() + ' >' + $(this).text() + '</option>');
}
$('#ss' + i).removeAttr('disabled');
})
console.log(t);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='picks'>
<div id='29' parent='26'>Pick1</div>
<div id='30' parent='29'>Pick11</div>
<div id='31' parent='26'>Pick</div>
</div>
<select id="ss1">
<option >First pick</option>
<option value="26">Angri</option>
<option value="27">lands</option>
<option value="28">tree</option>
</select>
<select id="ss2" disabled>
<option >Secound Pick</option>
</select>
<select id="ss3" disabled>
<option>Third Pick</option>
</select>
Here is a jsfiddle jsfiddle
Is this what you were shooting for? https://jsfiddle.net/6c5t8ort/
A couple things,
var t = '#ss' + i;
$(t).change(function() {
This only adds the change event to the first dropdown. If you give jQuery a selector (a class) if will add the event to all the elements though. Also the way you had your i variable set up means it would increment on every change.
The code below only attaches a change listener to the first ss ss1 so the change function is never called when you change ss2.
var i = 1;
var t = '#ss' + i;
$(t).change(function() {
You can fix this by adding a class on each select and using $(".myClass").change(function() {
or you can just attach the listener to all selects $("select").change(function() {
Also the value for the option tag does not include a "parent" number. In this case it would be Pick, Pick1, or Pick11.
$('#ss' + i).append('<option value=' + $(this).text() + ' >' + $(this).text() + '</option>');

Generating select options using Json and Angular

This is an issue that has bothered me to no end. I need to somehow generate options for a select tag from a Json object using Angular. The code looks something like this:
<select id="cargo" ng-model="cargo.values.cargoList">
<option ng-repeat="(class, name, weight) in cargo.values.cargolist
ng-click="orderList()">
</select>
The class cargo.js looks a little like:
function setCargo(){
this.cargo = {
values: {
forkliftNeeded: false,
cargoList: {
class: "class",
name: "name",
weight: "weight"
}
}
};
this.setData = function(input); {
this.cargo.value.cargoList = input.cargo.cargoList;
this.cargo.value.forkliftNeeded = input.cargo.forkliftNeeded;
}:
And the actual Json object:
[{"cargo":{"forkliftNeeded":true,"cargoList":[{"class":"A","name":"Book","weight":"1"}]}}]
The idea it to generate the appropriate number of option tags based on the number of items in the cargo list. Each option needs to display in order and also needs to display the class, name, and weight for each item (for the record, I'm delegating the forkliftNeeded item to a check box).
To make things even more complicated, I also want to make it so that clicking on a given option moves said option to the top of the list. Not just the options, either- it has to actually change the order of the Json object.
As you can imagine, I'm not nearly skilled enough in angular to make this work by myself. Any help you can give me will be greatly appreciated.
EDIT:
I managed to make some headway. Turns out you can do just fine using:
<select id="cargo">
<option ng-repeat="item in cargo.values.cargolist"
ng-click="orderList()">
{{ item.class + " " + item.name + " " + item.weight }}
</option>
</select>
Now all I need to know is how to do the orderList() function. Is there a way I can get the index for the order tags on click?
What you're looking for is ngOptions. Adding that parameter into your <select> tag will automatically fill out the <options> based on your array.
<select id="cargo"
ng-model="cargo.values.cargoList"
ng-options="option.class + ' ' + option.name + ' ' + option.weight as option.name for option in cargo.values.cargoList">
</select>
More on ngOptions here:
https://docs.angularjs.org/api/ng/directive/ngOptions

jQuery Select2 values appended by formatter be made searchable

I'm using a formatter on select2 so i can have a nice alignment of two elements ( code / description ), but the plugin only seems to be searching upon the description and not looking at the code / description as the whole text.
Probably because its only searching against whats inside the original <option/> and not on what is being appended to that later on.
HTML
<select class="foo">
<option value="codex">description 1</option>
<option value="codey">description 2</option>
<option value="cod">description 3</option>
<option value="code">description 4</option>
</select>​
JS
function selectBoxOptionFormat(state) {
var originalOption = state.element;
return "<span class='selectBoxOptionCode'>" + state.id + "</span><span>" + state.text + "</span>";
}
$(".foo").select2({
width:"350px",
formatResult: selectBoxOptionFormat
}); ​
fiddle here
Anyone knows of a way around this ?
You can add this code - or manually add the value to the text in the html
$('.foo option').text(function(i,v){
return this.value + ' ' + v;
});
Then in your format function, remove the value
function selectBoxOptionFormat(state) {
var originalOption = state.element;
var txt = state.text.split(' ').slice(1).join(' ');
return "<span class='selectBoxOptionCode'>" + state.id + "</span><span>" + txt + "</span>";
}
http://jsfiddle.net/wirey00/2ZLWU/
EDIT:
You can use the matcher option and add the value to the text
$(".foo").select2({
width:"350px",
formatResult: selectBoxOptionFormat,
matcher: function(term, text,v) {
var txt = $(v).val() + ' ' + text;
return txt.toUpperCase().indexOf(term.toUpperCase())==0; }
}); ​
http://jsfiddle.net/wirey00/HudyG/
Without editing the select2 plugin you could do something simple like...
Appending the value to the description in your markup (or using jQuery).
<option value="codex">description 1 [codex]</option>
Then have your "selectBoxOptionFormat" strip it out
state.text.replace(/\[[^\]]+\]/, "");
Seems like its possible to create custom matches in Select2. I've missed the section on their documentation page that mentions the possibility of searching based on custom option attributes as well. Sorry bout that.
matcher: function(term, text, opt) {
return text.toUpperCase().indexOf(term.toUpperCase())>=0
|| opt.attr("value").toUpperCase().indexOf(term.toUpperCase())>=0;
}

calling a javascript function within markup created by javascript using Jquery

I have form fields which are displayed using Jquery on click of a button.
[select dropdown: conOperator] [textfield: conValue ] [select dropdown: conValuedd]
conValuedd is hidden by default.
I'm trying to figure out a way so that when I select either Apple or Banana in the first select drop down [conOperator], it hides the textfield conValue and displays drop down conValuedd instead. However, if I were to select Watermelon, it would display conValue and hide conValuedd again. Any ideas would be much appreciated.
$('<select id="conOperator' + num + '" name="conOperator' + num + '" class="standard_select" style="width:147px;">
<option>Watermelon</option>
<option>Apple</option>
<option>Banana</option>
</select>
<input type="text" id="conValue' + num + '" name="conValue' + num + '" class="short_input" value="" style="width:147px;">
<select style="display:none" id="conValuedd' + num +'" multiple="multiple" size="5">
<option value="option1">Blah</option>
<option value="option2">Blah</option>
</select>').appendTo('#addCondition');
Try something like a:
$('#addCondition').on('change','#conOperator' + num, function(e){
switch( $('option:checked',this).text() ){
case 'Apple':
case 'Banana':
$(this).nextAll(':text:first').hide();
$(this).nextAll('select:first').show();
break;
case 'Watermelon':
$(this).nextAll(':text:first').show();
$(this).nextAll('select:first').hide();
break;
}
});
$('#conOperator' + num).trigger('change');
DEMO
When you call appendTo(), the generated <select/> is added to the DOM so you can retrieve it with jQuery and add a listener on it.
$("#conOperator" + num).change(function() {
// Your logic here
}

Categories