Am having a select element containing bunch of options with an attribute of value, what i want to do is to grab one of those options by its Value attribute but the value attribute needs to have a data equal to the data coming from my variable the code below will demonstrate what i mean
<option value="8">Preston Sharpe</option>
<option value="9">Margaret Cochran</option>
const serviceID = 8;
document.querySelector(`[value="${serviceID}"]`);
so what i want is to grab the option with a value of whatever equals to the variable of serviceID
Am having a select element containing bunch of options with an attribute of value, what i want to do is to grab one of those options by its Value attribute but the value attribute needs to have a data equal to the data coming from my variable the code below will demonstrate what i mean
<option value="8">Preston Sharpe</option>
<option value="9">Margaret Cochran</option>
const serviceID = 8;
document.querySelector(`[value="${serviceID}"]`);
so what i want is to grab the option with a value of whatever equals to the variable of serviceID
Share Improve this question asked Feb 5 at 16:41 Zakaria HilaliZakaria Hilali 114 bronze badges 5 |1 Answer
Reset to default 0You already partly solved it when you found the option you wanted. The further step is to set the value
of the parentNode
, which is your select
tag to this option.
const serviceID = 8;
let myOption = document.querySelector(`[value="${serviceID}"]`);
myOption.parentNode.value = myOption.value;
<select>
<option value="7">John Doe</option>
<option value="8">Preston Sharpe</option>
<option value="9">Margaret Cochran</option>
</select>
EDIT
In the question's comment section you said the selector returns with null (or undefined). If this is the situation, then, given the fact that the selector is correct as you can test in this snippet, your select
or its option
does not exist yet or does not have the value of 8 yet. If that's the case, then your Javascript needs to be running at the time when the structure was properly initialized.
document.querySelector(`option[value="${serviceID}"]`);
– AmirHossein_Khakshouri Commented Feb 5 at 16:50