2016-11-08 84 views
0

我試圖更改TextBoxFor只讀屬性是否選中複選框。 我已閱讀其他帖子,但答案似乎並沒有爲我工作.. 我任何一個請指出我在下面的代碼想念。更改TextBoxFor只讀屬性關於是否選中複選框

<div class="editor-label"> 
       @Html.LabelFor(m => m.AddFitbit) 
      </div> 
      <div class="editor-field" id="checkBox"> 
       @Html.CheckBoxFor(m => m.AddFitbit) 
      </div> 
      <div class="editor-label"> 
       @Html.LabelFor(m => m.Mail) 
      </div> 
      <div class="editor-field" id="userMail"> 
       @Html.TextBoxFor(m => m.Mail) 
      </div> 
      <br /> 
      <input class="submit" type="submit" value="@LangResources.Create" /> 
      <button onclick="history.back(); return false;">@LangResources.BtnCancel</button> 
     </div> 
    </article> 
} 

@Html.ValidationSummary(true, LangResources.ScreenAddGeneralError) 

<script type="text/javascript"> 
    $(function() { 
     $('#checkBox').change(function() { 
      if ($(this).is(':checked')) { 
       $('#userMail').attr('readonly'); 
      } else { 
       $('#userMail').removeAttr('readonly'); 
      } 
     }); 
    }); 
</script> 

回答

3

你的目標,其中包含您的複選框,這的確不會觸發任何change事件div。將目標複製框內的div這樣。

$(function() { 
    $('#checkBox input[type="checkbox"]').change(function() { 
     $('#userMail input[type="text"]').prop('readonly', $(this).is(':checked')); 
    }); 
}); 

而且,我糾正,並通過使用prop代替attr簡化你的代碼。屬性應該是給定屬性的初始值,所以最好改爲改變相應的元素屬性。

有關使用prop的詳細信息,請參閱the documentation(基於@ Liam的評論)。

+0

['prop()'here](http://api.jquery.com/prop/) – Liam

+0

的詳細信息對不起,但我沒有工作:( –

+0

是的,因爲'#userMail' id指的是一個'div'以及我已經編輯了答案。 –