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.
>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>