Zapnologica
Zapnologica

Reputation: 22556

JavaScript not adding option to select element

Here is my script:

 <script>
$(function () {
    $("#selectUser").on("change", function () {
        alert('button clicked');

        var selectedUser = $(this).val();

        if (selectedUser != null && selectedUser != '') {
            $.getJSON('@Url.Action("GetAUsersRegisteredRoles")' + '/' + selectedUser, function (data) {

                var dualSelect = $('#dualSelectRoles1');
                dualSelect.empty();

                $.each(data, function (index, data) {
                    dualSelect.append($('<option/>', {
                        value: index,
                        text: data.text
                    }));
                });
            });
        }           
    }
    );
});

here is the html element that I am trying to update:

 <label>Select User</label>
    <span class="field">
        <select name="selectUser" id="selectUser">
            <option value="">Choose One</option>
            @foreach (var item in Model.Users)
            {
                <option value="@item.Id">@item.UserName</option>
            }
        </select>
    </span>

<label>Select Roles</label>
    <span class="dualselect">
        <select name="RolesSelect" id="dualSelectRoles1" multiple="multiple" size="10">
            <option value="">Admin</option>
            <option value="">User</option>
            <option value="">Technical</option>
            <option value="">Sales</option>
            <option value="">End User</option>
            <option value="">Cient</option>
        </select>
        <span class="ds_arrow">
            <span class="arrow ds_prev">&laquo;</span>
            <span class="arrow ds_next">&raquo;</span>
        </span>
        <select name="select4" multiple="multiple" id="dualSelectRoles2" size="10">
            <option value=""></option>
        </select>
    </span>

Now my script works so far:

when I click on the user select my alert popups up then it calls my action method and it returns the json.

It then clears my select element to make it blank but it then doesn't add any elements? What am I doing wrong?

[Edit]

Here is my output of console.log(JSON.stringify(data)): ["Admin","Technical"]

Upvotes: 1

Views: 159

Answers (4)

Ashish Kumar
Ashish Kumar

Reputation: 3039

You are doing a very small mistake there. Try this:

var data = {text : "test"};
var dualSelect = $('#dualSelectRoles1').empty();

$.each(data, function (index, obj) {
    dualSelect.append($('<option/>', {
        value : index,
        text : obj
    }));
});

Working Example: http://jsfiddle.net/ashishanexpert/cG764/7/

Upvotes: 0

Mehran Hatami
Mehran Hatami

Reputation: 12961

There are some problems in your code which are important to consider. first of all, although it doesn't cause any direct problem or error, but it is no accepted to create a select that its options have no value, like yours. So you better change nodes like:

<option value="">Admin</option>

to

<option>Admin</option>

about your javascript code, if you are expecting to your data to be like:

data = [{text:"Admin"}, {text:"Technical"}];

then it makes sense to create you options like:

$('<option/>', { value: index, text: data0.text })

But as you see your data is simply an array of strings, so all the related part in your code is (but I have changed it):

var data = ["Admin","Technical"];
var dualSelect = $('#dualSelectRoles1');
dualSelect.empty();

$.each(data, function (index, value) {
    dualSelect.append($('<option/>', {
        value: index,
        //text: data.text
        text: value
    }));
});

As you see I have changed the argument name data to value in each iterator function, although it doesn't make any problem to use repeated names in different closures but it lowers legibility of your code.

Upvotes: 0

happyD
happyD

Reputation: 146

Instead of

dualSelect.append($('<option/>', {
    value: index,
    text: data.text
}));

Try

dualSelect.append('<option value="'+index+'">'+data+'</option>');

The fiddle.

This is due to the getJson call returning an array of strings (e.g. ['a', 'b', ... ] ) rather than the object you expected (e.g. {'text': 'a', 'text': 'b'}). As such the array of strings does not have a property 'text' and will return undefined.

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

data is an array of strings, so won't have a property text. Use the value on its own - from a naming standpoint it would be good to change the name of data within the each loop too to something more indicative of what the variable represents:

$.each(data, function (index, val) {
    dualSelect.append($('<option/>', {
        value: index,
        text: val
    }));
});

Here is an example Fiddle of the above.

Upvotes: 1

Related Questions