How to detect the selected value of a dropdown
When I select one item from 1st dropdown, an ajax event will fire up, invoke another function that will and load information to the second dropdown. I do not want this (No button solution please)
<select id=combo1>
<option>...</option>
开发者_运维技巧...
</select>
<input type=button onclick="loadCombo2()">
You can go about something like this:
<select id="combo1" onchange="requestSend(this.value);">
options..........
</select>
<select id="combo2">
options...........
</select>
<script>
function requestSend(txt)
{
$.ajax({
url:'process.jsp',
data: "v=" + txt,
cache:false,
success: function(response){
$("#combo2").val(response);
}
});
}
</script>
....
Populating Combo2 Options:
To populate combo2 options, you need to create them in the script which process ajax request, for example in php (i don't know which language you are using), i will do something like this in ajax processing script:
// db queries to get data or whatever
// create a variable that will hold options and shown in combo2
$options = '<option value="whatever">whatever</option>' . "\n";
$options .= '<option value="whatever">whatever</option>' . "\n";
$options .= '<option value="whatever">whatever</option>' . "\n";
//........ etc
// Now we send back the $options variable which will populate the combo2
echo $options;
If it was being implemented in ASP.NET I'd use an HTTP handler to return the data in JSON format to the second combobox.
Using jQuery you'd call the handler in the following way to implement cascading:
$("#combo1").change(function()
{
$("#combo2").html("");
var valueSelected = $("#combo1").val();
if (valueSelected != 0)
{
$.getJSON('LoadCombo2.ashx?valueSelected=' + valueSelected, function(returnedData)
{
$.each(returnedData, function()
{
$("#combo2").append($("<option></option>").val(this['ID']).html(this['Value']));
});
});
}
});
To see how to implement the HTTP handler, take a look at a more complete step-by-step in this post:
http://www.codedigest.com/Articles/jQuery/224_Building_Cascading_DropDownList_in_ASPNet_Using_jQuery_and_JSON.aspx
If you don't need cascading the comboboxes, it gets easier. Just call the handler passing no parameters and load any data you need to fill the second combobox in the callback function of jQuery.
http://api.jquery.com/jQuery.getJSON/
Hope you get the idea.
精彩评论