1

I'm having trouble populating a SELECT with jquery, when the user writes the zipcode or part of it, it searches the database and returns this:

{"success":1,"id":"50","street":"Central One"},{"success":1,"id":"60","street":"Central Two"}

One success for each street it finds. For a single street and using a text input I'm using this

UPDATE 1 - FULL CODE

$(document).ready( function() {
 $('#zip').blur(function(){
       $.ajax({
            url : '../../controller/zip.php', 
            type : 'POST', 
            data: 'zip=' + $('#zip').val(), 
            dataType: 'json', 
            success: function(data){
                if(data.sucesso == 1){
                    $('#id').val(data.id);
                    $('#street').val(data.street);
                }
            }
       });   
return false;    
})
}); 

How can I change this so I can populate a select box.

Thanks

1
  • 1
    if(data.sucess == 1){ check you mistyped in your code Commented May 2, 2015 at 18:12

5 Answers 5

1

What is being passed back for a single address is a single object from which you can grab the information. When there are multiple responses you need to go through each of them and handle them.

When we look at MDN's article it shows that we need a parent <select> tag and then we need to populate the children. The process would look like this:

  • Find / create parent select
  • [Optional] Remove previous child <option> tags
  • Loop through responses
    • Create a new <option> element
    • Populate the <option> with the appropriate value and content
    • Append it to the parent <select>

Some things to be aware of, if you're clearing the previous addresses each time you get a response from the database you'll want to remove these previous <option>s. This can be done either by .empty() if there are no other children in the parent or starting with the parent <select> and removing all child <options>.

Sign up to request clarification or add additional context in comments.

Comments

1

Use this for adding items to select box dynamically:

var $selectBox = $('#selectboxId');
$selectBox.empty();
$.each(data, function (idx, val) {
    if (val.success) {
        $selectBox.append($('<option>', {
            value: val.id,
            text:  val.street
        }));
    }
});

2 Comments

I would suggest not doing the select query in the loop... store it in a variable outside the loop.... var $selectBox = $('#selectboxId').
Also want to point out that appending each item within the loop will cause a redraw on each iteration, would be better to push them into an array and append the final collection to the select element which will reduce it to one redraw
0

I would not encourage to do so; you're better off using a html-templating engine like mustache or handlebars.

Doing this kind of stuff in plain JS (string concatenation) is gross. It pollutes your sourcecode.

Anyways, this would do the trick to generate the necessary HTML:

function generateHTML(data){
    return data.reduce(function(o,n){
        return o+"<option value='"+n.id+"'>"+n.street+"</option>";
    },"");
}

Here is the Fiddle to play with. If you need to filter for success, you could add a filter()

function generateHTML(data){
    return data.filter(function(x){
        return !!x.success;
    }).reduce(function(o,n){
        return o+"<option value='"+n.id+"'>"+n.street+"</option>";
    },"");
}

You could easily use $("#selectBoxId").html(generateHTML(data)) to insert it to the DOM.

To fit it into your codebase, you should add it in the success handler:

success: function(data){
    function generateHTML(data){
        return data.reduce(function(o,n){
            return o+"<option value='"+n.id+"'>"+n.street+"</option>";
        },"");
    }
    $("select").html(generateHTML(data))
}

For the inner workings of Array.prototype.reduce() take a look at MDN and for Array.prototype.filter()

3 Comments

Depends on what you expected it to to. It shows "<option value='50'>Central One</option><option value='60'>Central Two</option>" in the developer console. The function simply generates the HTML as a string, which could be used further.
oh yeah sorry, Thanks, Think I got it now
It works in fiddle, I'm a total noob to js to I'm sorry for giving you girls trouble, I edited my post with the full script if anyone can help to change, cause I cant do it
0

If the JSON being returned is a list [{...}, ..., {...}], then you can use Array.forEach. Here is the success callback:

function(data) {
    data.forEach(function(item) {
        if (item.success) {
            // use item.id and item.street
        }
    });
}

If you have a <select> element, then you will want to be populating it with <options>, by appending an <option> element under each successful "if" branch in the forEach.

Comments

0

Assuming you already have the select element on the page and the data that is coming back from the server is an array of objects, this should work:

$.ajax({
    url : '../../controller/zip.php', 
    type : 'POST', 
    data: 'zip=' + $('#zip').val(), 
    dataType: 'json',
    success: function(data) {
        var $items  = [];
        $.each(data, function(street) {
            if(data.success === 1) {
                $items.push($('<option />').attr({
                    value: street.id
                }).text(street.street));
            }
        });
        $('#your-select-element').append($items);
    }
});

Notice this isn't setting the value for one option, it is creating <option> tags for each of the response's streets and appending them to a <select> element.

2 Comments

You like the $-sign? ;) btw. there is no need to cache the selection of the DOM-element, although it might be a good habit to do so, in this case it is not necessary.
I am an American, so yes, I like the $. In actuality, I use the $ to denote a cached jQuery object or a collection of jQuery objects, it makes for an easy visual reference. And yes, you are correct... I did not need to cache the select element in this instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.