1

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"]

4
  • provide a json result from your $.getJSON function, simply do console.log(JSON.stringify(data))and add the result to the question. Commented Feb 4, 2014 at 8:03
  • any error in the browser's console? Commented Feb 4, 2014 at 8:06
  • No Erroers in console. there is an error but that points to my js in my one view js file. not relating to this one. Commented Feb 4, 2014 at 8:18
  • If data is an array of strings, it will not have a property .text Commented Feb 4, 2014 at 8:22

4 Answers 4

1

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.

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

Comments

0

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.

2 Comments

I downvoted because I assumed you were only changing the syntax (which was already perfectly valid). If you had of offered an explanation I would have noticed the lack of the .data property
Thank you. I noticed the string of comments after my submission. I will offer an explanation.
0

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.

Comments

0

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/

Comments

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.