admin管理员组

文章数量:1417070

I have a form which posts data to a proccess.php file. In the form i am validating the input. There is a checkbox which asks if a tandem bicycle is used. I want it to display a text input field only if the box is ticked. here is my form code for that porion:

<tr>
  <td>
    <span style="font-weight:bold">Tandem:</span>
  </td>
  <td valign="middle">
    <input type="checkbox" name="tandem">&nbsp;
    <input style="visibility:hidden" type="text" name="partnerid" id="partnerid">
  </td>
</tr>

Basically if checkbox "tandem" is checked, set text input field "partnerid" visibility:visible;

I have a form which posts data to a proccess.php file. In the form i am validating the input. There is a checkbox which asks if a tandem bicycle is used. I want it to display a text input field only if the box is ticked. here is my form code for that porion:

<tr>
  <td>
    <span style="font-weight:bold">Tandem:</span>
  </td>
  <td valign="middle">
    <input type="checkbox" name="tandem">&nbsp;
    <input style="visibility:hidden" type="text" name="partnerid" id="partnerid">
  </td>
</tr>

Basically if checkbox "tandem" is checked, set text input field "partnerid" visibility:visible;

Share Improve this question edited Oct 7, 2011 at 11:02 SebastianOpperman asked Oct 7, 2011 at 10:45 SebastianOppermanSebastianOpperman 7,3366 gold badges32 silver badges37 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

I remend to use this code. When the disabled property of an input element is true, the element cannot be edited. The user usually has an indication that the input field should not be used.

<input type="checkbox" name="tandem" onchange="this.form.partnerid.disabled=!this.checked" />

Explanation of the code:

  • onchange=".." is triggered when the value of the checkbox changes. This can either occur by clicking, or by using the keyboard. The click event is NOT sufficient for this purpose.
  • this.form from the context of an form element's event listener refers to the form
    All named form elements can then be accessed through this.form.element_name or this.form["element_name"].
  • When the checkbox is checked (checked==true), the input should not be disabled (disabled=false). This is done by using a negotiation: this.form.partnerid.disabled = !this.checked.

Presumably the inputs are in a form, so you can put a click listener on the checkbox that makes the text input visible or not based on whether it's checked or not:

  <input type="checkbox" name="tandem" onclick="
    this.form.partnerid.style.visibility = this.checked? 'visible' : 'hidden';
  ">

It might seem logical to use the change event, but in IE that won't fire until the checkbox loses focus, which is a bit counter intuitive, so use click.

本文标签: javascriptDisplay a text input field only if another checkbox is checkedStack Overflow