开发者

jQuery check/uncheck problems

I'm using a gridview that has a radio button in one of the columns. It's used as a true/false flag. Anyways, because of the nature of my project, I requ开发者_Go百科ire javascript to uncheck any radio buttons when I check another one. This works fine, except that my gridview is wrapped in an update panel. I am taking care of reintializing the jQuery on autopost back, but what's happening is upon post back, removing my checked radio button and not putting it back. If I don't use the jQuery it works fine(but then I don't get the button exclusitivity), so I think its my code. Here's the code I have.

<script type="text/javascript">
$(document).ready(function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    function EndRequestHandler(sender, args) {
        $("input").click(function () {
            $("input").removeAttr('checked');
            $(this).attr('checked','checked');
        });
    }
    $("input").click(function () {
        $("input").removeAttr('checked');
        $(this).attr(':checked');
    });

});

Is there a better way to write this code? Thanks.


couple of things:

$(this).attr(':checked'); //this doesnt look right.. what are you trying to do here?

$('input') // this will target all input fields on the page, all radio buttons, textboxes etc. i don't think u want that. try giving the radio's IDs and use the ID selector to select them in jQuery


Assuming you set the name (not the ID) of the radio buttons to be the same, HTML will automatically make the selection exclusive for you without any jQuery needed. That's how a radio box differs from a checkbox. I'd look into that first as you shouldn't need a bunch of JS to do what HTML does built in if you set it up right.


I solved this issue by changing some of my t-sql code and not having to use jquery at all.


I changed your code like this:

if( $('input.any-radio').length ){ $('input.any-radio').change(function(){ $('input.any-radio').removeAttr('checked'); $(this).attr('checked', 'checked'); });}

and it works for me!


Try it

For Radio Button

function toggleCheckRadioButton(sender) {
    var res;
    if ($(sender).attr('previousValue') == 'true') {
        $(sender).attr('checked', false)
        res = false;
    } 
    else {
        $(sender).attr('checked', true);
        res = true;
    }

    $('form input[type="radio"][name$="' + $(sender).attr('name') + '"]').each(function () {
        $(this).attr('previousValue', false);        
    });

    $(sender).attr('previousValue', res);    
}

For Radio List

function initToggleCheckRadioList(sender) {
    $(sender).find('input[type="radio"]').each(function () {
        $(this).click(function () { toggleCheckRadioButton(this); });
    });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜