geepers
geepers

Reputation: 69

jquery get input value to retrieve matching array values to populate hidden inputs

Looking for some guidance on a form being used to extract lat/long values that are stored in an array. Code example is incomplete (sorry), just in the rough stages.

<script type="text/javascript">
$document.ready(function(){
    var geoCity = [
        { 'Toronto', '43.6532', '-79.3831'},
        { 'Vancouver', '49.2612', '-123.1139'},
        { 'Calgary', '51.04532', '-114.0581'}
    ];
});
</script>

When an input is entered for city field (actually uses bootstrap's typeahead on actual form), the entered value (before submission of form), needs to be used to search the arrays and extract the matching lat/long values and enter them into their respective hidden input fields.

<input type="text" id="city" name="city" value="" />
<input type="hidden" id="latitude" name="latitude" value="" />
<input type="hidden" id="longitude" name="longitude" value="" />

Hoping that someone can steer me in the right direction for this one.

Upvotes: 0

Views: 530

Answers (2)

user2625787
user2625787

Reputation:

Yes, change the data structure. Then correlate input values to object keys

$(function () {
    var geoCity = {
        'Toronto': {
            'lat': '43.6532',
            'lon': '-79.3831'
        },

        'Vancouver': {
            'lat': '49.2612',
            'lon': '-123.1139'
        },

        'Calgary': {
            'lat': '51.04532',
            'lon': '-114.0581'
        }
    };

    $('#button').click(function () {
        var lat, lon, city = $('#city').val();
        if (city) {
            lat = geoCity[city].lat;
            lon = geoCity[city].lon;
            $('#latitude').val(lat);
            $('#longitude').val(lon);
        }
    });
});

Fiddle

Upvotes: 1

Chandu
Chandu

Reputation: 82953

You need to change the structure of the geoCities object as mentioned below:

$(function () {
    var geoCity = [{
        'city': 'Toronto',
        'location': ['43.6532', '-79.3831']
    }, {
        'city': 'Vancouver',
        'location': ['49.2612', '-123.1139']
    }, {
        'city': 'Calgary',
        'location': ['51.04532', '-114.0581']
    }];

    $("#city").blur(function () {
        $("#latitude").val("");
        $("#longitude").val("");
        var curCity = $("#city").val();
        var location = $.map(geoCity, function (itm) {
            if (itm.city === curCity) 
                return itm.location; 
        });
        if(location) {
            $("#latitude").val(location[0]);
            $("#longitude").val(location[1]);
        }
    });
});

JsFiddle: http://jsfiddle.net/BJwhu/

You can $("#city").closest("form").submit instead of $("#city").blur.

Upvotes: 1

Related Questions