I have a form with two submit buttons with the same name
but different value
s. If I submit the form with a GET
action, no JS, the name and value of the the button triggering the submission are included in the URL parameters. However, when I listen to the submit
event, the value
of the submit button does not seem accessible in the same way other inputs are.
Why is the submit button value not included in the form data when accessing it from JS?
Reason
I have a page where I want to make a form where I let the browser do the most of the work. So, I don't want to have to attach click event listeners to each button when the form can emit a submit
event, which it does.
Snippets
MCVE:
const form = document.querySelector('form')
const output = document.querySelector('ul')
form.addEventListener('submit', function (event) {
event.preventDefault()
const item = document.createElement('li')
item.innerText = `Pressed button "${form.foo.value}": text field contains "${form.bar.value}"`
output.appendChild(item)
})
<form>
<input type="text" name="bar" value="sample input" />
<button type="submit" name="foo" value="a">Action a</button>
<button type="submit" name="foo" value="b">Action b</button>
</form>
<ul>
</ul>
MCVE but with FormData
:
const form = document.querySelector('form')
const output = document.querySelector('ul')
form.addEventListener('submit', function (event) {
event.preventDefault()
const fd = new FormData(form)
const item = document.createElement('li')
item.innerText = `Pressed button "${fd.getAll('foo')}": text field contains "${fd.getAll('bar')}"`
output.appendChild(item)
})
<form>
<input type="text" name="bar" value="sample input" />
<button type="submit" name="foo" value="a">Action a</button>
<button type="submit" name="foo" value="b">Action b</button>
</form>
<ul>
</ul>