Reputation: 67
I have list of radio button with true and false values. I want to get the value on change click event so I can use it for displaying conditional label. If its true; I'll show a label if its false different label. Its a list of items so I am looping through it..
here is what I have so far:
Model:
public List<bool>answerValues { get; set; }
View:
<td>
@Html.RadioButtonFor(model => model.answerValues[i], true, new { id =
"TrueValueID", @onclick = "buttonValue()"}) True
@Html.RadioButtonFor(model=> model.answerValues[i], false, new { id =
"FalseValueID", @onclick ="buttonValue()" }) False
</td>
JavaScript
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function buttonValue(e) {
alert(e.value);
}
</script>
In the Controller - Action method (Get), I want to get the true/ false value so I can show/hide based on values.
I am not familiar with Razor / MVC. any help will be highly appreciated!
Upvotes: 0
Views: 9360
Reputation: 1782
I hope this will help you.
Razor Code
here we can set common class on radio button to bind on change event in js.
<td>
@Html.RadioButtonFor(model => model.answerValues[i], true, new { id =
"TrueValueID", @class="rdbtnanswervalue"}) True
@Html.RadioButtonFor(model=> model.answerValues[i], false, new { id =
"FalseValueID", @class="rdbtnanswervalue" }) False
</td>
Js Code
<script>
$(function () {
$(".rdbtnanswervalue").on("change", function () {
// for current value
alert($(this).val());
// for all radio button with same class uncomment below code.
//$(".rdbtnanswervalue").each(index, ele)
//{
// // get value and perfom action acordingly.
// alert($(ele).val())
//}
})
})
Upvotes: 1
Reputation: 16575
You missed this
, should use buttonValue(this)
:
<td>
@Html.RadioButtonFor(model => model.answerValues[i], true, new { id =
"TrueValueID", @onclick = "buttonValue(this)"}) True
@Html.RadioButtonFor(model=> model.answerValues[i], false, new { id =
"FalseValueID", @onclick ="buttonValue(this)" }) False
</td>
In action:
function buttonValue(e) {
alert(e.value);
if (e.value === 'true') {
alert('it is true');
} else {
alert('it is false');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="test" value="true" onclick="buttonValue(this)" />
<input type="radio" name="test" value="false" onclick="buttonValue(this)" />
I want to get the true/ false value so I can show/hide based on values
Radio button return on
if checked, so show label if value return on
else show another label. Also you can set value
for radio button like <input type="radio" value="true"...
or boolean.
Upvotes: 3
Reputation: 836
You should use name attribute for all radio buttons.
and then in JQuery
$('input:radio[name=RADIO_NAME]').change(function () {
var value = $('input:radio[name=RADIO_NAME]:checked').val();
switch(value).....
});
Upvotes: 0