I'm new to jQuery, and have created a script that operates on a simple two-field form (as described below). I know that jQuery should make much of what I'm doing much easier than I'm actually doing it, so I'd appreciate any feedback on how to do things better. I'm trying to learn the jQuery way of doing things, so any improvements at all, no matter how small, will be gratefully received!
The form has a date field (standard text input box for now), and a country dropdown list. When a date is entered, an Ajax request is fired off and returns a JSON list of "best guess" countries. These are displayed as flags beside the dropdown list, and the first result is selected. The currently selected country at any time has a larger flag. Clicking on any of the flags changes the selection. Selecting a country from the dropdown that doesn't currently have a flag displayed will add that flag. The code is below. Thanks for any suggestions. Tony ---- The form is: <form> <p>Date: <input name="date" /></p> <p>Country: <select id="cty" name="country"> <option value="ad">Andorra</option> ... lots of other countries ... </select> <span id="flags" /> </p> <p><input type="submit" /></p> </form> ---- The jQuery script is: $(document).ready(function() { $("input[name='date']").change(function() { $.getJSON("/guess_location", { date: $(this).val() }, function(json){ set_flags(json.country); change_country(json.country[0]); } ); }); $("#cty").change(function() { set_big_flag( $(this).val() ); }); function set_flags(ccs) { $("#flags").html("").data("ccs", ccs); jQuery.each(ccs, function(i, cc){ $("#flags").append(flag_for(cc)).append(" "); }); } function flag_for(cc) { return $('<img>').attr({ class: 'flag', height: 20, border: 1, alt: cc, src: '/img/flag/' + cc + '.png' }) .data("country", cc) .click(function(){ change_country(cc) }); } function change_country(cc) { $("#cty").val(cc); set_big_flag(cc); } function set_big_flag(cc) { if ($("#flags .flag").filter(function() { return $(this).data("country") == cc; }).size() == 0) { var ccs = $("#flags").data("ccs"); ccs.push(cc); set_flags(ccs); } $("#flags .flag").attr('height', function() { return $(this).data("country") == cc ? 30 : 20; }); }