从一个选择框填充两个选择框
我浏览了这些主题来解决我的问题,但我认为我的问题有点不同。
我的表单中有 3 个选择框。命名为“类别”、“子类别”、“主题”。
子类别是从类别选择中填充的,主题是从子类别选择框中选择的。
我创建了一个通用函数,用于使用 jQuery 填充选择框。
我在父选择框的更改事件上调用该函数(populateSelectBox
)。
现在,子类别选择框可以轻松地填充到类别选择框的更改事件上,但是如果子类别只有一个通过 ajax 填充的选项,则不会触发子类别的更改事件,因为子类别选择框中只有一项.
这种情况下我该怎么办?
请帮忙。
I went through these topics for a solution to my problem but I think my question is a bit different.
- Using javascript and jquery, to populate related select boxes with array structure
- Populating a 2nd select box - binding problem
I have 3 select boxes in my form. Named 'Category', 'Subcategory', 'Topic'.
Subcategory is populated from selection of Category and topic is selected from subcategory select box.
I have created a generalized function for populating select boxes using jQuery.
I am calling that function (populateSelectBox
) on the change event of parent select box.
Now the Subcategory select box is easily populated on the change event of Category select box but if the subcategory has only one option populated through ajax, the change event for subcategory is not fired as there is only one item in the subcategory select box.
What shall I do in that case in?
Please help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以测试收到的选项数量,如果只有一个,则手动触发
change
事件:或者只是:
另一种方法是在每个
select
的顶部实际上是一个标题。类似于:这将要求用户选择一个选项,即使只有一个选项存在。
You could test for the number of options received and if there's only one, trigger the
change
event manually:or just:
Another way to go would be to have an
option
at the top of eachselect
that is effectively a heading. Something like:This would require the user to choose an option, even if only one exists.
发布此答案是因为我只需要在第二个选择框的更改事件上填充第三个选择框。
感谢帕特里克给出了空白选择选项的想法
因此,我没有通过 PHP 添加空的“选择选项”,而是修改了我的 populateSelectBox 函数,使其自动添加空白响应中的“选择”选项,例如
$element.append('');
以便更改事件可以由用户触发。Posting this answer as I needed to populate the third select box only on the change event of second select box.
Thanks to patrick for giving an idea of blank select option
So instead of adding an empty 'select option' through PHP, I modified my populateSelectBox function in such a way that it will automatically add a blank 'select' option to the response, like this
$element.append('<option value="">Select</option>');
so that change event can be triggered by the user.