Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, April 5, 2012 3:19 AM
I am trying to hide markup on an MVC3 Razor View when a user selects a checkbox.
FYI - I have used Entity Framework 4.1 Code First Approach Scaffolding to produce the Create View.
I think it needs to be JavaScript because the change needs to happen on the client side.
The .Checked is what I would like to be able to do, but it's not available.
**<div class="editor-field">
@Html.CheckBoxFor(model => model.SafetyManagement)
@Html.ValidationMessageFor(model => model.SafetyManagement)
</div>
@if (Model.SafetyManagement.Checked == true)
{
<p> Show Text </p>
}**
Can you anyone help?
All replies (5)
Thursday, April 5, 2012 7:33 AM âś…Answered
put your text that should be hidden/ shown in check box change in a DIV tag as follows
@Html.CheckBoxFor(model => model.SafetyManagement, new { id = "cbSafetyManagement" })
<div id="divTest" style="display: none;">
//your text here
<div class="editor-label">
@Html.LabelFor(model => model.OrgHoldCert)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.OrgHoldCert)
@Html.ValidationMessageFor(model => model.OrgHoldCert)
</div>
</div>
//now your JQ click handler should be as follows
<script type="text/javascript">
$('#cbSafetyManagement').change(
function (e) {
// code here to hide your text
var checked = $(this).attr('checked');
if(checked)
{
$('#divTest').show();
}
else
{
$('#divTest').hide();
}
}
);
</script>
Thanks,
Ashok
Thursday, April 5, 2012 6:59 AM
Hi david
1) your check box needs an id as follows
@Html.CheckBoxFor(model => model.SafetyManagement, new { id = "cbSafetyManagement" })
2) use jQuery click() handler as follows
** ** $('#cbSafetyManagement').change(
function (e) {
// code here to hide your text
}
);
Thanks,
Ashok
Thursday, April 5, 2012 7:21 AM
Thanks for your reply.
Can I put razor code in the JQ function? If not how can I hide and show my razor view markup if checked is selected?
Example below (which doesn't work).
@Html.CheckBoxFor(model => model.SafetyManagement, new { id = "cbSafetyManagement" })
<script type="text/javascript">
$('#cbSafetyManagement').change(
function (e) {
// code here to hide your text
** <div class="editor-label">**
** @Html.LabelFor(model => model.OrgHoldCert)**
** </div>**
** <div class="editor-field">**
** @Html.EditorFor(model => model.OrgHoldCert)**
** @Html.ValidationMessageFor(model => model.OrgHoldCert)**
** </div>**
}
);
</script>
Thursday, April 5, 2012 8:37 AM
Thank you so much.
David
Friday, August 17, 2012 4:56 PM
just as a variation (same end result) ::
if ($this).is(':checked') { }
You may even find this a little more useful so you never actually have to ensure the 'checked' attribute has been initialized.