After some research and testing, I figured out both methods produce the same result. So I was just wondering what the difference is between:
function buildUrl() {
compType = document.querySelector('[name = "c-type"]');
compTypeValue = compType.value;
}
and
function buildUrl() {
compType = document.querySelector('[name = "c-type"]');
compTypeValue = compType.options[compType.selectedIndex].value;
}
<form id="custom-drop">
<select name="c-type" id="compressor-type">
<option value="screw">Screw</option>
<option value="scroll">Sroll</option>
<option value="centrifugal">Centrifugal</option>
<option value="piston">Piston</option>
</select>
</form>
I did read questions (this and this) related to this topic but I couldn't find any explanation for their differences.
CodePudding user response:
The select element keeps track on as well the value of the currently selected item and of the index of the selected items.
In your first example you access value of the currently selected option. In the second one you get the whole option element takeing the one at the index-postion that is selected. By accessing its value-member you then return its value.
By this you get the same result. However i would call the second approach hacky and not consider doing it.