且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取复选框列表中最后选中的复选框ID?

更新时间:2022-12-02 21:37:22

试试这个..



JavaScript部分 -

try this out..

JavaScript part --
// Define a global variable array to store the last selected checkbox Id
var g_selectedCheckboxId = [];

// setter method to update checkbox id array
function setLastSelected(checkboxObj) {
  if(checkboxObj.checked) {
    g_selectedCheckboxId.push(checkboxObj.id);
  } else {
    g_selectedCheckboxId.splice(g_selectedCheckboxId.indexOf(checkboxObj.id), 1);
  }
}

// getter method to get ID of the last checked checkbox 
function getLastSelected() {
  if(g_selectedCheckboxId.length > 0)
    return g_selectedCheckboxId[g_selectedCheckboxId.length-1];
  return null;
}





HTML部分(假设)为每个复选框添加onclick事件 -



HTML part (assumption) Add onclick event to each and every checkbox -

<input type="checkbox" id="ctl00_ContentPlaceHolder1_cblcheckbox_0" onclick="setLastSelected(this)">Checkbox 1
<input type="checkbox" id="ctl00_ContentPlaceHolder1_cblcheckbox_1" onclick="setLastSelected(this)">Checkbox 2
<input type="checkbox" id="ctl00_ContentPlaceHolder1_cblcheckbox_2" onclick="setLastSelected(this)">Checkbox 3
<input type="checkbox" id="ctl00_ContentPlaceHolder1_cblcheckbox_3" onclick="setLastSelected(this)">Checkbox 4
</br></br></br></br></script>





问候,

Niral Soni



Regards,
Niral Soni


我为此制定了你好。



看看演示

1. 根据所选文本的另一个复选框选中一个复选框。 [ ^ ]。

2. 根据所选索引的另一个复选框选中一个复选框。 [ ^ ]。



谢谢...
I worked out this for you.

Take a look at the Demos
1. Select one checkbox according to checked status of another by selected text.[^].
2. Select one checkbox according to checked status of another by selected index.[^].

Thanks...


可能是因为Postback你的代码无效。



查看下面的代码....



May be because of Postback your code is not working.

Look at code below....

<script type="text/javascript">
    function show() {
    document.getElementById('light').style.display = 'block';
    document.getElementById('fade').style.display = 'block';

    return false;
     }
    </script>





这里我包含了return false。这避免了点击按钮的回发,你的代码将正常工作...



希望它有效...



Here I included "return false". Which avoids postback for a button click and your code will work fine...

Hope it works...