2016-11-08 83 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'以及我已经编辑了答案。 –