How to get the latest selected value from a checkbox list?

后端 未结 3 1751
余生分开走
余生分开走 2020-12-05 15:39

I am currently facing a problem. How to get the latest selected value from a asp.net checkbox list?

From looping through the Items of a checkbox list, I can get the

3条回答
  •  佛祖请我去吃肉
    2020-12-05 16:41

    Don't know about you, but as a user i wouldn't want the page to post back every time a checkbox item was checked.

    This is the solution i would go with (jQuery):

    Declare a server-side hidden field on your form:

    
    

    Then wire up client-side event handlers for the checkboxes to store checkbox clicked:

    $('.someclassforyourcheckboxes').click(function() {
       $('#HiddenField1').val($(this).attr('id'));
    

    This is a lightweight mechanism for storing the ID of the "latest" checkbox clicked. And you won't have to set autopostback=true for the checkboxes and do an unecessary postback.

    You dont HAVE to use jQuery - you can use regular Javascript, but, why do more work? =)

    Then when you actually do the postback (on a submit button click i assume), just check the value of the hidden field.

    Unless of course you WANT to postback on every checkbox click, but i can't envision a scenario in which you'd want this (maybe you're using UpdatePanel).

    EDIT

    The HTML of a checkbox list looks like this:

     I have a bike
    

    So, you can access three things:

    Vehicle = $(this).attr('name');

    Bike = $(this).attr('value');

    I have a bike = $(this).html();

    If you're trying to access the databound value, try the second technique.

    Give that a try.

提交回复
热议问题