How do I implement cascading dropdown using golang's templates - javascript

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.

Related

PrimeFaces 3.2 Picklist : Getting Target-List On JavaScript Function

How to Traverse Picklist - TargetList and update the target list values to a ManagedBean List by using java script function.
Note: The version I am working not support ajax transfer event, I need to use onTransfer
Below my code.
<p:pickList id="pickListId" value="#{bean.legacySystem}"
onTransfer="bindTargetValues();" var="legacySys" widgetVar="pickListWV"
itemLabel="#{legacySys}" itemValue="#{legacySys}"/>
<script>
function bindTargetValues(){
//How to traverse and bind tragetList values to a managed bean object
}
</script>
If you want to access in the JavaScript the content of the both lists, there are hidden selects, suffixed with "_source" and "target".
So, $('[id$=pickListId_source] option') will return you all option elements representing the source list, and $('[id$=pickListId_target] option') the same, with target.
Than you can iterate the options and read value attribute to check which elements are in which list.

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.

Javascript - Remember Selected Option

I have a webpage thats created by javascript injections and one of my pages has a dropdown shown below:
html +="<select name='Sort' id='Sort' onchange='sortSwitch(document.getElementById(\"Sort\")[document.getElementById(\"Sort\").selectedIndex].value); display(document.getElementById(\"searchQuery\").value);return false;'>\n";
html +="<option></option>\n";
html +="<option value='4'>Smallest First</option>\n";
html +="<option value='5'>Largest First</option>\n";
html +="<option value='6'>A-Z</option>\n";
html +="<option value='7'>Z-A</option>\n";
html +="</select>";
The dropdown filters the information displayed on the page by passing the selected option to a switch function and another function reloads this information. However, when the javascript page loads again, it starts off with the blank option.
Does anyone know of a good way to remember the last sort selected? For example, if I sort with "Smallest First" and then the page refreshes, the box will show "Smallest First" as apposed to the blank. I know there is an "option selected" attribute, but I need it to be dynamic. I feel like it is something trivial, yet I can't seem to put my finger on it.
Thanks in advance!
Here's an article on Cookies in JavaScript which contains an explanation of how they work, along with functions to read, write and delete cookies.
Using those functions you'd get the selected value and write the cookie to save the value like this:
var select = document.getElementById("Sort");
var selectedItem = select.options[select.selectedIndex].value;
createCookie("selectedItem",selectedItem);
then read the cookie to retrieve the value and select the option in the select box, like this:
var selectedItem = readCookie("selectedItem");
var select = document.getElementById("Sort");
select.value = selectedItem;
You need to use cookies. or some session variables on the server side to save the values that were selected.
I use this jQuery cookie plugin

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:

Dynamically generate the content of Drop Down list via jQuery

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.

Categories

Resources