开发者

Find particular CheckListItem in CheckBoxList control using Javascript or jQuery

开发者 https://www.devze.com 2023-03-22 10:15 出处:网络
I have a CheckBoxList that displays a list of checkboxes using data from a table. While the records in this table is expected to change, the last item is expected to have a text value of Other with a

I have a CheckBoxList that displays a list of checkboxes using data from a table.

While the records in this table is expected to change, the last item is expected to have a text value of Other with an expected value.

If the user selects "Other", I want to be able to enable an associated text box where they enter a specified "Other" description. I want to be able to do this on the开发者_开发百科 client using Javascript or jQuery.

Since the IDs individual list items are dynamically created is there a way that I can avoid hard coding something like:

chkOther = document.getElementbyID("checkListItem12_chkOccupationOther")

I don't know jQuery, but I figure that that Library probably provides a nice way to get control using a matching ID mask, for example.

Suggestions?


If you can guarantee that your "Other" Check box is always last you can use the last selector. Using the ID of the check box list:

$(document).ready(function() {
    $("#<%=YourCheckBoxList.ClientID%> input:checkbox:last").click(function(){
       if(this.checked)  {          
          //Enable Text Box Here
       }else{
          //Disable here 
       }
    });
});

EDIT: Updated to remove the unnecessary convert of "this" to a jQuery object as per RobG's Comment.


You can do this with plain JS quite easily. I'll guess that your checkboxes are in a form, so you start by getting the form then add a listener to the last checkbox:

function addClick() {
  var form = document.forms['f0'];
  var input, inputs = form.getElementsByTagName('input');
  var i = inputs.length;

  while (i--) {
    input = inputs[i];

    if (input.type == 'checkbox') {
      input.onclick = function() {
        if (this.checked) {

          // Do stuff...
          alert('checked!');

        } else {
          // Put stuff in here if unchecked, probably
          // want to hide whatever is shown when above
          // is clicked
        }
      }
      // Going backward, the first checkbox found is the
      // last one so stop after first one found
      return;
    }
    input = null;
  }
}

Then add the function as a bottom script, using a DOM ready function or window.onload.

0

精彩评论

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