Hiba
Hiba

Reputation: 251

How to set value of drop down in jquery?

I am working on MVC 5 and i get the value from action method for drop down and i got these value successfully but i want to set value by default. How can i do this.

$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        var markup = "<option value>@Resources.WorkFlowTemplate</option>";
        for (var x = 0; x < data.length; x++) {
            markup += "<option value=" + data[x].templateId + ">" + data[x].templateName + "</option>";

        }
        $("#TemplateId").html(markup).show();
    }
});

TemplateId is the id of drop down list of Html helper.

Upvotes: 1

Views: 4852

Answers (2)

vijayP
vijayP

Reputation: 11502

As suggested by ChiranjeeviIT; you can add selected attribute to an option while building dropdown HTML. Also once HTML set, you can preselect dropdown via jQuery as:

 $("#TemplateId").val("someValue");

where this "someValue" is value of an option of that drop down box as :

<option value="someValue">Some Name</option>

Upvotes: 0

Dragon
Dragon

Reputation: 1088

I assume you have a value that you set as default i.e 1 here, and you want to set as selected.

  $(document).ready(function () {
         $('#TemplateId').find('option[value="1"]').attr('selected','selected');
      });

Upvotes: 3

Related Questions