1

I have the following code (HTML) :

<select name="size"    id="size">
Cat Dog

How to get (“Dog’’) selected option in javaScript?

<select name="animal" id="animal">
Cat Dog

and how to click button using javascript?

<fieldset id="add-remove-buttons">

My html is:

<select name="size" id="size">
  <option value="72452">Cat</option>
  <option value="72453">Dog</option>
</select> 
Greedo
  • 3,438
  • 1
  • 13
  • 28
  • I have the following code (HTML) : How to get (“Dog’’) selected option in javaScript? and how to click button using javascript?
    – martin_wp30 Feb 24 '21 at 09:18
  • Does this answer your question? [How do I change an HTML selected option using JavaScript?](https://stackoverflow.com/questions/10911526/how-do-i-change-an-html-selected-option-using-javascript) – Yosvel Quintero Feb 24 '21 at 09:31

2 Answers2

0

If you know the value of your option, you can just force it in the value field

document.getElementById("size").value="72453"
<select name="size" id="size">
  <option value="72452">Cat</option>
  <option value="72453">Dog</option>
</select> 
Greedo
  • 3,438
  • 1
  • 13
  • 28
0

You can find your <select> tag by its id and save it in a variable using getElementById() method of a document object like this:

let selectSize = document.getElementById('size');

Then you can call the selectSize.option key which will return you an HTMLOptionsCollection object that has multiple useful properties such as length. You can then just call for the needed key in that object. For example, if i want to find Dog in your select field i'll do the following:

let selectSize = document.getElementById('size');
let keys = selectSize.options;

for (key of keys) {
    if (key.innerHTML === 'Dog') {
        console.log('Found a dog at index ', key.index, ' its value is ', key.value);
    }
}

Which will print out the following result:

Found a dog at index  1  its value is  72453

More about Document object

More about getElementById()

More about for...of

qurquru
  • 198
  • 2
  • 12