Through javascript how can I add more options to a dropdown selectmenu?
Currently trying the following with no luck:
for (i = 0; i < json.powerDropDownItems.length; i++) {
//$('#powerSelect').append($("<option></option>").attr("value", json.powerDropDownItems[i]).text(json.powerDropDownItems[i]));
$('#powerSelect').selectmenu("value", "nice name");
//$('#powerSelect').appendTo("<option>" + json.powerDropDownItems[i] + "</option>");
}
$('#powerSelect').selectmenu("refresh");
UPDATE
Thanks to naveen, I got it working (also added code to clear the list). Here is my following code:
service.getPowerDropDowns(productEC, $('#mountSelect').val(), function (response) {
var json = $.parseJSON(response.value);
var options = [];
// Clear the options first
$("#powerSelect option").each(function(index, option) {
$(option).remove();
});
options.push("<option value=''>Choose</option>");
for (i = 0; i < json.powerDropDownItems.length; i ++)
{
options.push("<option value='" + json.powerDropDownItems[i] + "'>" + json.powerDropDownItems[i] + "</option>");
}
$('#powerSelect').append(options.join("")).selectmenu();
$('#powerSelect').selectmenu('enable');
});
This will work
$(function() {
var options = [];
for (i = 0; i < json.powerDropDownItems.length; i++) {
options.push("<option value='" + json.powerDropDownItems[i] + "'>" + json.powerDropDownItems[i] + "</option>");
}
//append after populating all options
$('#powerSelect')
.append(options.join(""))
.selectmenu();
});
Demo: http://jsfiddle.net/codovations/p863Q/
Depends on the version.
https://github.com/jquery/jquery-ui/tree/selectmenu uses refresh method
https://github.com/fnagel/jquery-ui/tree/selectmenu uses selectmenu() like naveen described.
Related
I'm doing some refactoring and trying to create a generic method which is able to populate given dropdowns with object data. However I'm coming up against an issue regarding how to make accessing different object data generic. For example:
Original method
function populateDropdown(element, data) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i].ID + '>' + data[i].Name + '</option>');
}
This works if a given array of objects has the field ID and Name. What I'm trying to achieve is something like this
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i].valueField + '>' + data[i].dataField + '</option>');
}
When I've tried calling this method like this I get Undefined as a result: populateDropdown($('#myDropdown'), dataArray, "ID", "DataType");
And when I've tried without the "" I get a console error saying that ID and DataType isn't defined. Is there a way to tell my method what fields I want from the object?
Use bracket notation -
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
Note - to make this a little more resilient to special characters in the property values, I would do this instead:
$('<option />', { value : data[i][valueField] }).text(data[i][dataField]).appendTo(element);
You can do data[i][valueField]and data[i][dataField]:
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
Use bracket notation [] to access the properties:
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
What the others said, not sure if this is helpful, just fyi you can also define default values if you don't pass them like so...
function populateDropdown(element, data, valueField, dataField) {
valueField = valueField || 'some_default_value';
dataField = dataField || 'some_default_value';
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
Then you can call it like this, leaving valueField and dataField params out:
populateDropdown('someElement', 'someValue');
I've been stuck with this for several days and I can't solve it.
I've done it with jQuery with no problem, but I need it in pure JS.
This is how my list is generated.
function get_friends(items){
if(items != undefined){
if (items.length != 0){
var html_friends_list = "";
for(var count = 0; count < items.length; count++){
if(items[count].subscription == "both"){
var display_name = Strophe.getNodeFromJid(items[count].jid);
html_friends_list = html_friends_list + "<li style='font-size:19px' id='open_chat-" + items[count].jid + "'>" + "<a href='chat-js/index.html'>" + display_name + "<span class='block-list-label' id='" + items[count].jid + "_unread_messages" + "'>0</span><span class='block-list-label' id='" + items[count].jid + "_change_status" + "'></span></a></li>";
}
}
document.getElementById("friends-list").innerHTML = html_friends_list;
As a said I want to save the value of the text and the id of any li element clicked.
Regards
you haven't specified whether this is for a specific list or just any li on your page. The below will log the id and innerHTML components of any li on the page. Perhaps you may need to update the querySelector for your particular use case.
var list = document.querySelectorAll('li');
Array.prototype.slice.call(list).forEach(function(listItem){
listItem.addEventListener('click', function(e){
console.log(this.id);
console.log(this.innerHTML);
});
});
Here's a JSFiddle which I think demonstrates what you are trying to achieve.
Jsfiddle
Combination of james' answer and working example.
function get_friends(items) {
if (items != undefined) {
if (items.length != 0) {
var html_friends_list = "<ul>";
for (var count = 0; count < items.length; count++) {
if (items[count].subscription == "both") {
html_friends_list = html_friends_list + "<li id='open_chat-" + items[count].jid + "'>"+ items[count].display_name +"</li>";
}
}
html_friends_list = html_friends_list + '</ul>'
document.getElementById("friends-list").innerHTML = html_friends_list;
}
}
}
Note: you should trigger prototype after your dom element created.
It is my fiddle: http://jsfiddle.net/anton9ov/d8yga33f/
I need to organize an order of items in my selector according to the ID numbers in the GeoJSON file. It is a part of my code where the items appear in the list:
map.on("layeradd", function(e) {
if(!e.layer.options) {
return;
}
if((e.layer.options.id != "markerLayer1") && (e.layer.options.id != "markerLayer2")) {
return;
}
var markers = e.layer.getLayers();
var mySelector = $("#mySelector");
for(var i = 0; i < markers.length; i++) {
mySelector.append("<option value='" + L.stamp(markers[i]) + "'>" + markers[i].feature.properties.name + "</option>");
}
});
Try using Array.prototype.sort():
map.on("layeradd", function(e) {
// ...
var markers = e.layer.getLayers();
// Get the dropdown
var mySelector = $("#mySelector");
markers.sort(function(a,b) {
// get the ids, and parse them as int
var aId = parseInt(a.feature.properties.id,10),
bId = parseInt(b.feature.properties.id,10);
return aId < bId ? -1 : aId > bId ? 1 : 0
}).forEach(function(marker) {
mySelector.append("<option value='"
+ L.stamp(marker) + "'>"
+ marker.feature.properties.id // I added the marker id
+ '. '
+ marker.feature.properties.name
+ "</option>");
})
});
See forked fiddle
I need to build my DDL dynamically,I get info from DB using JSON (I get the data with no problem) but couldn't show my data in my DDL...
I tried three different ways, nothing changed.. What am I doing wrong ?
//HTML
<asp:DropDownList ID="productDDL" runat="server" CssClass="ddl"></asp:DropDownList>
//Javascript
function creatDDL(data) {
var obj = $.parseJSON(data.Data);
for (var i = 0; i < obj.length; i++) {
$("#productDDL").append("<option>" + obj[i].id + "' - '" + obj[i].name + "</option>");
$("#productDDL").append("<option>"+obj[i].id + "' - '" + obj[i].name+"</option>");
$("#productDDL").append($("<option></option>").html(obj[i].id + "' - '" + obj[i].name));
}
}
I like your third attempt best. Assuming your data is in order, you just need to brush up on the jQuery API.
Here's a working version of what I gather you're trying to do:
function createDDL(data) {
var options = $.parseJSON(data.Data);
$.each(options, function(n, option) {
var $option = $('<option />').text(option.name).val(option.id);
$("#productDDL").append($option);
});
}
Fiddle: http://jsfiddle.net/klenwell/Esr5q/
I am using my function in onclick nav tabs event (when click on any tab this below function activates). I just want that no same name can twice be inserted into the dropdownlist. Below function is working just perfectly. I just need a check maybe like name.text != arr[i] something like that to prevent it to insert the same name twice in the list. Any help would be appreciated.
js:
<script>
$(".nav-tabs li").click
(
function()
{
var getnumber = document.getElementById("permanentno").value;
var getData = 'methodname=getList&no='+getnumber;
$.ajax
({
type: 'GET',
url: 'Dropdown List/List.php',
data: getData,
success: function(resp)
{
alert(resp); // names for example: mile,stone,
var arr = resp.split(",");
var list = $(".dropdownlist");
var html = "";
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
}
}
$(".dropdownlist").append(html);
}
});
}
);
</script>
You could keep track of the names with another array and IndexOf. Note that for IE<9 support you'll need a shiv to use it.
var names = [];
for(var i = 0; i < arr.length; i++)
{
var name = arr[i];
if(name.length != 0 && names.indexOf(name) == -1)
{
html += "<option value='" + name + "'>";
html += name;
html += "</option>";
names.push(name);
}
}
You can append options to the dropdownlist on the loop, and check repeated names using jQuery like:
var list = $(".dropdownlist");
for (var i = 0; i < arr.length; i++) {
var name = arr[i];
if (name.length != 0 && !list.find("option[value='" + name + "']").length) {
var html = "<option value='" + name + "'>";
html += name;
html += "</option>";
list.append(html);
}
}