tags:

views:

31

answers:

1

I have these three fields in my jsp page.

    <td>
           <html:text property="my_dto.number1" </html:text>
   </td>
    <td>
           <html:text property="my_dto.number2" </html:text> 
    </td>

    <td>                                    
          <input type ="checkbox" id ='isTrue' /> 
    </td>

now i want if isTrue is checked the two text box will be disabled. how to do it?

+1  A: 

Fact: JSP runs at webserver, produces HTML/CSS/JS and sends it to webbrowser. JS runs at webbrowser and sees only the HTML DOM tree, not any line of Java/JSP. Rightclick page in webbrowser, choose View Souce and see yourself. Do you understand this? OK, then continue.

In the generated HTML source you should see some HTML <input type="text"> elements in place of Struts' <html:text> components. I don't do Struts, but a bit decent MVC framework will assign those HTML elements an id as well. If not done or when the ID value is randomly generated, you'd like to set a fixed ID yourself. According the TLD documentation, you need to set the styleId attribute: <html:text styleId="someFixedId">.

Finally, write a JS function which get executed on click of the checkbox and modifies the disabled attribute of those text elements accordingly. Andy E has already given some hints. Here is how the JSP should basically look like:

<html:text property="my_dto.number1" styleId="number1" />
<html:text property="my_dto.number2" styleId="number2" /> 
<input type="checkbox" id="isTrue" onclick="disableNumbers(this)" /> 

<script>
    function disableNumbers(checkbox) {
        var number1 = document.getElementById("number1");
        var number2 = document.getElementById("number2");
        number1.disabled = number2.disabled = checkbox.checked;
    }
</script>
BalusC
I think *onchange* would be more suitable, *onclick* won't fire if you focus the checkbox and press the spacebar key. I can't remember if *onchange* fires before or after though, so a 0ms timeout might also be needed.
Andy E
@Andy: it will :) [Test yourself](http://jsbin.com/erene3). Oh, there's one more disadvantage of onchange: it get only fired when checkbox loses focus.
BalusC
@BalusC: huh, I couldn't find that documented anywhere... You're right about the *change* event firing when focus is lost (but it's not true of all browsers and it's only the case when the keyboard is used). I think you've proven the *click* event works better for this situation though, +1 :-)
Andy E
@Andy: not only for this situation. Always use it whenever you want to hook on a change of checkbox / radio button. The `onchange` on those elements won't behave as you'd intuitively expect.
BalusC