Tim Blount
Tim Blount

Reputation: 35

How to get selected option with raw javascript

HTML

<form>
  <select name="select">
     <option value="option1">Option 1</option>
     <option value="option2">Option 2</option>
  </select>
  <input type="submit" onclick="processForm(this.form)">
</form>

JS

function processForm(form) {
  console.log(form)
}

I can successfully get the form as HTMLElement but cannot seem to find easy way to get selected value

Upvotes: 1

Views: 870

Answers (1)

elzi
elzi

Reputation: 5672

Since you're sending the form object itself on submit, getting data is easy in vanilla JS. Modify your function to:

function processForm(form) {
  var selected = form.select
  console.log(selected.value)
}

Note that select is not some special property of the form, it's just because that's what you gave the name attribute for the select element.

Upvotes: 3

Related Questions