Question

I am using jquery to change the label of the checkboxes.

use strict';
$("#chId").click(function () {
   if (this.checked) {
         $('#divId').html("Checked");
   }
   else{
         $('#divId').html("Un-Checked");
   }

});

It works OK if I specify checkbox in regular html style

<input type="checkbox" id="chId"/> 
<div id='divId'>Checked</div>

There are several checkboxes and I am using different "divId" for each text to change However, I need to specify it with the struts checkbox tag with the "label" attribute. I know that when it's done like this, I will have label rendered on html as

<label for"checkbox_class">Checked</label>

And if if change jquery just a little to select by class "label" it will work

$('.label').html("Checked");

But, if I have multiple check boxes, all the labels would have the same class ".label" and I am not sure how to make different text by check box change not at the same time Basically, I want to either 1) have 5 labels to all have different classes "label1", ... "label5" or 2) have id on each label so that ... or 3) be able to use "for" attribute in a jquery selector? I think #(3) is my best bet, but I don't know how to to do it.
Can anyone help ? Thanks

Was it helpful?

Solution

Give class and id attributes to your checkboxes and use jQuery attribute equals selector to get label element where for attribute equals checkbox id.

<script type="text/javascript">
  $(function () {
    $(".checkb").click(function () {
      if(this.checked) {
        $("label[for="+this.id+"]").html("Checked");
      }else {
        $("label[for="+this.id+"]").html("Un-Checked");
      }
    });
  });
</script>

<s:checkbox cssClass="checkb" id="checkid1" name="check1" label="Un-Checked"/>
<s:checkbox cssClass="checkb" id="checkid2" name="check2" label="Un-Checked"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top