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')
CodePudding user response:
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>