Populate the dropdown in order - javascript

I'm trying to populate my drop down in certain order (alphabetical order/alpha numeric order), but my code doesn't seems to be working. It is populating the value but not in order.
Here is my code
function dropdown(){
var html = html + "<option value='All'>All</option>";
var colValue = getColumn("COLUMN");
for( var i = 0; i < colValue.length; i++ ) {
var valueRow = colValue[i];
html = html + "<option value='" + valueRow.c + "'>" + valueRow.c + "-" + valueRow.v + "</option>";
}
$('#id').append(html);
}
here, COLUMN is the key that holds the value A1,A2,A3,B1
this code populate my drop down in the order A3,A1,A2,B1
I want my drop down to populate in the order A1,A2,A3,B1
while i did alert(html);i get the result
<option value='All'>All </option>";
<option value='A3'>A3-a3Value </option>";
<option value='A2'>A1-a2Value </option>";
<option value='A1'>A2-a1Value </option>";
<option value='B1'>B1-b1Value </option>";
and it is populating exactly in the same order.
My question is, what i need to do, to populate my dropdown in order?
I'm still in the beginner phase in java script and Jquery. Appreciate your help
Thanks

Based on what you are saying, it looks like colValue looks like this:
colValue = [
{ c="A3", v="a3Value" },
{ c="A1", v="a2Value" } // etc.
]
So you will need to decide what property to sort on, and then you can create a comparator:
function createComparator(property) {
return function(a, b) {
return a[property] > b[property];
};
}
You would use it like this:
colValue.sort(createComparator("c"));
Based on this SO answer: How to sort javascript objects based on their properties, specifying the property

You could try this:
function dropdown(){
var html = html + "<option value='All'>All</option>";
var colValue = getColumn("COLUMN");
colValue.sort();
for( var i = 0; i < colValue.length; i++ ) {
var valueRow = colValue[i];
html = html + "<option value='" + valueRow.c + "'>" + valueRow.c + "-" + valueRow.v + "</option>";
}
$('#id').append(html);
}

Since valueRow is an object instead of an array and you want to sort on valueRow.v you need more than Array.sort().
Take a look at lodash's sortBy: http://lodash.com/docs#sortBy
_.sortBy(valueRow, 'c')

Related

Where to place my code to select first option of <select> with jQuery?

I need to select first option of select with jQuery. My code is a bit complex and can't figure out how to make it work. Thanks
Html:
'sortingHtml': '<select id="bc-sf-filter-top-sorting-select">{{sortingItems}}</select>'
Javascript:
BCSfFilter.prototype.buildFilterSorting = function() {
if (bcSfFilterTemplate.hasOwnProperty('sortingHtml')) {
jQ(this.selector.topSorting).html('');
var sortingArr = this.getSortingList();
if (sortingArr) {
// Build content
var sortingItemsHtml = '';
for (var k in sortingArr) {
sortingItemsHtml += '<option value="' + k +'">' + sortingArr[k] + '</option>';
}
sortingItemsHtml = '<option disabled="disabled" selected>Sort by</option>' + sortingItemsHtml
var html = bcSfFilterTemplate.sortingHtml.replace(/{{sortingItems}}/g, sortingItemsHtml);
jQ(this.selector.topSorting).html(html);
// Set current value
jQ(this.selector.topSorting + ' select').val(this.queryParams.sort);
}
}
};
Code to select the first option:
$("#bc-sf-filter-top-sorting-select").val($("#bc-sf-filter-top-sorting-select option:first").val());
$("#bc-sf-filter-top-sorting-select option:first").prop("selected", true);

Splitting an array before adding to combo list

I have a JSON object that returns several key value pairs. One of which is a Languages key and this contains comma separated values e.g "English, Hindi,French" etc
I'm trying to split the array before adding it to a combo list, but everything I try fails. Can anybody help, please?
$('#combolist-languages').html(function () {
var ret = '<option value="-1" selected>Select language_</option>',
u = user.slice(),
arr = [];
(function get() {
if (u.length) {
var v = u.shift();
if ($.inArray(v.Languages, arr) == -1) {
arr.push(v.Languages);
ret += '<option value="">' + v.Languages + '</option>';
}
get();
}
}());
return ret;
});
I'm just not sure where to put the split function. Thanks!
What about that?
var lang = 'English,Hindi,French';
var html = '<option value="-1" selected>Select language_</option>';
html += '<option value="">';
html += lang.split(',').join('</option><option value="">');
html += '</option>';
$('#combolist-languages').html(html);
Setting a value for each option with jQuery.map :
var lang = 'English,Hindi,French';
var html = '<option value="-1" selected>Select language_</option>';
$('#combolist-languages').html(
html + jQuery.map(lang.split(','), function (text, value) {
return '<option value="' + value + '">' + text + '</option>';
})
);

Jquery / Javascript - most efficient way to build a select menu?

I'm using jquery and trying to tune my select menu builder to run much quicker.
I was using each and append, however I've since switched to a standard for loop and currently trying to convert my options from using append to concatenated string appended to my select option using .html(). I seem to be at a loss trying to convert my var option object back to an html string. Could someone please tell me what I might be doing wrong.
$.selectMenuBuilder = function(json) {
var myselect = $("#myselect");
var list = "<option value=\"\">> Select Account Number</option>";
var l= json.funding.length;
for(var i=0;i<l; i++) {
var funding = json.funding[i];
var option = $("<option value=\"" + funding.id + "\">" + funding.accountNumber + "</option>")
if(someLogic) {
option.attr("selected", "selected");
}
//Having trouble here converting option object back to html.
list += option.html();
}
list += "<option value=\"addnew\">+ New Account Number</option>";
myselect .html(list);
}
You can totally do away with using jQuery for creating the option elements (unless theres some other untold reason you're using it).
i.e. Instead of
var option = $("<option value=\"" + funding.id + "\">" + funding.accountNumber + "</option>")
if(someLogic) option.attr("selected", "selected");
You can do:
list += "<option value=\"" + funding.id + "\" "+ (someLogic?'selected':'') +">" + funding.accountNumber + "</option>"
Secondly, $(option).html() will return the innerHTML of the option element, not including the option tag name. For doing this in a cross-browser fashion, you can wrap the option in an outer element and use its innerHTML instead.
i.e.
$(option).wrap('<select/>').parent().html() will give you what you want.
If you want to keep the for loop but want something that looks a bit cleaner, try this:
function menuBuilder( json ) {
var list = [],
$select = $('#myselect'),
i = 0,
l = json.funding.length,
funding;
for ( ; i < l; i++ ) {
funding = json.funding[ i ];
list.push(
'<option '+ somelogic ? 'selected' : ''+' value='+ funding.id +'>'+
funding.accountNumber +
'</option>'
);
}
$select.append(
'<option>Select Account Number</option>'+
list.join('') +
'<option value="addnew">New Account Number</option>'
);
}
You can create elements more efficiently like this:
$.selectMenuBuilder = function (json) {
var myselect = $("#myselect");
var l = json.funding.length;
for (var i = 0; i < l; i++) {
var funding = json.funding[i];
var opt = $("<option/>", {
value: funding.id,
html: funding.accountNumber,
selected: somelogic ? true : false //Pre-select option
});
myselect.append(opt);
}
}
efficiency with pure JavaScript
example jsfiddle
selectMenuBuilder = function(json) {
var myselect = document.getElementById("myselect"),
listItem = document.createElement("option"),
l = json.funding.length,
someLogic = false; // placeholder
listItem.innerText = "> Select Account Number";
myselect.appendChild(listItem);
for (var i = 0; i < l; i++) {
var funding = json.funding[i];
var listItem = document.createElement("option");
if (someLogic) {
listItem.setAttribute("checked", "checked");
}
listItem.setAttribute("value", funding.id);
listItem.innerText = funding.accountNumber;
myselect.appendChild(listItem);
}
listItem = document.createElement("option")
listItem.setAttribute("value", "addnew");
listItem.innerText = "+ New Account Number";
myselect.appendChild(listItem);
}

Using Jquery val() on a dropdown list

Among other things I am trying to alert the selected value in the 'Amount' drop down box which is a list of numbers from 1 to 10. The list is generated and then inserted in to a div.
// generate the amount dropdown list
var dropdown = "<select name=\"amount\">";
for(var i=1; i <= MAX_PRINT; i++) {
dropdown = dropdown + "<option>" + i + "</option>"
}
dropdown = dropdown + "</select>";
jQuery("#" + divId).html("<div>Amount: " + dropdown + "</div></div>");
var amount = 1;
jQuery(document).ready(function() {
amount = jQuery("#amount").val();
alert(amount);
});
My question is: Why does it produce 'undefined' when I alert the amount? I am expecting it to return the selected number
Make sure you give your select an id—right now it just has a name. As a result, your jQuery('#amount') selector is not returning anything, which is why the alert is showing
undefined.
var dropdown = "<select id='amount' name='amount'>";
you are using amount = jQuery("#amount").val(); for that you have to give your dropdown an id
var dropdown = "<select name=\"amount\" id=\"amount\">";
DEMO
there are 2-3 Approach to get a selected value from <select>
use :selected
use .prop
use .attr
use this if this works for you:
jQuery(document).ready(function() {
var amount = jQuery("select[name='amount']").val();
alert(amount);
});
The id is missing on your dropdown.
// Generate the amount dropdown list
var dropdown = "<select id="amount" name=\"amount\">";
for(var i=1; i <= MAX_PRINT; i++) {
dropdown = dropdown + "<option>" + i + "</option>"
}
dropdown = dropdown + "</select>";
jQuery("#" + divId).html("<div>Amount: " + dropdown + "</div>/div>");
var amount = 1;
jQuery(document).ready(function() {
amount = jQuery("#amount").val();
alert(amount);
});

display my dropdown box in a specific area

Ok here's what I am doing. Based on some dropdown value I am craeting another dropdown value.
Is it possible to display that dropdown in some specific area as I wish based on my existing code.
if (SelectedIndex == 2 || SelectedIndex == 5 || SelectedIndex == 7) {
$("#DomContainer").remove();
var MainContainer = document.createElement("Div");
MainContainer.id = "DomContainer";
$("body").append(MainContainer);
var Options = new Array();
for(var i=1;i<=28;i++){
Options.push(i);
}
AddDropDown(Options);
}
function AddDropDown(Options) {
var selectHTML = "<label>Day:</label> ";
selectHTML += "<select>";
for (i = 0; i < Options.length; i = i + 1) {
selectHTML += "<option value='" + Options[i] + "'>" + Options[i] + "</option>";
}
selectHTML += "</select>";
document.getElementById("DomContainer").innerHTML = selectHTML;
}
For example <div id="new_drop">//Display the drop down here </div>
Simply add a second parameter to AddDropDown for passing the ID of the container to which you want to insert your dropdown list:
function AddDropDown(Options, containerId) {
...
document.getElementById(containerId).innerHTML = selectHTML;
Then call it like this:
AddDropDown(Options, "new_drop");
(if I understand you correctly)
No need to remove and append elements from the DOM, just replace the existing element contents ... here's a simplified version.
// if "SelectedIndex" is one of the values in the array provided
if ($.inArray(SelectedIndex, [2,5,7])) {
$("#DomContainer").html("<label>Day:</label> "+inject_dropdown(28));
}
// Creates and returns a new drop-down based on the "length" provided
function inject_dropdown(length){
var selectHTML = "<select>";
for( i=1; i<=length; i++ ){
selectHTML += "<option value='" + i + "'>" + i + "</option>"
}
selectHTML += "</select>"
return selectHTML;
}
Replace the $('#DomContainer') selector with whatever selector identifies the place you want the new drop-down to appear.

Categories