issya wrote:
I recently made this small script and was thinking it is a bit long.
It works just fine, I was wondering if there is any way to make it
shorter or is this right? Thanks in advance for the help.

The previous suggestion, I think missed the point that you were only selecting the first option for those that DIDN'T match the selected value, so would take some additional work to get working correctly.

My approach was someone similar. It's concise, but probably less readable than the original. The advantage is that it easily extensible to additional fields. But it would require that you change the HTML so that #id_zip_code became #id_zip. This is of course entirely untested, and probably will throw errors until it's debugged:

$(document).ready(function() {
    var items = ["city", "zip", "county"];
    $($.map(items, function(item, i){return "." + item}).join(",")).hide();
    $("." + $("input:checked").val()).show();
    $("input").click(function() {
        var test = $(this).val();
$($.map(items, function(item, i) {return "." + item}).join(",")).hide();
        $("." + $("input:checked").val()).show();
$($.map($.grep(items, function(item, i) {return (item != test);}), function(item, i) {return "#id_" + item + " option:first"}).join(",")).attr("selected", "selected");
    });
});

I don't know if this is in fact any better than the original code, but it is certainly shorter.

Cheers,

  -- Scott

Reply via email to