简体   繁体   中英

jQuery won't append append option tags inside of select tag

I've got the following for my JS code.

$(document).ready(function () {
    var newOptions = "{'East': 'first','West': 'second', 'North': 'third'}";
    var option = $('#type_form');

    option.empty(); 

    $.each(newOptions, function(key, value) {
        option.append($('<option></option>').attr('value', value).text(key));
    });
});

HTML is as follows:

<select id="type_form">
    <option value="first">First</option> 
    <option value="second">Second</option> 
</select>

The JS console in chrome doesn't throw me any error. All of the option tags are removed, but they're not replaced with anything.

Any ideas?

newOptions should be an object not a string,

If you have it as a string then parse it to an object using JSON.parse() - for browsers like IE8 which does not have native JSON support you have to add a library like json2

$(document).ready(function () {
    var newOptions = {"East": "first","West": "second", "North": "third"};
    var option = $('#type_form');

    option.empty(); 

    $.each(newOptions, function(key, value) {
        option.append($('<option></option>').attr('value', value).text(key));
    });
});

You must parse your JSON string :

$.each(JSON.parse(newOptions), function(key, value) {

EDIT : My answer supposes that your string comes from elsewhere. If it's really a literal, it's better to write it as a literal object directly, as shown by Arun.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM