开发者

issue in javascript in checkboxlist

开发者 https://www.devze.com 2022-12-13 18:34 出处:网络
this is my Javascriptwhich behaves like anRadiobutton. whereuser can select only 1 option at atime (ex: if he select item1 and selects item2 then item1 gets deselected, as he as selected item2 if hecl

this is my Javascript which behaves like an Radiobutton. where user can select only 1 option at a time (ex: if he select item1 and selects item2 then item1 gets deselected, as he as selected item2 if he clicks again on item2 it gets deselected.) which make user either select any one item or deselect the selected item to

this condition works fine

issue i have an button in page once user clicks th开发者_开发技巧at button again if user selects any item[eg item1 is selected before clicking on the button. then after clicking the button. and now if we selected any item in checkboxlist the initially selected item1 is not getting deselected when i am selecting another item in check boxlist

below is my code

var objChkd;

function HandleOnCheck() 
{
   var chkLst = document.getElementById('CheckBoxList1'); 
   if(objChkd && objChkd.checked)
          objChkd.checked=false;objChkd = event.srcElement; 
}

and register the client event to the 'CheckBoxList1' at the Page_load as

CheckBoxList1.Attributes.Add("onclick","return HandleOnCheck()");

in .cs file i don't want to do this CheckBoxList1.clearSelection();

any help would be great

thank you


Your problem is clear but not specific enough. But let's try to find out together the solution.

In case when you trying to check or uncheck the previous item, I would advice you to use onclick handlers at "ListItem"'s classes and not at the list itself. (Imagine that someone clicks next to the list-item, so your state will be incorrect);

This also gives you the freedom in not depending anymore on browser compatibilities, like window.event or event, or whatever. You will get your node as the parameter to the function.

ListItem1.Attributes.Add("onclick","return HandleOnCheck(this)");
ListItem2.Attributes.Add("onclick","return HandleOnCheck(this)");

Also, try to eliminate the use of the hardcoded id's inside you HandleOnCheck function.

Next, you could better save your Item state inside the function scope and not outside it. You can do this by assigning argument to the function itself, like this:

HandleOnCheck.selectedItem = someNode;

So, the complete code is:

function HandleOnCheck(node) {
    var oldNode = HandleOnCheck.selectedItem;
    if(oldNode) {
        oldNode.checked = false;
    }

    HandleOnCheck.selectedItem = node;
}

And handler part :

ListItem1.Attributes.Add("onclick","return HandleOnCheck(this)");
ListItem2.Attributes.Add("onclick","return HandleOnCheck(this)");

This should help.

0

精彩评论

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