Jquery javascript - Chained Select Tutorial with fiddle

纵然是瞬间 提交于 2019-12-24 14:56:23

问题


I had an issue creating a chained select, and eventually found the solution by patching several SO solutions together. In the spirit of SO, I'm posting my final solution. It works with jquery 1.10.

And to make everyone happy, I also included the jsfiddle for it. =)

Final JSFiddle is here: http://jsfiddle.net/NNLh2/

Walkthrough:

Assume you have two select boxes:

<select id="my_alert_type_id" size="2" name="my_alert[type_id]">
    <option value="1">Live</option>
    <option value="2">EOD</option>
</select>
<br>
<br>
<select id="my_alert_category_id" name="myalert[category_id]" size="10">
    <option>select a feed type</option>
</select>

I want the second select options to change after the user selects an option from the first select. At first I used this answer from SO:

How do you remove all the options of a select box and then add one option and select it with jQuery?

And then I found out that it had to run when the page was actually done loading everything with this question:

show/hide div based on select option jquery

But it still didn't work the way I wanted. I had two options in that first box, and the code needed to respond to each selection. I needed to wrap it into a if/then block, and THEN run that nifty bit of code when I had the selection.

Greaaaat. I'm a C#/php/ruby/C developer; what the heck do I know about all those $'s and functions? Javascript tries to emulate C formatting, so I wrapped it in a if-then block, and with the help of this question:

JQuery - Get select value

I was able to assign the value of the first select to a variable, then run the nifty javascript replace-the-options part.

And viola! Now I have a basic chained select that works. I can replace it any way I want by adjusting the append part. This is for a rails project, so the next part is how to create all this dynamically. But for now I'll enjoy my kludged solution and get on with the project.

For the rails people: rails and js don't really talk to each other, so if you want to create those appended option dynamically, use escape_javascript, render, and custom create the url you're passing. And there's always passing it via json. There are other questions on SO that talk about it. Go look it up; I can't do everything for you. =P


回答1:


Well, I pretty much walked through the entire problem and solution above, so feel free to comment and critique. I'm rather proud of myself considering jquery and JS aren't my forte.



来源:https://stackoverflow.com/questions/20789049/jquery-javascript-chained-select-tutorial-with-fiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!