MVC / Bootstrap - Radio Button in group not selecting on initialisation

Viewed 1017

I have an edit form in my MVC application that has a Traffic Light Status.

When the form is initially opened, the check mark on the "lights" always set to "green" despite jQuery code to set otherwise.

All the code is firing, but it just does not set the initial state.

In this simplified example, if the Model's AlertLevel is set to "Red", the "tick" is still on the "green"

Markup

@Html.HiddenFor(model => model.AlertLevel)
<span class="btn-group RAGStatus" data-toggle="buttons">
    <label class="btn btn-success active " style="width:50px; height: 30px">
        <input type="radio" name="ragStatus" id="ragButton_Green" autocomplete="off" value="Green">
        <span class="glyphicon glyphicon-hidden unchecked"></span> <span class="glyphicon glyphicon-ok checked"></span>
    </label>
    <label class="btn btn-warning" style="width:50px; height: 30px">
        <input type="radio" name="ragStatus" id="ragButton_Amber" autocomplete="off" value="Amber">
        <span class="glyphicon glyphicon-hidden unchecked"></span> <span class="glyphicon glyphicon-ok checked"></span>
    </label>
    <label class="btn btn-danger" style="width:50px; height: 30px">
        <input type="radio" name="ragStatus" id="ragButton_Red" autocomplete="off" value="Red">
        <span class="glyphicon glyphicon-hidden unchecked"></span> <span class="glyphicon glyphicon-ok checked"></span>
    </label>
</span>

jQuery

$(function () {
    var status = $("#AlertLevel").val();
    $('#ragButton_' + status).prop("checked", true);
})

Model

public class DeptStatus
{
    public string AlertLevel { get; set; }
}

CSS (for the glyph icon display)

.RAGStatus .checked {
    display: none;
}

.RAGStatus .active .checked {
    display: inline-block;
}

.RAGStatus .active .unchecked {
    display: none;
}

Update

In a follow on jQuery function (removed from example), if I do var ragStatus = $('input[name=ragStatus]:checked').val(); then it returns "Red"

3 Answers
Related