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

javascript find select option index based on option text

I am trying (and failing) to check if an option exists in the select element, based on the option’s text:

<select id="select">

    <option value="13">I1</option>
    <option value="23">I21</option>
    <option value="954">I33</option>

</select>

var select = document.getElementById('select');

findInvoice(44);

function findInvoice(value_option) {
    
    let x = select.value = [...select.options].findIndex(option => option.text === 'I' + value_option);
    console.log(x);
    
}

This does output the -1 value for the index, but it also sets the option index in the select form as well. I strictly only want to check if the index exists or not without selecting it.

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

>Solution :

You need to remove select.value when assign value to x

Change:

let x = select.value = [...select.options].findIndex(option => option.text === 'I' + value_option);

to:

let x = [...select.options].findIndex(option => option.text === 'I' + value_option);
var select = document.getElementById('select');

findInvoice(44);

function findInvoice(value_option) {
    
    let x =  [...select.options].findIndex(option => option.text === 'I' + value_option);
    console.log(x);
    
}
<select id="select">

    <option value="13">I1</option>
    <option value="23">I21</option>
    <option value="954">I33</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