VimleshS
VimleshS

Reputation: 312

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

Upvotes: 2

Views: 2936

Answers (1)

icza
icza

Reputation: 417797

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.

Upvotes: 1

Related Questions