necrofish666
necrofish666

Reputation: 75

Can't get the value of @Html.RadioButtonFor using Jquery, checked attribute not changing

Using MVC 5, I have a radio button for a Boolean property on a Razor view, a simple yes or no selection, like so:

<td class="warning">@Html.LabelFor(model => model.HeartCondition)</td>
<td class="info">Yes @Html.RadioButtonFor(model => model.HeartCondition, true, new { @class = "radio" })</td>
<td class="info">No @Html.RadioButtonFor(model => model.HeartCondition, false, new { @class = "radio"})</td>

<a role="button" class="btn btn-primary btnnav" id="SaveParQ">Save & Next</a>

When I pass a true or false value to the view, the corresponding radio button is selected, and has the checked="checked" attribute. I then want to save the value without having to reload the page, which I'm trying to do using jquery, and this is where the problem lies. If I pass a true value to the view, the "yes" radio button is selected and has the checked attribute, but when I click the "no" radio button, the "no" button does get selected, but the checked attribute is still on the "yes" button, and doesn't change to the "no" button, which is what I thought it would've done.

My jquery looks like this:

//Save ParQ
$("body").on("click", "#SaveParQ", function (e) {
    preventDefaultAction(e);
    var url = GetUrlPath() + "/PreAssessment/SaveParQ";
    var parQId = $("#ParQId").val();
    var heartCondition = false;
    if ($("input[name='heartCondition']:checked").val()) {
        heartCondition = true;
    }

    var viewModel = new ParQViewModel(parQId, heartCondition);
    $.ajax({
        type: "POST",
        cache: false,
        url: url,
        data: JSON.stringify(viewModel),
        contentType: 'application/json; charset=utf-8',
        success: function (result) {
            if (result.success === true) {
                showFullScreenLoadMask(false);
                $("#ParQId").val(result.ParQId);
            }
        },
        error: function (responseText, textStatus, errorThrown) {
            alert('Error - ' + errorThrown);
        }
    });
});

I'm not sure if my jquery is right, but if it is, it doesn't register me changing "yes" to "no", because the checked attribute stays on the original element. Can anyone help with the right way to achieve what I'm trying to do?

Upvotes: 1

Views: 4025

Answers (1)

user3559349
user3559349

Reputation:

Remove the following lines of code

var heartCondition = false;
if ($("input[name='heartCondition']:checked").val()) {
    heartCondition = true;
}

and replace with

var heartCondition = $("input[name='HeartCondition']:checked").val();

which will set the value to either true or false based on the selected radio button.

Upvotes: 2

Related Questions