Although VitoshAcademy is not an Academy, there should be some educational stuff. Thus, in this article I have decided to put something educational. 🙂
Let’s see how to make a simple selector in jQuery, which updates below some text, based on the selection. Thus, we have three different selectors, as in the picture:
Each selector has 4 two-letter abbreviations, which are related to cities in Bulgaria, Netherlands and Spain. Once you select anything on any of the selectors, an action is triggered. An array of the selected items is serialized and based on the name of the selector, the results are displayed. What is interesting to see is the removal of the <hr> and its adding through JS. Both were not known for me, before starting the article.
Its better to see the code, than to speak about it.
Here it goes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
$(document).ready(function(e) { $('form').on('change', function() { $('#message').empty(); $('#summary').empty(); $('hr').remove(); var choice =$(this).serializeArray(); var bg = 0; var nl = 0; var es = 0; $.each(choice, function(i, item){ $("#message").append(i+1 + ". " + item.name + ": " + item.value + "<p>"); switch (item.name) { case "Bulgarian": bg++; break; case "Dutch": nl++; break; case "Spanish": es++; break; } }); var hr_line = "<hr/>"; $('#summary').before(hr_line); $("#summary").append("You have selected " + bg + " Bulgarian cities."+"<p>"+"You have selected " + nl + " Dutch cities."+"<p>"+"You have selected " + es + " Spanish cities."+"<p>"); }); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<html> <head> <title>VitoshAcademy</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="my_script.js"></script> </head> <body> <form id="my_form"> <select name="Bulgarian" multiple="multiple" size="6"> <option value="Sofia">SF</option> <option value="Plovdiv">PD</option> <option value="Varna">VN</option> <option value="Bourgas">BR</option> </select> <select name="Dutch" multiple="multiple" size="6"> <option value="Groningen">GR</option> <option value="Utrecht">UT</option> <option value="Eindhoven">ED</option> <option value="Maastricht">MA</option> </select> <select name="Spanish" multiple="multiple" size="6"> <option value="Barcelona">BA</option> <option value="Valencia">VT</option> <option value="Alicante">AT</option> <option value="San Antonio">SA</option> </select> </form> <div id="content"> <p id="message"></p> <p id="summary"></p> </div> </body> </html> |
Available also in GitHub here.
Enjoy it! 🙂