Question:
How do I get the answers from a HTML form
to be sent to a javascript file and set a variable to be put in a function
Repl link:
https://replit.com/@JohnnySuriano/JohnnySites
The form looks something like this (Not in actual project):
<form name="form">
<select name=''color>
<option>Red</option>
<option>Blue</option>
<option>Green</option>
</select>
<form>
JS
function myFunction() {
console.log(result)
//I want the variable 'result' to the result to the form above
Thanks for any help provided
You can get the result of aselect
element by using selectElement.value
.
You’ll also need a submit
button so the form can be submitted.
<form>
<!-- select-stuff-here !-->
<button>Submit</button>
</form>
and you can listen to submittions by
formElement.addEventListener("submit", (e) => {
e.preventDefault()
console.log(selectElement.value)
})
Here is how you can get data from this form:
<form name="form" id="form">
<select name='color'>
<option>Red</option>
<option>Blue</option>
<option>Green</option>
</select>
<form>
function myFunction() {
let form = document.getElementById("form");
const formData = new FormData(form);
const data = Object.fromEntries(formData); // { color: 'Red' }
}