0

I'm building a form consisted of button. I want to get value from a highlighted button being sent to a parameter when submit button is clicked, but the problem is I only found a way to sent value from a radio button. Is there any equivalent way to do this?

I know this is only applicable for radio button, so I'm searching an equivalent queryselector that will give exact action like code below but for button

document.querySelector('input[name=customButton]:checked').value
<button type="button" class="btn" id="customButton1" name="customButton" value="1">
<label for="customButton1">Excellent</label>

<button type="button" class="btn" id="customButton2" name="customButton" value="2">
<label for="customButton2">Not good</label>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • What's a *"highlighted button"* given that it's not the submit button (as *"when submit button is clicked"*) and won't be the button in focus (which will be the submit button) – freedomn-m Mar 04 '22 at 11:50
  • *Maybe* this is what you are after: [Get button that caused submit](https://stackoverflow.com/questions/2066162/how-can-i-get-the-button-that-caused-the-submit-from-the-form-submit-event) – freedomn-m Mar 04 '22 at 12:11

1 Answers1

1

You cannot convert a radio directly to a button like you did. The HTML is not valid

You can style a radio like a button or do this

document.getElementById("myForm").addEventListener("click",function(e) {
  const tgt = e.target.closest("button")
  if (tgt.matches(".customButton")) document.getElementById("customButton").value = tgt.value
})
<form id="myForm">
<input type="hidden" name="customButton" id="customButton" value="" />
<button type="button" class="btn customButton" value="1">Excellent</button>
<button type="button" class="btn customButton" value="2">Not good</button>
</form>
mplungjan
  • 169,008
  • 28
  • 173
  • 236