Reputation: 763
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?
Upvotes: 4
Views: 20414
Reputation: 106385
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
).
Upvotes: 10
Reputation: 397
Just use an event listener:
$(document).on('click', 'input[name="rating"]', function() {
alert($(this).val());
});
JSFiddle: https://jsfiddle.net/59uquvfz/5/
Upvotes: 2
Reputation: 763
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
Upvotes: 1