NotYourType___
NotYourType___

Reputation: 31

Get value using jquery from button clicked

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>

Upvotes: 0

Views: 112

Answers (1)

mplungjan
mplungjan

Reputation: 178421

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>

Upvotes: 1

Related Questions