Reputation: 47
I'm trying to set default select value of select2 options but it was not working ...can anyone help me .?
here is my controller
public ActionResult OrderAcceptanceDetails()
{
var res = Db.CustomerDetails.ToList();
Session["cust"] = new SelectList(res, "CUSTCODE", "CUSTCODE");
var yearlist = Db.Years.ToList();
Session["year"] = new SelectList(yearlist, "Year1", "Year1");
//var spresult = Db.Database.SqlQuery<OADetail>("Sp_OADetails_GetAll").ToList<OADetail>();
return View();
}
here is my view
<div class="col-md-3">
<p>
@Html.DropDownList("Year", Session["year"] as SelectList, "-- Select Year-- ", htmlAttributes: new { @class = "selectpicker", data_style = "select-with-transition" })
</p>
</div>
here is my javascript
<script type="text/javascript">
$(document).ready(function () {
$("#Year").children("option:last-child").attr("selected",trues);
})
</script>
i want to select last child of dropdown value which are come from database.please tell me how's this possible.?
Upvotes: 0
Views: 804
Reputation: 20039
Try using the trigger property for this: doc
$(document).ready(function () {
$("#Year").select2({ width: '75px' });
$("#Year").children("option:last-child").attr("selected", true).trigger('change');
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<select id="Year">
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
</select>
Upvotes: 1