-1

I have appended country names and iso codes from a php routine to option value of $('#innerSelect')

$('#innerSelect').append("<option value=" + country['data'][i]['code'] + ">" + country['data'][i]['name'] + "</option>");

However, I'm now wondering is there a way to declare when I want the code and when I want the name?

For example

countryName = $('#innerSelect option:selected').val(name)
countryCode = $('#innerSelect option:selected').val(code)

I have future API calls where some need the name as a parameter and some need the code, so it would be nice to be able to tell JS which one to use based on the $('#innerSelect')

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Does this answer your question? [Get SELECT's value and text in jQuery](https://stackoverflow.com/questions/12614308/get-selects-value-and-text-in-jquery) – pilchard Nov 02 '22 at 21:17

1 Answers1

0

You can use .val() to get the value, and .text() to get the name (ie what you see in the select)

console.log($("#innerSelect option:selected").val(),$("#innerSelect option:selected").text())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="innerSelect">
 <option value="US">USA</option>
 <option value="CA">CANADA</option>
</select>
imvain2
  • 15,480
  • 1
  • 16
  • 21