Jquery添加值以选择选项 [英] Jquery Add Values to Select Options
本文介绍了Jquery添加值以选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经用Google搜索了这个选项很多天但我找不到解决方案。
I have googled this option for many days but I couldn't find a solution.
我想要的是:
- 我有两个选择框
- 第一个选择框有国家名称
- 第二个选择框是空的
我想要的是当我从第一个选择框中选择任何国家(即英国)时,应运行php查询以获取所有来自table的城市名称然后使用Jquery将它们添加到第二个选择框。
What I want is when I select any country (i.e United Kingdom) from first select box, a php query should run to get all cities name from table then add them to second select box using Jquery.
谢谢
推荐答案
假设
-
你有一个带参数的脚本(/getCities.php)(country )这是您想要城市的国家/地区的ID,并输出如下所示的JSON:
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" } ]}
(您可以使用 JSONLint 来验证您的JSON。)
(You can use JSONLint to validate your JSON.)
然后可能是这样的:
<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>
这篇关于Jquery添加值以选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文