문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top