Dynamically generate the content of Drop Down list via jQuery - javascript

I am new to Javascript, JSON and jQuery. So please be easy on me. I have a JSP page that contain a drop down list. The contents of the drop down list are populated when the page is loaded. I wrote a Servlet that return the contain of the drop down list in the form of Map, and convert it to JSON string and sent back to the jsp via response.getWriter().write(json); However I am having trouble to getting the result back from the jsp side, and populate the contain of the drop down list from the result. Here are my codes
customer.jsp
$(document).ready(function() {
getCustomerOption('customer'); //try to pre-populate the customer drop down list
});
function getCustomerOption(ddId) {
var dd = $('#' + ddId);
$.getJSON("http://localhost:8080/WebApps/DDListJASON", function(opts) {
$('>option', dd).remove(); // Remove all the previous option of the drop down
if (opts) {
$.each(opts, function(key, value) {
dd.append($('<option/>').val(key).text(value));
}
}
});
}
down where the drop down list is generated
<select id="customer" name="customer">
<option></option>
</select>
The result is nothing get populated into the list. So sad

I think you are invoking the wrong function in document ready
Shouldn't it be
getInitialOption('customer');
instead of
getCustomerOption('customer');

You may add additional <option> elements to a <select> with the code:
$("#selectID").append("<option>" + text + "</option>");
see: JQuery Docs

I don't understand $(''), but I'm not sure that's the problem either, hard to tell exactly.
I do know it will be quicker if you do create the list of options in-memory and then do one append with .html(options) rather than append them one at a time. That may make it easier to understand also, to build the html up one line at a time and then append it.

Related

How do I implement cascading dropdown using golang's templates

Scenario:
I have a cascade scenario, where values in second dropdown depends upon first. I have three templates "layout", "input" and "inner".
Attempt:
I'm making ajax call on change of first dropdown in "input" template and stuck with handling the response returned. Currently I found a way to fix it by replacing html of second dropdown. But, I think this is not the better way to handle. I want something in line of rendering templates where I do not need to amend html.
please help in acheiving the task in better way or point to some wiki. Only Standard Library
Thanks,
Layout.html:
http://play.golang.org/p/LikKy6rf3-
Input.html:
http://play.golang.org/p/wM7EpPdXuM
Inner.html:
http://play.golang.org/p/xFpInKZfFT
Main.go:
http://play.golang.org/p/cxtJU-Lhi1
On the higher level you have 2 options:
Either send all the values for the dropdown lists (e.g. as a tree) and change the values on the 2nd and 3rd level when the dropdown of a higher level changes (suitable for small lists, unsuitable for large dataset)
Or the one you chose: when selection changes, you make an AJAX call (triggered from onchange) and you populate the list from the results.
Elaborating #2: populating list from the AJAX call result
You also have 2 options to do this:
Either the AJAX call returns HTML call which you can simply use to replace the inner HTML of the HTML <select> tag.
Or the AJAX call may only return the data (e.g. encoded using JSON), and a Javascript code can build the content of the list.
AJAX returning HTML
The AJAX call may return the complete HTML code needed to be replaced as the inner HTML of the <select>. To achieve this at server side, you can create/separate the HTML template responsible only to generate the HTML code of this, for example:
{{define "innerList"}}
{{range .}}
<option value="{{.Key}}">{{.Text}}</option>
{{end}}
{{end}}
You can execute only this template like this:
// tmpl is the collection of your templates
values := ... // Load/construct the values
tmpl.ExecuteTemplate(w, "innerList", values)
Here values is a slice of the following structure:
type Pair struct {
Key string
Text string
}
Building <select> content with Javascript
The AJAX call may return a JSON datastructure, an array/list of value;text pairs from which you add the <option> child tags yourself.
To add an <option> to a <select> tag:
var x = document.getElementById("mySelect");
var option = document.createElement("option");
option.value = "1234";
option.text = "Kiwi";
x.add(option);
So basically what you need to do is remove current children of the <select>, iterate over the list received as the response and add a new <option> tag constructed from each.

Dropdown values disappear in an AJAX-based jQuery element

I am growing quite fond using AJAX, JSON, and jQuery. I am coding from scratch an application to replace a previous application that is flawed.
Although I am progressing and getting better using the AJAX method, I am coming across various issues that I want to correct, so that my replacement application is flawless.
My application uses AJAX to call PHP scripts. It returns JSON that I use to populate certain dropdowns for the user to select.
For the most part, the application does what it is supposed to do. The many dropdowns populate with the parsed JSON data. The user can select 1 or more dropdowns which will then fire a SEARCH query that will return data.
The issue appears to happen when the data-set from the previous search is large. I'm talking barely thousands. When I click on the dropdown to conduct a new search, the dropdown (that was previously populating the JSON data) is now blank.
It doesn't do it all the time. It seems this issue arises when the initial search returns a large data set. I cannot be for sure.
Here is the html within my file called bpSearch.php: (just two of my dropdowns)
<div class="input-group">
<span class="input-group-addon">Sales Rep</span>
<select class="form-control" id="salesRep" name="salesRep">
<option value=""></option>
</select>
</div>
<div class="input-group">
<span class="input-group-addon">Services</span>
<select class="form-control" id="service" name="service">
<option value=""></option>
</select>
</div>
There are a few more dropdowns. I only listed 2.
Here is the javascript (also within the same file, bpSearch.php) that populates the dropdowns via AJAX and JSON:
<script type="text/javascript">
// populates the dropdown id #salesRep
$.getJSON( "api/reps.php", function( data )
{
$.each(data, function(index, item)
{
$('<option>').
attr('value', item.fullname).
text(item.fullname).
appendTo($('#salesRep'));
});
});
// populates the dropdown id #service
$.getJSON( "api/services.php", function( data )
{
$.each(data, function(index, item)
{
$('<option>').
attr('value', item.service).
text(item.service).
appendTo($('#service'));
});
});
</script>
Here is the PHP called reps.php. This returns the JSON data for the #service dropdown:
<?php
if ($result =
mysqli_query($dbc, "SELECT DISTINCT(service)
FROM services_imp ORDER BY service"))
{
$out = array();
while ($row = $result->fetch_assoc())
{
$out[] = $row;
}
echo json_encode($out);
mysqli_free_result($result);
}
?>
At this point, I don't think I need to show the code for reps.php. It pretty much looks exactly the same as the code for services.php, except of course for the names of the fields that I search in the query.
With all the code above, I can populate the dropdowns as stated. But, as I also previously stated, sometimes the dropdown values disappear after conducting a search. This seems to always happen when the data-set is large.
Here is what the services dropdown looks like when it is working:
And here is what it looks like after I conduct a search that returns a larger data-set:
I do not understand why this is happening. What might be causing it?
It is a good practice to ensure that the dropdowns are loaded in DOM ready event
$(function()
{
//AJAX call for loading dropdowns
})
Please make sure first that the calls are made in DOM ready event.
The following code disables the dropdown when the AJAX function is called and enables it when the data is fully loaded. Execution starts when the page is fully loaded and I reduced your AJAX calls to one generic function that accepts an element and a uri as input. This function also makes a clone of the select. Appending the new options in memory and when the list is build the original select is replaced with the cloned one. This should enhance the browser performance.
function loadDataAndAppendToSelect(select, uri)
{
$(select).prop('disabled', true); //disable
// populates the dropdown id
$.getJSON( uri, function( data )
{
var tempElement = $(select).clone();
$.each(data, function(index, item)
{
$('<option>').
attr('value', item.fullname).
text(item.fullname).
appendTo(tempElement);
});
$(select).replaceWith(tempElement);
$(select).prop('disabled', false); //enable
});
}
$(document).ready(function(){
loadDataAndAppendToSelect('#salesRep', 'api/reps.php');
loadDataAndAppendToSelect('#service', 'api/services.php');
});

Dynamically loading select boxes on page load

I'm dynamically populating several select boxes via ajax calls when my app first opens. When the page loads however, what I am noticing is my select boxes start out empty and then once populated they adjust their size accordingly. This is annoying and a bit of a UI distraction.
I do have the population methods within my document.ready method, but perhaps I am approaching this incorrectly?
$(document).ready( function(){
populateOptions(); // Populate our select box upon page load.
});
// Builds a select list and binds it to a class
function populateOptions(){
var optionList = getOptions();
var myList = "";
// Loop over our returned result set and build our options
for(i=0; optionList.length; i++){
myList += "<option>"+optionList[i][1]+"</option>";
}
// Now take our myList and append it to our select
$("#myOptionList").append(myList);
}
Options: <select id="myOptionList"></select>
you can set a width to the select by css
Add a dummy option to show while Loading via AJAX:
<select id="myOptionList">
<option>Loading...</option>
</select>
Clear "loading" option and add new list once available
$("#myOptionList").html('');
$("#myOptionList").append(myList);
to set width with css:
#myOptionList{
width:150px;
}
One simple solution would be to create your child directly when your ajax function is called.
Before finishing your populateOptions() function, append the select to your .
I remember having this issue, it is possible to solve it but this is a very simple way to handle it.
Hope this help.

Unable to select first element from select using Jquery

I am filling a drop down based on the value selected in the first drop down.Data being sent back from server is in JSON format and using JQuery to parse and fill the second select tag
<select name="abc" id="jobName">
<option value="-1">Please select a Job</option>
</select>
This is my Jquery code
var selectedGroup = document.getElementById(groupDropDownId);
var groupdata = selectedGroup.options[selectedGroup.selectedIndex].value;
var formInput='group='+groupdata;
$.getJSON('search/getSchedulerJobListForGroup',formInput,function(data) {
$('.result').html('' + data.jobList + '');
$.each(data.jobList,function(index, value){
var jobId = document.getElementById(resetDropDownId);
var option=new Option(value,value);
try{
jobId.add(option);
}
catch(e){
jobId.appendChild(option);
}
});
});
$("#jobName")[0].selectedIndex = 1;
// $("#jobName").val($("#triggerjobName option:first").val());
in above code groupDropDownId is ID of the drop down based on whose value, second drop down will be filled.resetDropDownId is ID of second drop down which i am trying to fill from JSON data getting from the server.
Upon filling the drop down, its also creating an empty option tag and it is getting select by default.
I am not sure if i can add some default value to that empty option so that i can select that default option value like "please select bla bla."
also i tried to select first element from the drop down but nothing seems working for me.I am wondering what i am doing wrong here?
Based on your question, it looks like you want to know how to change the value and text of an element within a dynamically populated select list.
Currently, you have this statement $("#jobName")[0].selectedIndex = 1; sitting outside of your getJSON request. If you move this inside of the getJSON function, it will work as expected.
If you want to set the value and text of that object, you'll want to use ->
$('#jobId option:first').val("Some Value").text("other stuff");
You can see a working JS Fiddle using dynamically populated select list from a JSON object.
Fiddle

Populating JScript Array for reuse on SELECTs

Forgive me if this is already 'somewhere' on StackOverflow, but I don't 100% know exactly what it would come under...
I'm trying to retrieve information from a WebService, store this in an array, and then for each <select> within my ASP.Net Datalist, populate it with the array AND have binding attached to an OnChange event.
In other words, I have an array which contains "Yes, No, Maybe"
I've an ASP.Net Datalist with ten items, therefore I'd have 10 <Select>s each one having "Yes, No, Maybe" as a selectable item.
When the user changes one of those <Select>s, an event is fired for me to write back to the database.
I know I can use the [ID=^ but don't know how to:
a) Get the page to populate the <Select> as it's created with the array
b) Assign a Change function per <Select> so I can write back (the writing back I can do easy, it's just binding the event).
Any thoughts on this?
I have built a simple example that demonstrates, I think, what you are attempting to accomplish. I don't have an ASP.Net server for building examples, so I have instead used Yahoo's YQL to simulate the remote datasource you would be getting from your server.
Example page => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource.html
Example steps:
query datasource to get array of select questions
build HTML of selects
append HTML to page
attach change event listener to selects
on select value change submit value
Example jQuery:
// get list of questions
$.ajax({
url: url,
dataType: "jsonp",
success: function(data) {
// build string of HTML of selects to append to page
var selectHtml = "";
$(data.query.results.p).each(function(index, element) {
selectHtml += '<select class="auto" name="question'+index+'"><option value="Yes">Yes</option><option value="No">No</option><option value="Maybe">Maybe</option></select> '+element+'<br/>';
});
// append HTML to page
$(document.body).append(selectHtml);
// bind change event to submit data
$("select.auto").change(function() {
var name = $(this).attr("name");
var val = $(this).val();
// replace the following with real submit code
$(document.body).append("<p>Submitting "+name+" with value of "+val+"</p>");
});
}
});
Example datasource => http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-multiple-selects-from-datasource-datasource.html
Example loaded:
Example select value changed:

Categories

Resources