如何使一个选择框的值驱动第二个选择框的选项
我想制作一个带有 2 个选择框的 HTML 表单。第一个选择框中选定的选项应驱动第二个选择框中的选项。我想在客户端上动态解决这个问题(使用 javascript 或 jQuery),而不是必须向服务器提交数据。
例如,假设我有以下菜单类别和菜单项:
- 三明治
- 土耳其
- 火腿
- 培根
- 配菜
- 奶酪通心粉
- 土豆泥
- 饮料
- 可口可乐
- 雪碧
- 甜水 420
我有两个选择
框,分别命名为Menu Category
和Items
。当用户在Menu Category
框中选择Sandwiches
时,Items
框中的选项将仅显示Sandwich选项。
为了使这更具挑战性,我们假设在我准备好将页面发送给客户端之前我不知道菜单项或类别是什么。我需要某种方法来“链接”两个选择列表的数据,但我不知道如何完成。
我对如何处理这个问题感到困惑。一旦我过滤掉第二个列表一次,一旦我更改第一个列表中的菜单类别,如何“查找”列表选项?另外,如果我在 SQL 中思考,我会在第一个框中有一个键,用于链接到第二个框中的数据。但是,我看不到第二个框中有足够的空间容纳“关键”元素。
如何结合使用 jQuery 或纯 JavaScript 来解决这个问题?
I want to make an HTML form with 2 select boxes. The selected option in the first select box should drive the options in the second select box. I would like to solve this dynamically on the client (using javascript or jQuery) rather than having to submit data to the server.
For example, let's say I have the following Menu Categories and Menu Items:
- Sandwiches
- Turkey
- Ham
- Bacon
- Sides
- Mac 'n Cheese
- Mashed Potatoes
- Drinks
- Coca Cola
- Sprite
- Sweetwater 420
I would have two select
boxes, named Menu Category
and Items
, respectively. When the user selects Sandwiches
in the Menu Category
box, the options in the Items
box will only show Sandwich options.
To make this more challenging, let's assume that I don't know what the menu items or categories are until I'm ready to send the page to the client. I'll need some way to "link" the data for the two select lists, but I don't know how that would be done.
I'm stuck as how I might approach this. Once I filter out the 2nd list one time, how do I "find" the list options once I change my menu category in the 1st list? Also, if I'm thinking in SQL, I would have a key in the 1st box that would be used to link to the data in the 2nd box. However, I can't see where I have room for a "key" element in the 2nd box.
How could this problem be solved with a combination of jQuery or plain javascript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在动态云端硬盘上查看此示例,或者您可以在 google 中搜索“链式选择" 查看其他示例。
编辑:这是一个非常好的 Remy Sharp 教程: 使用 jQuery 和自动填充选择框AJAX
好吧,因为我有强迫症,所以我为您整理了一个演示。
它定义了一个变量,如果需要的话也可以加载为 json。
HTML
脚本
Check out this example on Dynamic Drive, or you can search google for "chained select" for other examples.
Edit: And here is a very nice Remy Sharp tutorial: Auto-populating Select Boxes using jQuery & AJAX
Well, because I have OCD, I threw together a demo for you.
It defines a variable could also loaded as json if required.
HTML
Script
你可以做简单的javascript。如果这就是您需要 javascript 的全部目的,那么 jQuery 可能就太多了。
在 中创建一个函数来填充第二个组合框。在第一个组合框中,您使用 onChange=theFunctionYouCreated() 调用该函数,
希望这足以让您开始。
You could do plain javascript. If this is all you need javascript for, then jQuery is probably too much.
create a function in the that populates the second combo box. In the first combo box, you call that function with onChange=theFunctionYouCreated()
hope that's enough to get you started.