开发者

How can I correct my code to return all matching cities separate div's?

开发者 https://www.devze.com 2023-03-09 06:44 出处:网络
I have the following piece of JS code within a function that responds to the user pressing enter (not di开发者_开发问答splayed). The part of the code I am concerned with is shown:

I have the following piece of JS code within a function that responds to the user pressing enter (not di开发者_开发问答splayed). The part of the code I am concerned with is shown:

   $.each(cityhash,function(key,value){
        if(value['city']== user_input) {
            $('#city').append(value['city']);
            $('#state').append(value['state']);
        }

I have the following hash:

cityhash =  [{"address":"07288 Albertha Station","city":"Littelside","state":"Missouri"},{"address":"0615 Mervin Rapid","city":"Tessmouth","state":"South Carolina"},{"address":"779 Elody Lock","city":"Littelside","state":"New Mexico"}]

As you can see, the city of Littelside appears twice in the hash. My problem is if there are two city matches, the cities are placed directly beside one another. For example LittelsideLittelside. I would like each matching Littelside, to appear in its own div. How do I do this?

How can I correct my code to return all matching cities in their own separate div?

Thank you in advance


Instead of setting the city text in an element with id="city", I would make an element with id="cities" and then append the city elements inside of that.

$('#cities').append('<div class="city">' + value['city'] + ', ' + 
    value['state'] + '</div>');


Something like this:

$('#city').append($("<div>").html(value['city']));


var prev_city;

$.each(cityhash,function(key,value){
    if(value['city']== user_input) {
        $('#city').append(value['city']);
        $('#state').append(value['state']);

        if(value['city'] == prev_city){
            // Append to new div logic
        } else {
            prev_city = value['city'];
        }
    }
}

Not sure how you are printing the cities out right now but basically you need to track the previous city to know if you need to append another div.

0

精彩评论

暂无评论...
验证码 换一张
取 消