dasdasd dasdasd - 4 months ago 32
jQuery Question

Show/Hide on click dropdownlist MVC 4

I have this view:

<div class="editor-field">Best</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Best, new List<SelectListItem>
{
new SelectListItem { Value = "Best3", Text = "Best 3"},
new SelectListItem { Value = "Best5", Text = "Best 5"},
new SelectListItem { Value = "Best10", Text = "Best 10"},
new SelectListItem { Value = "XBest", Text = "X Best"}
},
new { @class = "myselect" })
@Html.ValidationMessageFor(model => model.Best)
</div>
<div class="editor-label">X</div>
<div class="editor-field">
@Html.EditorFor(model => model.X)
@Html.ValidationMessageFor(model => model.X)
</div>


And I have this jquery:

$('#Best').on('change', function () {
if ($(this).val() != "XBest") {
$('#X').hide(); //invisible
$('#X').attr('disabled', 'disabled'); // disable
} else {
$('#X').show(); //visible
$('#X').removeAttr('disabled'); // enable
}
});


And it works, but when i go to this view the EditorFor X is always visible, only changes when i start clicking on the values of the dropdownlist. My question is how can it stays hidden when accessing to the view and only shows on click.

Answer

You need to execute the change() event immediately after binding the event like following.

$('#Best').on('change', function () {
    if ($(this).val() != "XBest") {
        $('#X').hide(); //invisible
        $('#X').attr('disabled', 'disabled'); // disable
    } else {
        $('#X').show(); //visible
        $('#X').removeAttr('disabled'); // enable
    }
}).change(); // auto execute
Comments