Instability in script to hide / show fields

0

I have the following script:

    @Scripts.Render("~/bundles/jquery")
<script>
    $(document).ready(function () {

        $('.ocultar').hide();

        $('#dn').change(function () {
            if ($("#dn").attr("checked",true)) {
                $('.ocultar').show();
            }
            else {
                $('.ocultar').hide();
            }
        });
    });

<div id="dn">
    @Html.CheckBoxFor(x => x.DN) <b>Dpto. Nacional </b>
</div> 

    <div><br /></div>
<div class="ocultar">
  <b> Número do Ofício </b> 
</div>
<div class="ocultar">
    @Html.EditorFor(x => x.Numero)
     @Html.ValidationMessageFor(x => x.Numero)
</div>
    <div class="ocultar">
  <b> Observacao </b> 
</div>
<div class="ocultar">
    @Html.TextAreaFor(x => x.Observacao)
</div>

The script works fine. Load the page with the fields hidden and if I check the 'DN' checkbox the 'Numero' and 'Observacao' fields appear. But I have two small problems: If I uncheck the checkbox the two fields will not disappear. And if I leave it checked and I try to save it, when I click the save button, the two fields disappear and the message that the field is obligatory that should appear does not appear. That is, when it saves and does not pass, it loads 'hide' again. How to correct these two instabilities?

    
asked by anonymous 03.12.2014 / 13:04

1 answer

2

The error is in this line:

if ($("#dn").attr("checked",true)) {

$("#dn").attr("checked",true) marks the checkbox as checked , and still returns an object, which will make execution always enter if and never else . The solution is very simple:

if ($("#dn").prop("checked")) {

Just do not pass the value, so the attr method returns the current value. But notice that I've switched to prop , which returns the current state of the DOM, not what's in the source code of the DOM. your HTML. This is the recommended way to check the status of the checkbox.

    
03.12.2014 / 13:35