Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find a select option with same value as select data-status and load option as "selected" with jquery

I am loading 2 separate ajax responses into a select dropdown and the select dropdown will have a data-status, what I am looking to achieve is to loop through the options and find the option that has the same value as the select data-status and load it as "selected".

Given my html code generated from my ajax call:

<select class="orderCurrentStatus" data-status="1215458">
  <option value="608653">Goods Received</option>
  <option value="608654">Purchase - Awaiting Payment</option>
  <option value="608655">Purchase - Payment Received</option>
  <option value="766705">EXCHANGE FEE PAID</option>
  <option value="838627">Order Refunded</option>
  <option value="1215458">Goods Dispatched</option>
  <option value="2322397">Paid - Custom Order Under Production</option>
  <option value="2384172">WRONG/INCOMPLETE ADDRESS!</option>
  <option value="2544576">Paid - Awaiting Pre-Ordered Items</option>
</select>

My attempt to make it work:

var order_status = $(".orderCurrentStatus").data("status");
var options = $(".orderCurrentStatus option");

if (options.val(order_status)) {
  $(this).attr("selected");
}

I just can't get it to work.

like image 920
Ricardo Alves Avatar asked Dec 08 '25 11:12

Ricardo Alves


1 Answers

You can just use the attribute selector [value="'+ order_status +'"] in order to select an option element that has a value equal to the variable order_status.

From there, set the selected property value to true or selected.

$('.orderCurrentStatus option[value="'+ order_status +'"]').prop('selected', true);

There were a couple issues with your initial code.

  • The variable this refers to the global object, in this case the window object, since there is no functional scope.
  • If you don't specify a value when using the .attr() method, the selected attribute value is returned. You need to specify a second parameter in order to set a value for the selected attribute. Specifying true or selected will work in your case. However, the .prop() method is better suited for this since you should be setting the property.

Additionally, if you want to do this for all select elements, then you could iterate over them, then retreive the data-status attribute value, and set the corresponding option element's selected property:

$('select').each(function () {
  var status = $(this).data("status");
  $(this).find('option[value="'+ status +'"]').prop('selected', true);
});
like image 151
Josh Crozier Avatar answered Dec 10 '25 01:12

Josh Crozier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!