Select a value of selectbox using javascript properly?

89 views Asked by At

I'm trying to select a specific value of selectbox using javascript. I planned to use jQuery to select an element, but somehow the site I'm trying to automate blocked it or not using jQuery.

So, I slected an element using document.querySelector();. Like below.

document.querySelector("#softBoardListLayer > div:nth-of-type(2) > div:nth-of-type(1) > table > tbody > tr:nth-of-type(1) > td > select").selectedIndex = 01;

It does work. After running this javascript, Seleectbox shows the value I selected using this command.

but when I hit confirm button at the bottom of the website to go to the next page, website says that I haven't selected anything.

here is the selectbox part of html.

<select data-v-f6ebec28="" name="" id="">
    <option data-v-f6ebec28="" value="">Select...</option>
    <option data-v-f6ebec28="" value="01">Seoul</option>
    <option data-v-f6ebec28="" value="02">Busan</option>
    <option data-v-f6ebec28="" value="03">Jeju</option>
</select>

Is there any way to select the value of selectbox properly?

2

There are 2 answers

5
bhumin On

you have to very small changes in your HTML code.
first, you have to set the id of the select tag.
then, you have to put that id in document.querySelector("#select-option") statement.

document.querySelector("#select-option").value = '01';
<select data-v-f6ebec28="" name="" id="select-option">
    <option data-v-f6ebec28="" value="">Select...</option>
    <option data-v-f6ebec28="" value="01">Seoul</option>
    <option data-v-f6ebec28="" value="02">Busan</option>
    <option data-v-f6ebec28="" value="03">Jeju</option>
</select>

1
Davi On

You have to set the selected property on the <option> element. Not only does this change the UI, it also ensures you get the correct value back from asking the element's .value property:

function setSelected(selectEl, valueToSelect) {
  var options = selectEl.children, i = 0;
  for (; i < options.length; i += 1) {
    if (options[i].value === valueToSelect) { // <-- if the option has the value
      options[i].selected = 'selected'; // <-- select it
    } else {
      options[i].selected = null; // <-- otherwise deselect it
    }
  }
}



var select = document.querySelector('select');
setSelected(select, '03');

console.log('Selected value is:', select.value);
<select data-v-f6ebec28="" name="" id="">
    <option data-v-f6ebec28="" value="">Select...</option>
    <option data-v-f6ebec28="" value="01">Seoul</option>
    <option data-v-f6ebec28="" value="02">Busan</option>
    <option data-v-f6ebec28="" value="03">Jeju</option>
</select>