Get value of radio button with onChange for javascript function

12,134

Solution 1

I got it. Pretty simple. Just added "value" in the brackets:

<input type="radio" name="rating" value="1" onchange="getRating(value)> 1
<input type="radio" name="rating" value="2" onchange="getRating(value)> 2
<input type="radio" name="rating" value="3" onchange="getRating(value)> 3

Solution 2

One possible approach is passing this (an element an event is triggered on) into getRating as its argument. Like this:

function getRating(el) {
  console.log(el.value);
}
<input type="radio" name="rating" value="1" onchange="getRating(this)"> 1
<input type="radio" name="rating" value="2" onchange="getRating(this)"> 2
<input type="radio" name="rating" value="3" onchange="getRating(this)"> 3

As alternative, you can pass element's value into a function directly:

HTML

<input type="radio" name="rating" value="1" onchange="getRating(value)" /> 1

<!-- and so on -->

JS

function getRating(ratingValue) {
  // process the given value
}

... using the fact that EventHandler's Lexical Environment contains element itself (and therefore its properties are accessible directly, without explicit reference to this).

Solution 3

Just use an event listener:

$(document).on('click', 'input[name="rating"]', function() {
    alert($(this).val());
});

JSFiddle: https://jsfiddle.net/59uquvfz/5/

Share:
12,134
BlueCat
Author by

BlueCat

Updated on June 09, 2022

Comments

  • BlueCat
    BlueCat almost 2 years

    I have some radio buttons and I want to get their values with onChange for my function.

    <input type="radio" name="rating" value="1" onchange="getRating(???)> 1
    <input type="radio" name="rating" value="2" onchange="getRating(???)> 2
    <input type="radio" name="rating" value="3" onchange="getRating(???)> 3
    

    my function:

    function getRating(ratingValue) {
         $.ajax({
              url: '/Rating/Create',
              type: "POST",
              data: {rating: ratingValue.value },
         success: function (data) {
              //Successmessage
              console.log(ratingValue);
         },
         error: function (xhr) {
              //Errormessage
        }
    

    How can I get the value of the radio button?