简体   繁体   中英

this.id is empty for asp:CheckBox

I have an asp:CheckBox with the following tag:

<asp:CheckBox ID="cbTest1" runat="server" onchange="cbChange(this.id);"/>

cbChange is a Javascript function in the <head> that looks like this (it's simple for now):

<script type="text/javascript">

    function cbChange(senderID) {
        alert('|' + senderID + '|'); // '|' is to help see string length
        return false;
    }

</script>

Now, whenever I click on cbTest1 , I get the alert box with the following text:

||

In other words, it's an empty/null string. I should also note that when I use a more traditional <input> that I get the expected results:

(Code for <input> )

<input type="checkbox" name="cbtest2" id="cbtest2" onchange="cbChange(this.id);" />

(Text in alert box when I check cbtest2 )

|cbtest2|

Why would I be getting the null/empty string with the asp:Checkbox , but expected behaviour with the <input> ?

EDIT I did a little bit more research, since the asp:CheckBox has the ID attribute instead of (lowercase) id , so I tried onchange="cbChange(this.ID);" . Now I get the following output in the alert box:

|undefined|

Why would this also be happening?

Pull up your rendered page source, you'll see the ASP actually renders this as:

<span onchange="cbChange(this.id);"><input id="ContentArea_cbTest" type="checkbox" name="ctl00$ContentArea$cbTest" /></span>

Your input element is actually nested with a span element.

Using Pure JS, you can still get the ID of your input by doing:

<asp:CheckBox ID="cbTest" runat="server" onchange="cbChange(this.childNodes[0].id);"/>

If you view source, you'll see:

<span onchange="cbChange(this.id);">
    <input id="cbTest" type="checkbox" name="cbTest" />
</span>

One of the downsides of WebForms - the markup doesn't always come as you'd expect.

Your best bet is to hook up the event manually on the client. If you happen to be using jQuery, you can do:

jQuery(document).ready(function() {
    jQuery("#<%= cbTest.ClientID %>").click(function() {
        cbChange(jQuery(this).attr("id"));
    });
});

(If you're not using jQuery, do the same thing, just hook up to the click event manually using regular javascript - I always have to look up that syntax though...)

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