[SOLVED] Show/Hide field based on checkboxfor value in asp.net mvc

Issue

i want to hide/show textbox based on checkbox value. With this line of code, it is achieveable when i click the checkbox directly. But, when i reload the form and bind checkbox value from databse, even the checkbox is checked, the textbox keep hidden. Can guide me the proper way to fix this ?

View

@Html.CheckBoxFor(model => model.rcf_data.lnkt_fastnetpackages, new { @id = "check2" })@Html.LabelFor(model => model.rcf_data.lnkt_fastnetpackages) <br />
@Html.TextBoxFor(model => model.rcf_data.FastnetTextBox, htmlAttributes: new { @id = "text2", @class = "form-control widthlenghtmin" })<br id="coba" />

Script

<script>
    $(function () {
        $("#check2").click(function () {
            if ($(this).is(':checked')) {
                $("#text2,#coba").show();
            }
            else {
                $("#text2,#coba").hide();
            }
        });
    });
</script>

Solution

try something like this


@if (Model.rcf_data.lnkt_fastnetpackages==true)
{
@Html.TextBoxFor(model => model.rcf_data.FastnetTextBox, 
htmlAttributes: new { @id = "text2", @class = "form-control widthlenghtmin" })<br id="coba" />
}
else
{
@Html.TextBoxFor(model => model.rcf_data.FastnetTextBox, 
htmlAttributes: new { @id = "text2", @class = "hidden  form-control widthlenghtmin", 
@style = "display: none;" })<br id="coba" />
}

Answered By – Serge

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *