简体   繁体   中英

How to toggle properties using an ASP.NET checkbox and javascript?

The following code sets a chosen property of one element and toggles that element when a checkboxs checked value is changed.

ASP.NET

<asp:CheckBox CssClass="Cb" RunAt="Server"/>
<asp:TextBox CssClass="Txt" RunAt="Server" ReadOnly="True"/>

HTML

<input class="Cb" type="checkbox"/>
<input class="Txt" type="text" readonly="true"/>

JQUERY

$(".Cb").change(function() {
    $(".Txt").prop("readonly",!this.checked);
});

WORKING EXAMPLE

http://jsfiddle.net/gKwbn/


A PROBLEM

When this code is executed with a ASP.NET asp:checkbox the result is not the same as when the code is executed with an input:checkbox.

With input:checkbox the readonly state toggles as:

INITIAL STATE

<input class="Txt" type="text" readonly="true"/>

TOGGLE

<input class="Txt" type="text"/>
<input class="Txt" type="text" readonly=""/>

With asp:checkbox the readonly state toggles as:

INITIAL STATE

<input class="Txt" type="text" readonly="readonly"/>

TOGGLE

<input class="Txt" type="text" readonly=""/>
<input class="Txt" type="text" readonly=""/>

UNDERSTANDING READONLY

All the following are properies are valid for readonly to be set to true.

  • readonly
  • readonly=""
  • readonly="true"
  • readonly="readonly"

MY QUESTIONS

How to remove and then toggle the readonly property when using asp.net with jquery/javascript?


EDITS

The problem is the class is applied to the incorrect element when using an asp:checkbox.

THIS

<asp:CheckBox CssClass="Cb" RunAt="Server"/>

RENDERS IN THE BROWSER AS

<span class="Cb"><input id="ctl01" type="checkbox" name="ctl01" /></span>

THE SOLUTION

Target the asp:checkbox using ID and not class.

<asp:CheckBox ID="CBID" CssClass="Cb" RunAt="Server"/>

$("#<%= CBID.ClientID %>").change(function() {
    $(".Txt").prop("readonly", this.checked ? "" : "readonly");
});

If I'm not completely misunderstanding your question, you can use this instead...

$(".Cb").change(function() {
    $(".Txt").prop("readonly", this.checked ? "" : "readonly");
});

That will set the readonly property to either readonly or empty, depending on the checkbox state.

Here's a working fiddle

Edit: Further to your update, you can either add the class to the checkbox like this...

<asp:CheckBox class="Cb" RunAt="Server"/>

or you can refer to it by ID...

$("#ctl01").change(function()...

or by name...

$("input[name=ctl01]").change(function()...

or by the fact that it's in the span...

$(".Cb input:checkbox").change(function()...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM