0

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())
  })
})
Jerry
  • 366
  • 4
  • 22
  • 1
    Arrow functions `=>` does not work well with jQuery. `$(this)` refer to the window not the element itself. Use normal function like this > `$("input:radio").click(function(){})` – Always Helping Aug 12 '20 at 02:47
  • Does this answer your question? [Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)](https://stackoverflow.com/questions/27670401/using-jquery-this-with-es6-arrow-functions-lexical-this-binding) – Always Helping Aug 12 '20 at 02:52

3 Answers3

2

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>
dave
  • 62,300
  • 5
  • 72
  • 93
0

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

bovine
  • 1
0

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

$('input[name="name_of_your_radiobutton"]:checked').val();
Jerry
  • 366
  • 4
  • 22