How can I check if a checkbox is checked in view page with razor and if checked display a textbox!
I'm new in asp mvc and razor, still learning.
View Code
@Html.CheckBoxFor(m => m.SupportRequired)
@Html.TextBoxFor(m => m.AssistName new { @class = "form-control" })
How can I check if a checkbox is checked in view page with razor and if checked display a textbox!
I'm new in asp mvc and razor, still learning.
View Code
@Html.CheckBoxFor(m => m.SupportRequired)
@Html.TextBoxFor(m => m.AssistName new { @class = "form-control" })
Share
Improve this question
edited Oct 10, 2017 at 13:10
Ali Soltani
9,9565 gold badges32 silver badges57 bronze badges
asked Aug 15, 2017 at 14:24
Tom Tom
1357 silver badges15 bronze badges
4
-
Very simple:
@if (Model.SupportRequired) { /* textbox here /* }
- probably need to break it into multiple lines because the Razor parser might not like it otherwise. – Peter B Commented Aug 15, 2017 at 14:28 - My code had a syntax error. I edited it. Please see it again. – Ali Soltani Commented Aug 15, 2017 at 15:08
-
When page is loading.. check the value of
SupportRequired
property and show and hide the textbox..@Html.TextBoxFor(m => m.AssistName new { @class = "form-control", style="display:@(Model.SupportRequired == true ? "block": "none")})
– SwapNeil Commented Aug 15, 2017 at 15:12 - Just curious, is this for an Edit page? If so, you would like this to happen on load? Please be more clear. What happens if the checkbox is checked on load of the page then the user unchecks it? This can be done via JS/jQuery, or if it is as simple as showing the textbox onload of the page, then just Razor will suffice – Grizzly Commented Aug 15, 2017 at 15:13
1 Answer
Reset to default 6You can use JavaScript like this:
@Html.CheckBoxFor(m => m.SupportRequired , new { id = "MyChk", onchange = "valueChanged()"})
@Html.TextBoxFor(m => m.AssistName , new { id = "MyTxt" , @class = "form-control" })
<script type="text/javascript">
function valueChanged() {
if ($('#Mychk').is(":checked"))
$("#MyTxt").show();
else
$("#MyTxt").hide();
}
</script>
Edit
For show or hide in page load you need add this code:
$(document).ready(function() {
valueChanged();
});