简体   繁体   中英

Select2: How to select the “value” of an option?

I have a dropdown of countries:

<select size="1" class="product-load-port" name="product-load-port">
  <option value=""></option>
  <option value="AF">Afghanistan</option>
  <option value="AX">Aland Islands</option>
  <option value="AL">Albania</option>
  <option value="DZ">Algeria</option>
</select>

How to select the value of the chosen country, ex. if Albania was chosen, value should be "AL"?

I'm trying to do that with

$('select.product-load-port').select2('data')[0].text;

but it gives me "Albania" as a value.

You can do that by simply accessing the .val() of the underlying native <select> element:

$('select.product-load-port').val()

You can also proxy it through .select2().val() , but that's not really necessary anyway:

$('select.product-load-port').select2().val()

 $('select.product-load-port').select2(); $('#getSelectedValue').on('click', function() { console.log($('select.product-load-port').val()); });
 <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/css/select2.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.12/js/select2.min.js"></script> <select size="1" class="product-load-port" name="product-load-port"> <option value=""></option> <option value="AF">Afghanistan</option> <option value="AX">Aland Islands</option> <option value="AL">Albania</option> <option value="DZ">Algeria</option> </select> <button type="button" id="getSelectedValue">Log selected value to console</button>

 <select size="1" class="product-load-port" name="product-load-port"> <option value=""></option> <option value="AF">Afghanistan</option> <option value="AX">Aland Islands</option> <option value="AL">Albania</option> <option value="DZ">Algeria</option> </select> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> $('select').on('change', function() { alert( this.value ); }); </script>

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