Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS specify which option value to to call

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading