Rohan Büchner
Rohan Büchner

Reputation: 5393

Jquery/Javascript refactoring basics

I still consider myself quite a novice when it comes to JavaScript/JQuery. How would I go about refraction this into a method/function I can re-use.

$.getJSON('@Url.Action("GetLabNames", "Micro")', null, function(j) {
    var options = '';

    for (var i = 0; i < j.length; i++) {
        if (elem.value == j[i].Description) {
            options += '<option selected="selected" value="' + j[i].Lab_LN_ID + '">' + j[i].Description + '</option>'
        } else {
            options += '<option value="' + j[i].Lab_LN_ID + '">' + j[i].Description + '</option>'
        }
    }

    $(elem).html(options);

    $(elem).multiselect({
        multiple: false,
        header: "Select an option",
        noneSelectedText: 'Lab Name',
        selectedList: 1,
        minWidth: 150
    });

});

I was hoping to have a function something like

 CreateMultiSelect(elem, controller, action, text, value);

But I can't pass object properties into the function eg (Lab_LN_ID , Description), and making them text (eg 'Lab_LN_ID', 'Description'), clearly doesn't work, and I'm not sure how to go about it?

Upvotes: 1

Views: 150

Answers (1)

Betty
Betty

Reputation: 9189

Why not return a json object with common property names? It would simplify this greatly.

eg

[{Text: 'text', Value: '1'},{Text: 'text', Value: '1'}]

Then you can create all your option items very easily.

    $('<option />', { value: item.Value, text: item.Text });

Upvotes: 2

Related Questions