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>

2
  • 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) Commented Mar 4, 2022 at 11:50
  • Maybe this is what you are after: Get button that caused submit Commented Mar 4, 2022 at 12:11

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.