Luiz Gustavo
Luiz Gustavo

Reputation: 37

Get the value of a radio input button using jQuery

I'm trying to get the value of the radio button that has been clicked, and I'm using the code below. But I'm getting the following error:

jquery-3.5.1.min.js:2 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

The code that I have used:

$(()=> {
  $("input:radio").click(()=>{
    alert($(this).val())
  })
})

Upvotes: 0

Views: 77

Answers (3)

Jerry
Jerry

Reputation: 406

Just use the easier built in :checked parameter with the val() function

$('input[name="name_of_your_radiobutton"]:checked').val();

Upvotes: 0

dave
dave

Reputation: 64657

The issue is that you are using an arrow function, so this refers to whatever it refered to outside of that function (it won't refer to the clicked element).

$(()=> {
  $("input:radio").click(function(){
    alert($(this).val());
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label for="demo">
    <input type="radio" name="demo" value="a"/> A
</label>
<label for="demo">
    <input type="radio" name="demo" value="b"/> B
</label>
<label for="demo">
    <input type="radio" name="demo" value="c"/> C
</label>
<label for="demo">
    <input type="radio" name="demo" value="d"/> D
</label>

Upvotes: 2

bovine
bovine

Reputation: 1

The error message has nothing to do with the code you provided, it is recommended to check the Chrome plugin or other codes

Upvotes: 0

Related Questions