I'm using a <datalist>
<datalist id="items"></datalist>
And using AJAX to populate the list
function callServer (input) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//return the JSON object
console.log(xmlhttp.responseText);
var arr = JSON.parse(xmlhttp.responseText);
var parentDiv = document.getElementById('items');
parentDiv.innerHTML = "";
//fill the options in the document
for(var x = 0; x < arr.length; x++) {
var option = document.createElement('option');
option.value = arr[x][0];
option.innerHTML = arr[x][1];
//add each autocomplete option to the 'list'
option.addEventListener("click", function() {
console.log("Test");
});
parentDiv.appendChild(option);
};
}
}
xmlhttp.open("GET", "incl/search.php?value="+input.value, true);
xmlhttp.send();
}
However I can't get it to perform an action when I click on a selection in the datalist, for example if I type in "Ref F" and the item "Ref flowers" comes up, if I click on it I need to execute an event.
How can I do this?
option.addEventListener("click", function() {
option.addEventListener("onclick", function() {
option.addEventListener("change", function() {
Sorry for digging up this question, but I've had a similar problem and have a solution, that should work for you, too.
function onInput() {
var val = document.getElementById("input").value;
var opts = document.getElementById('dlist').childNodes;
for (var i = 0; i < opts.length; i++) {
if (opts[i].value === val) {
// An item was selected from the list!
// yourCallbackHere()
alert(opts[i].value);
break;
}
}
}
<input type='text' oninput='onInput()' id='input' list='dlist' />
<datalist id='dlist'>
<option value='Value1'>Text1</option>
<option value='Value2'>Text2</option>
</datalist>
This solution is derived from Stephan Mullers solution. It should work with a dynamically populated datalist as well.
Unfortunaltely there is no way to tell whether the user clicked on an item from the datalist or selected it by pressing the tab-key or typed the whole string by hand.
Due to the lack of events available for <datalist> elements, there is no way to a selection from the suggestions other than watching the input's events (change, input, etc). Also see my answer here: Determine if an element was selected from HTML 5 datalist by pressing enter key
To check if a selection was picked from the list, you should compare each change to the available options. This means the event will also fire when a user enters an exact value manually, there is no way to stop this.
document.querySelector('input[list="items"]').addEventListener('input', onInput);
function onInput(e) {
var input = e.target,
val = input.value;
list = input.getAttribute('list'),
options = document.getElementById(list).childNodes;
for(var i = 0; i < options.length; i++) {
if(options[i].innerText === val) {
// An item was selected from the list!
// yourCallbackHere()
alert('item selected: ' + val);
break;
}
}
}
<input list="items" type="text" />
<datalist id="items">
<option>item 1</option>
<option>item 2</option>
</datalist>
Use keydown
Contrary to the other answers, it is possible to detect whether an option was typed or selected from the list.
Both typing and <datalist> clicks trigger the input's keydown listener, but only keyboard events have a key property. So if a keydown is triggered having no key property, you know it was a click from the list
Demo:
const opts = document.getElementById('dlist').childNodes;
const dinput = document.getElementById('dinput');
let eventSource = null;
let value = '';
dinput.addEventListener('keydown', (e) => {
eventSource = e.key ? 'input' : 'list';
});
dinput.addEventListener('input', (e) => {
value = e.target.value;
if (eventSource === 'list') {
alert('CLICKED! ' + value);
}
});
<input type="text" id="dinput" list="dlist" />
<datalist id="dlist">
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
</datalist>
Notice it doesn't alert if the value being clicked is already in the box, but that's probably desirable. (This could also be added by using an extra tracking variable that will be toggled in the keydown listener.)
Datalist actually don't have an event (not all browsers), but you can detect if a datalist option is selected in this way:
<input type="text" list="datalist" />
<datalist id="datalist">
<option value="item 1" />
<option value="item 2" />
</datalist>
window.addEventListener('input', function (e) {
let event = e.inputType ? 'input' : 'option selected'
console.log(event);
}, false);
demo
Shob's answer is the only one which can detect when an option gets clicked as well as not trigger if an intermediary written text matches an option (e.g.: if someone types "Text1" to see the options "Text11", "Text12", etc. it would not trigger even if "Text1" is inside the datalist).
The original answer however did not seem to work on newer versions of Firefox as the keydown event does not trigger on clicks so I adapted it.
let keypress = false;
document.getElementById("dinput").addEventListener("keydown", (e) => {
if(e.key) {
keypress = true;
}
});
document.getElementById("dinput").addEventListener('input', (e) => {
let value = e.target.value;
if (keypress === false) {
// Clicked on option!
console.debug("Value: " + value);
}
keypress = false;
});
<input type="text" id="dinput" list="dlist" />
<datalist id="dlist">
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
</datalist>
Datalist don't support click listener and OnInput is very costly, checking everytime all the list if anything change.
What I did was using:
document.querySelector('#inputName').addEventListener("focusout", onInput);
FocusOut will be triggered everytime a client click the input text and than click anywhere else. If they clicked the text, than clicked somewhere else I assume they put the value they wanted.
To check if the value is valid you do the same as the input:
function onInput(e) {
var val = document.querySelector('#inputName').value;
options = document.getElementById('datalist').childNodes;
for(var i = 0; i < options.length; i++) {
if(options[i].innerText === val) {
console.log(val);
break;
}
}
}
<input type="text" id="buscar" list="lalista"/>
<datalist id="lalista">
<option value="valor1">texto1</option>
<option value="valor2">texto2</option>
<option value="valor3">texto3</option>
</datalist>
//0 if event raised from datalist; 1 from keyboard
let idTimeFuekey = 0;
buscar.oninput = function(){
if(buscar.value && idTimeFuekey==0) {
alert('Chévere! vino desde la lista')
}
};
buscar.onkeydown = function(event){
if(event.key){ //<-- for modern & non IE browser, more direct solution
window.clearInterval(idTimeFuekey);
idTimeFuekey = window.setInterval(function(){ //onkeydown --> idTimeFuekey++ (non 0)
window.clearInterval(idTimeFuekey);
idTimeFuekey = 0 //after 500ms onkeydown --> 0 (could work 500, 50, .. 1)
}, 500)
}
}
Well, at least in Firefox the onselect event works on the input tag
<input type="text" id="dinput" list="dlist" onselect="alert(this.value)"/>
<datalist id="dlist">
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
</datalist>
After having this problem and not finding a suitable solution, I gave it a shot.
What I did was look at the "inputType" of the given input event on top of the event toggle variable from above, like so:
eventSource = false;
const selector = document.getElementById("yourElementID");
selector.addEventListener('input', function(evt) {
if(!eventSource) {
if(evt.inputType === "insertReplacementText") {
console.log(selector.value);
}
}
});
selector.addEventListener('keydown', function(evt) {
eventSource = !evt.key;
});
This works if you want to allow the user to search a field but only hit a specific function/event on selection from the datalist itself. Hope it helps!
Edit: Forgot to mention this was done through Firefox and has not been tested on other browsers.
Related
I have a chunk of jQuery that isn't quite behaving the way I expect.
I'm taking the selected value from an HTML dropdown and storing it in a variable. The variable is then used to select an HTML element ID.
Here's the <select> I'm using for the dropdown:
<select id="bubble-tea-flavor" class="" name="attribute_bubble-tea-flavor" data-attribute_name="attribute_bubble-tea-flavor" data-show_option_none="yes">
<option value="">Choose an option</option>
<option value="Kiwi Apple" >Kiwi Apple</option>
<option value="Peach Mango" >Peach Mango</option>
<option value="Pineapple Peach" >Pineapple Peach</option>
</select>
Here are the HTML tags I am trying to target:
<rs-slides>
<rs-slide data-key="rs-1" data-title="pineapplepeach" data-anim="ms:1000ms;" data-in="o:0;" data-out="a:false;" class="pineapplepeach" id="pineapplepeach">
...
</rs-slide>
<rs-slide data-key="rs-3" data-title="peachmango" data-in="o:0;" data-out="a:false;" class="peachmango" id="peachmango">
...
</rs-slide>
<rs-slide data-key="rs-4" data-title="kiwiapple" data-anim="ms:1000ms;" data-in="o:0;" data-out="a:false;" class="kiwiapple" id="kiwiapple">
...
</rs-slide>
</rs-slides>
Here is the jQuery snippet:
jQuery(function($) {
$( "#bubble-tea-flavor" ).change( function() {
var slide = $(this).children("option:selected").val();
console.log(slide);
var selectedFlavorID = slide.replace(/\s+/g, '').toLowerCase();
console.log(selectedFlavorID);
revapi1.revcallslidewithid(selectedFlavorID);
});
});
It definitely works to some extent. The console log shows the value is being captured and modified correctly:
JQMIGRATE: Migrate is installed, version 3.3.2
(index):290 Peach Mango
(index):292 peachmango
(index):290 Pineapple Peach
(index):292 pineapplepeach
(index):290 Kiwi Apple
(index):292 kiwiapple
But then... nothing happens. What am I doing wrong?
Or, since this is for Revolution Slider and is probably more complicated than I'm thinking about it, how do I use Chrome to see what's happening when revapi1.revcallslidewithid(selectedFlavorID); is called?
For reference, here is the entire <script> tag where my snip comes from:
<script type="text/javascript">
setREVStartSize({c: 'rev_slider_1_1',rl:[1240,1024,778,480],el:[900],gw:[1240],gh:[900],type:'standard',justify:'',layout:'fullscreen',offsetContainer:'',offset:'',mh:"0"});
var revapi1,
tpj;
function revinit_revslider11() {
jQuery(function() {
tpj = jQuery;
revapi1 = tpj("#rev_slider_1_1");
if(revapi1==undefined || revapi1.revolution == undefined){
revslider_showDoubleJqueryError("rev_slider_1_1");
}else{
revapi1.revolution({
sliderLayout:"fullscreen",
visibilityLevels:"1240,1024,778,480",
gridwidth:1240,
gridheight:900,
enableUpscaling:true,
perspective:600,
perspectiveType:"global",
editorheight:"900,768,960,720",
responsiveLevels:"1240,1024,778,480",
progressBar: {
style:"vertical",
horizontal:"center",
vertical:"top",
size:5
},
navigation: {
onHoverStop:false
},
fallbacks: {
allowHTML5AutoPlayOnAndroid:true
},
});
jQuery(function($) {
$( "#bubble-tea-flavor" ).change( function() {
var slide = $(this).children("option:selected").val();
console.log(slide);
var selectedFlavorID = slide.replace(/\s+/g, '').toLowerCase();
console.log(selectedFlavorID);
revapi1.revcallslidewithid(selectedFlavorID);
});
});
}
});
} // End of RevInitScript
var once_revslider11 = false;
if (document.readyState === "loading") {document.addEventListener('readystatechange',function() { if((document.readyState === "interactive" || document.readyState === "complete") && !once_revslider11 ) { once_revslider11 = true; revinit_revslider11();}});} else {once_revslider11 = true; revinit_revslider11();}
</script>
I'am new to angularjs, I'm creating an application of attendance. When i check the checkall checkbox all the checkbox of name is also check and What i really wanted to achieve is to get the value of checked checkboxes. I'm done with checking all checkboxes. I just want to store all the value of checkboxes in an array. I can only get data when i check those checkboxes one by one. Thank you in advance.
In my html here is my code.
<ion-checkbox ng-model="Selected" ng-click="checkAll()">
<div class="wew">
Check All Checkbox
</div></ion-checkbox>
</label></div>
<table><tr><th><center>
List of Names
</center></th>
<th colspan="3">
Actions
</th></tr><tr><td><label>
<ion-checkbox ng-repeat="role in roles" ng-model="isChecked" ng-
change="format(isChecked,role,$index)"><div class="wew">
{{role}}
</div></ion-checkbox>
</label></td>
And in my controllers code. First this is my code where i get the list of names.
$http.post(link1, {section: section}).success(function(attendance){
for(a = 0; a<attendance.length; a++){
$scope.roles = [
attendance[0].Full_Name,
attendance[1].Full_Name,
attendance[2].Full_Name,
attendance[3].Full_Name,
attendance[4].Full_Name,
attendance[5].Full_Name,
attendance[6].Full_Name,
attendance[7].Full_Name,
attendance[8].Full_Name,
attendance[9].Full_Name,
]
}
})
.error(function(err) {
console.log(err)
})
And this is my code where i wanted to execute the checkall and automatically store the data in $scope.selected = []; if i click the check all checkbox..
$scope.checkAll = function () {
if ($scope.Selected) {
$scope.Selected = false;
} else {
$scope.Selected = true;
}
$scope.isChecked= $scope.Selected;
$scope.selected = [];
$scope.format = function (isChecked, role, $index) {
if (isChecked == true) {
$scope.selected.push(role);
}
else {
var _index = $scope.selected.indexOf(role);
$scope.selected.splice(_index, 1);
}
var students = $scope.selected;
console.log(students);
}
}
try this code
<script>
$(function(){
var numbers = $("input[type='checkbox']:checked").map(function(_, el) {
return $(el).val();
}).get();
});
</script>
I'm creating a standard html select dropdown with a hundred or so entries. My users would like to be able to type in the value to get to the proper selection faster. While this is supported natively, the keystroke timeout is very quick, so if you don't type the string quickly, you end up with the wrong selection. Is there a way to increase the timeout? Or has anyone written code to do this manually?
Here's a jsFiddle to illustrate the issues. JsFiddle
label for="title">Choose your poison</label>
<select id="title" name="title">
<option value="Cider" selected>Apple Cider</option>
<option value="Juice">Apple Juice</option>
<option value="Curacao">Curacao</option>
<option value="Jack">Jack's Hard Cider</option>
<option value="Jake">Jake's Hard Cider</option>
<option value="James">James' Hard Cider</option>
<option value="Jamison">Jamison Irish Whiskey</option>
<option value="Kool">Kool Ade</option>
<option value="Lemonade">Lemonade</option>
<option value="Prune">Prune Juice</option>
</select>
Try selecting the Jack's or Jake's by slowly typing and see if you end up selecting Curacao or Kool Ade.
You could use a <datalist> instead. It's supported in IE10 and higher. MDN Page
DEMO
<label for="poison">Choose your poison</label>
<input id="poison" name="poison" list="poisons" />
<datalist id="poisons">
<option value="Cider" selected>Apple Cider</option>
<option value="Juice">Apple Juice</option>
<option value="Curacao">Curacao</option>
<option value="Jack">Jack's Hard Cider</option>
<option value="Jake">Jake's Hard Cider</option>
<option value="James">James' Hard Cider</option>
<option value="Jamison">Jamison Irish Whiskey</option>
<option value="Kool">Kool Ade</option>
<option value="Lemonade">Lemonade</option>
<option value="Prune">Prune Juice</option>
</datalist>
If you have a small number of entries, the answer using datalist is fantastic. However, my users were using lists that had over a hundred entries and the datalist won't scroll. So, I built a utility class for use in a few places.
To use it, create the listFilter and initialize it with your list of choices. Then hook up keyUp and keyPress and use the return values. The class uses a 2-second time out and actually filters the answers. Using the delete key, you can clear the filtering. Be sure to check for a null return value in the keyUp, since that only handles the delete key. Note that the dropdown must be unexpanded for you to get the key events to work.
var listFilter = {
originalListToHold: [],
time1: 1,
search: "",
initialize: function(originalListToCopy) {
this.originalListToHold = [];
for (var i = 0; i < originalListToCopy.length; i++) {
this.originalListToHold[i] = originalListToCopy[i];
}
},
isInOriginalList: function(member) {
return this.originalListToHold.indexOf(member) > 1;
},
keyUpEvent: function(event) {
var keyCode = event.keyCode;
if (keyCode == 46) {
var filtered = this.filterList("");
this.search = "";
event.stopPropagation();
return filtered;
} else {
return null;
}
},
keyPressEvent: function(event) {
//The delete key will reset the list. See the key up event above.
var val = String.fromCharCode(event.which).toUpperCase();
var timenow = event.timeStamp;
var timeDiff = timenow - this.time1;
if (!isNaN(timeDiff)) {
//If the time difference is < 2 seconds (2000 ms), then we
//will search the options.
if (timeDiff > 2000) {
//Reset the search string
this.search = "" + val;
} else {
this.search = this.search + val;
}
} else {
this.search = "" + val;
}
this.time1 = timenow;
//Now, let's filter the options by the search string.
var filtered = this.filterList(this.search);
event.stopPropagation();
return filtered;
},
filterList: function(filter) {
var newList = [];
for (var i = 0; i < this.originalListToHold.length; i++) {
if (this.originalListToHold[i].indexOf(filter) > -1) {
newList.push(this.originalListToHold[i]);
}
}
return newList;
}
}
(I can't find it, but then again I don't really know how to search for it.)
I want to use <input list=xxx> and <datalist id=xxx> to get autocompletion, BUT I want the browser to match all options by 'contains' approach, instead of 'starts with', which seems to be standard. Is there a way?
If not simply, is there a way to force-show suggestions that I want to show, not those that the browser matched? Let's say I'm typing "foo" and I want to show options "bar" and "baz". Can I force those upon the user? If I just fill the datalist with those (with JS), the browser will still do its 'starts with' check, and filter them out.
I want ultimate control over HOW the datalist options show. NOT over its UI, flexibility, accessibility etc, so I don't want to completely remake it. Don't even suggest a jQuery plugin.
If I can ultimate-control form element validation, why not autocompletion, right?
edit: I see now that Firefox does use the 'contains' approach... That's not even a standard?? Any way to force this? Could I change Firefox's way?
edit: I made this to illustrate what I'd like: http://jsfiddle.net/rudiedirkx/r3jbfpxw/
HTMLWG's specs on [list]
W3's specs on datalist
DavidWalsh example
HONGKIAT's summary on behaviors..?
'contains' approach
Maybe this is what you are looking for (part 1 of your question).
It goes with the limitation of "starts with" and changes when a selection is made.
'use strict';
function updateList(that) {
if (!that) {
return;
}
var lastValue = that.lastValue,
value = that.value,
array = [],
pos = value.indexOf('|'),
start = that.selectionStart,
end = that.selectionEnd,
options;
if (that.options) {
options = that.options;
} else {
options = Object.keys(that.list.options).map(function (option) {
return that.list.options[option].value;
});
that.options = options;
}
if (lastValue !== value) {
that.list.innerHTML = options.filter(function (a) {
return ~a.toLowerCase().indexOf(value.toLowerCase());
}).map(function (a) {
return '<option value="' + value + '|' + a + '">' + a + '</option>';
}).join();
updateInput(that);
that.lastValue = value;
}
}
function updateInput(that) {
if (!that) {
return;
}
var value = that.value,
pos = value.indexOf('|'),
start = that.selectionStart,
end = that.selectionEnd;
if (~pos) {
value = value.slice(pos + 1);
}
that.value = value;
that.setSelectionRange(start, end);
}
document.getElementsByTagName('input').browser.addEventListener('keyup', function (e) {
updateList(this);
});
document.getElementsByTagName('input').browser.addEventListener('input', function (e) {
updateInput(this);
});
<input list="browsers" name="browser" id="browser" onkeyup="updateList();" oninput="updateInput();">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
Edit
A different approach of displaying the search content, to make clear, what happens. This works in Chrome as well. Inspired by Show datalist labels but submit the actual value
'use strict';
var datalist = {
r: ['ralph', 'ronny', 'rudie'],
ru: ['rudie', 'rutte', 'rudiedirkx'],
rud: ['rudie', 'rudiedirkx'],
rudi: ['rudie'],
rudo: ['rudolf'],
foo: [
{ value: 42, text: 'The answer' },
{ value: 1337, text: 'Elite' },
{ value: 69, text: 'Dirty' },
{ value: 3.14, text: 'Pi' }
]
},
SEPARATOR = ' > ';
function updateList(that) {
var lastValue = that.lastValue,
value = that.value,
array,
key,
pos = value.indexOf('|'),
start = that.selectionStart,
end = that.selectionEnd;
if (lastValue !== value) {
if (value !== '') {
if (value in datalist) {
key = value;
} else {
Object.keys(datalist).some(function (a) {
return ~a.toLowerCase().indexOf(value.toLowerCase()) && (key = a);
});
}
}
that.list.innerHTML = key ? datalist[key].map(function (a) {
return '<option data-value="' + (a.value || a) + '">' + value + (value === key ? '' : SEPARATOR + key) + SEPARATOR + (a.text || a) + '</option>';
}).join() : '';
updateInput(that);
that.lastValue = value;
}
}
function updateInput(that) {
var value = that.value,
pos = value.lastIndexOf(SEPARATOR),
start = that.selectionStart,
end = that.selectionEnd;
if (~pos) {
value = value.slice(pos + SEPARATOR.length);
}
Object.keys(that.list.options).some(function (option) {
var o = that.list.options[option],
p = o.text.lastIndexOf(SEPARATOR);
if (o.text.slice(p + SEPARATOR.length) === value) {
value = o.getAttribute('data-value');
return true;
}
});
that.value = value;
that.setSelectionRange(start, end);
}
document.getElementsByTagName('input').xx.addEventListener('keyup', function (e) {
updateList(this);
});
document.getElementsByTagName('input').xx.addEventListener('input', function (e) {
updateInput(this);
});
<input list="xxx" name="xx" id="xx">
<datalist id="xxx" type="text"></datalist>
yet this thread is posted about 2 years ago. but if you are reading this thread, you maybe need to check a newer version of your browser:
Current specification: https://html.spec.whatwg.org/multipage/forms.html#the-list-attribute
User agents are encouraged to filter the suggestions represented by
the suggestions source element when the number of suggestions is
large, including only the most relevant ones (e.g. based on the user's
input so far). No precise threshold is defined, but capping the list
at four to seven values is reasonable. If filtering based on the
user's input, user agents should use substring matching against both
the suggestions' label and value.
And when this post written, behavior of Firefox (51) and Chrome (56) had already been changed to match the specification.
which means what op want should just work now.
this fiddle here has cracked what you are asking for
But I am not sure how to make it work without this dependency as the UI looks bit odd and out of place when used along with Bootstrap.
elem.autocomplete({
source: list.children().map(function() {
return $(this).text();
}).get()
I found this question because I wanted "starts with" behavior, and now all the browsers seem to implement "contains". So I implemented this function, which on Firefox (and probably others), if called from input event handler (and optionally, from focusin event handler) provides "starts with" behavior.
let wrdlimit = prefix =>
{ let elm = mydatalist.firstElementChild;
while( elm )
{ if( elm.value.startsWith( prefix ))
{ elm.removeAttribute('disabled');
} else
{ elm.setAttribute('disabled', true );
}
elm = elm.nextElementSibling;
}
}
I have 3 dropdown menu. and all 3 are interlinked. ie, if i select the values of 1st dropdown, depending on that the second dropdown should display values. depending on the selection of 2nd dropdown, 3rd dropdown should populate the values. have done for 1st and 2nd. but depending on the values of 2nd drop down am not able to populate the values of 3rd dropdown. can anyone plaz help me. i know something like this will be in JFIDDLE.com. but not able to fine the exact name to search that!
You have to use AJAX if you want that. it will be easy.
<select name="ID"
id="ID"
onchange="DoYourTaskHere(this);">
<option value="select" selected="selected">Select</option>
<c:forEach items="${A.List}" var="Variable">
<option value="${ID}">
<c:out value="${ID}" />
</option>
</c:forEach>
</select>
And in the script you write the code as follows.
function loadValue(ID) {
if (ID.value != "select") {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
// Safari
ValueXmlHttpReq = new XMLHttpRequest();
} else {// code for IE6, IE5
ValueXmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
ValueXmlHttpReq.onreadystatechange = processLoadValues;
ValueXmlHttpReq.open("POST", "getValue.htm?ID="
+ ID.value, true);
ValueXmlHttpReq.send();
} else {
var objSelect = document.getElementById("ValueId");
var currentValueListLength = objSelect.options.length;
while (currentValueListLength > 0) {
objSelect.remove(1);
currentValueListLength--;
}
var objSelect = document.getElementById("2ndDropDownWhereYouWantToPopulate");
var currentSecondValueListLength = objSelect.options.length;
while (currentSecondValueListLength > 0) {
objSelect.remove(1);
currentSecondValueListLength--;
}
}
}
Allright , here something to get you started :
<form name='cars'>
<select name='brand'></select>
<select name='model'></select>
</form>
and the javascript (i'm using jQuery ) :
var application_model = [
{
name: "General motors",
models: [
"model1", "model2", "model3"
]},
{
name: "Mercedes",
models: [
"model4", "model5", "model6"
]},
{
name: "Fiat",
models: [
"model7", "model8", "model9"
]}
];
var selectedBrandIndex = 0
var selectedModelIndex = 0
function render() {
// render the first combo
$('select[name=brand]').empty();
$.each(application_model, function(index, object) {
var selected = "";
if (index == selectedBrandIndex) {
selected = "selected";
}
console.log(this);
$('select[name=brand]').append("<option value='" + index + "' " + selected + ">" + object.name + "</option>");
})
// render the second combo
$('select[name=model]').empty();
$.each(application_model[selectedBrandIndex].models, function(index, object) {
var selected = "";
if (index == selectedModelIndex) {
selected = "selected";
}
console.log(this);
$('select[name=model]').append("<option value='" + index + "' " + selected + ">" + object + "</option>");
});
}
function main() {
$("select[name=brand]").bind("change", function(event) {
console.log(event.currentTarget.value);
selectedBrandIndex = event.currentTarget.value;
render();
});
render();
}
main();
check the fiddle here :
http://jsfiddle.net/camus/MAgza/2/
cheers
you can try related combobox
You can easily setup any number of combobox instances on a single page. They can interact with each other based on certain client or server side events.
This example shows how the comboboxes can interact with each other using client-side methods and requesting the items on demand. To request the items on demand at the client-side, the requestItems() method is used.
The ViewState of the dependent comboboxes is disabled because the data required for their proper operation in this example is maintained in their ClientState.
refer http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/multiplecomboboxes/defaultcs.aspx