0

I'm making an ajax call to retrieve some JSON objects. I get them right. but the problem is when I want to create a select element from returned JSON, it doesn't create one or seemed to be.

My JavaScript so far:

jQuery("#make").change(function () {
    var value = $(this).val();
    jQuery.getJSON("<?php echo site_url('ajax/get/models'); ?>", {
        makeId: value
    },

    function (data) {
        if (data != "false") {
            var modelsSelect = jQuery.createElement('select');
            var modelsOptions = "";
            var id;
            var model
            jQuery.each(data, function () {
                jQuery.each(this, function (key, value) {
                    if (key == "id") {
                        id = value;
                    } else {
                        model = value;
                    }
                });
                modelsOptions += "<option value=" + id + ">" + model + "</option>"
            });
            modelsSelect.innerHTML = modelsOptions;
            jQuery("#model").html = modelsSelect;
        } else {
            alert("false");
        }
    });
});

my returned JSON Format:

Object { id="28", model="test model"}

There could be n number of JSON objects in returned response from ajax call.

2
  • One small side note... trying to set the .innerHTML of a <select> element in older Internet Explorer browsers will fail. IE8 and below for sure will fail - I can't remember if this was fixed in IE9 or IE10. Commented Nov 9, 2013 at 15:04
  • @scunliffe, so what should i use? Commented Nov 9, 2013 at 16:07

2 Answers 2

2

There is no createElement method in jQuery

jQuery.createElement should be document.createElement


Also no need to loop over the objects' properties, you can access them by the key directly

jQuery.each(data, function (index, item) {
    modelsOptions += "<option value=" + item.id + ">" + item.model + "</option>"
});
Sign up to request clarification or add additional context in comments.

Comments

1

Change this

jQuery("#model").html = modelsSelect;

to

jQuery("#model").html(modelsSelect);


Reference

.html()

1 Comment

still doesn't replace the empty <select id="model"> with the generated one. is my code right?when ajax result is returned there could be n objects with the format above.

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.