display my dropdown box in a specific area - javascript

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.

Related

javascript/php won't load data for first option in dependent dropdown

I'm having a problem with a script that is part borrowed and part my own, it is javascript and php that populates two dropdown lists, with options in the second being dependent on what the user selects in the first. For some reason, it won't load the options in the second dropdown when the initial option is selected in the first, either on page load or if it is selected manually (if the options were 'a, b, c, d, e...etc', it won't load anything for 'a').
I think it might be something to do with the javascript document ready function, but I'm afraid I know very little about javascript. This is the javascript code:
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctProxy").change();
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});
Change event is only fired, when selection is changed - not when filled ;-)
Try adding $("#slctOutcome").trigger("change"); at pre-last line
Have fun :-)
Try the below. Second function wasn't being called in first function.
$(document).ready(function () {
$.getJSON("getOutcome.php", success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctOutcome").append(options);
$("#slctOutcome").change(); //<-Here
});
$("#slctOutcome").change(function()
{
$.getJSON("getProxies.php?outcome=" + $(this).val(), success = function(data)
{
var options = "";
for(var i = 0; i < data.length; i++)
{
options += "<option value ='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctProxy").html("");
$("#slctProxy").append(options);
});
});
});

Why are my rendered elements outside the select tag?

I am trying to append html to a Content Holder in a dialogue box and as you can see by the image, Mile, Meter and Kilometer are outside the select dropdown. Why is this?
var rows = $('#jqxUOMRelatedUnitsDropdownGrid').jqxGrid('getrows');
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").html('<select id="listNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder">');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
if (row.UOMRelatedUnit_AddItem) {
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append("<option value='" + row.UOMRelatedUnit_Name + "'>" + row.UOMRelatedUnit_Name + "</option>");
}
}
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append("</select>");
<div id="divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder"></div>
Because you are appending into the <div> and not the <select>. Do this way:
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder select").append("<option value='" + row.UOMRelatedUnit_Name + "'>" + row.UOMRelatedUnit_Name + "</option>");
// --------------------------------------------------- ^^^^^^
And you cannot do:
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append("</select>");
That's invalid! Either store everything in a tempAppend string and then use:
$("#divNewUnitOfMeasureDefaultUnitsPurchasePlaceHolder").append(tempAppend);

Populate the dropdown in order

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

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);
}

How to rewrite this Javascript code using Jquery?

function SelectDistrict(argument)
{
var sel=document.getElementById("city");
sel.style.display = '';
sel.options.length = 0;
sel.options.add(new Option('Please select a location',''));
var i=1;
var tempInt=parseInt(argument);
if (tempInt%10000==0)
{
var place1=document.getElementById('place1');
place1.innerHTML =county[tempInt];
}
sel.options.add(new Option('all',tempInt));
$('#inputcity').hide();
while (i<=52)
{
tempInt+=100;
if (county[tempInt]==undefined)
{
break;
}
else {
op_cir = new Option(county[tempInt], tempInt);
sel.options.add(op_cir);
}
i++;
}
}
You could do something like this:
function SelectDistrict(argument)
{
var sel = $('#city'); // Store the jQuery object to save time
sel.hide().empty().append('<option>Please select a location.</option');
var i = 1;
var tempInt = argument;
if (tempInt % 10000 == 0)
{
$('#place1').html(county[tempInt]);
}
sel.append('<option value="'+tempInt+'">all</option>');
$('#inputcity').hide();
var optionsValue = ''; // Appending strings to each other is faster than modifying the DOM
tempInt += 100;
while ((i <= 52) && (county[tempInt] != undefined)) // Just put the condition here instead of breaking the loop
{
optionsValue += "<option value='" + tempInt + "'>" + county[tempInt] + "</option>";
tempInt += 100;
i++;
}
sel.append(optionsValue);
}
I hope that works for you!
you have to replace every document.getElementById() by $("#elementid") like $("#city");
and place1.innerHTML =county[tempInt]; by $("#place1").text(county[tempInt]);
You can change the while loop to:
$.each(county, function(i, itm) {
optionsValue += "<option value='" + i + "'>" + itm + "</option>";
})

Categories