Setting selected option in a partial view using jQuery

Viewed 81

The dropdown in my partial looks like this:

<select id="odStatus" class="odStatus">
  <option value="placed">Placed</option>
  <option value="shipped">Shipped</option>
  <option value"Completed">Completed</option>
  <option value="Cancelled">Cancelled</option> 
</selection>

In my orders.hbs, I retrieve data which includes an status string

$.get("/getOrderDetail/"+ id, (data)=>{
  // ...
  $('#orderDetail').find('#odStatus value=[' + data.order.status + ']').attr('selected', 'selected');
  // ...
}

I'm trying to get it so #odStatus shows what the status is, but I can't get to to work.

1 Answers

The immediate issue is because your selector assumes value is its own element, eg. <value>. Instead this should be an attribute selector targeting the option elements within the select and using prop() to update it, like this:

$('#orderDetail').find('#odStatus option[value="' + data.order.status + '"]').prop('selected', true);

However, it's worth noting that the logic can be simplified by just setting the val() on the select directly. Similarly the find() can be removed as it's redundant; id attributes have to be unique within the DOM. Try this:

$('#odStatus').val(data.order.status);
Related