Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of radio button with onChange for javascript function

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?

like image 222
BlueCat Avatar asked Oct 28 '25 14:10

BlueCat


2 Answers

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).

like image 101
raina77ow Avatar answered Oct 31 '25 04:10

raina77ow


Just use an event listener:

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

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

like image 26
Matt D Avatar answered Oct 31 '25 05:10

Matt D