简体   繁体   中英

Setting selected option in a partial view using jQuery

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM