Jquery Add Values To Select Options
I have googled this option for many days but I couldn't find a solution. What I want is: I have two Select Box First Select Box have Country Names Second Select Box is Empty Wha
Solution 1:
Assumption
You have a script ("/getCities.php") that takes a parameter ("country") that is the ID of the country you want the cities of and outputs JSON that looks like this:
{"Cities": [ { "ID": 1, "Name": "New York" }, { "ID": 2, "Name": "Los Angeles" } ]}
(You can use JSONLint to validate your JSON.)
Then maybe something along these lines:
<select id="Countries">
<!-- omitted -->
</select>
<select id="Cities"></select>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// when a new country is selected...
$("#Countries").change(function() {
// ...clear existing cities...
$("#Cities").empty();
// ...and repopulate cities based on JSON data.
$.getJSON( "/getCities.php",
// pass the selected country ID
{
country: $("#Countries").val()
},
function(data) {
$.each(data.Cities, function(n, city) {
// add a new option with the JSON-specified value and text
$("<option />").attr("value", city.ID).text(city.Name).appendTo("#Cities");
});
}
);
}); // $("#Countries").change(function() { ... });
}); // $(document).ready(function() { ... });
</script>
Solution 2:
try this.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
function moveItem() {
$("#target").append($("#source").find(':selected'));
}
</script>
<select id="source" size="3">
<option>option1</option>
<option>option2</option>
<option>option3</option>
</select>
<button onclick="moveItem()">Move Item</button>
<select id="target" size="3"></select>
Solution 3:
The "cascading dropdown" is such a common interface - I find it hard to believe that you couldn't find any examples. Here's a PHP example that will point you in the right direction.
Post a Comment for "Jquery Add Values To Select Options"