Search code examples
htmlformsinputlabelfield

Activate input field from input checkbox


I want to activate the input field from checking the checkbox.

I have a basic form here:

<ul>
 <li>
  <label id="form-title" for="name3">Specifics:</label>
 <li>   
  <textarea id="name3" name="name3" >

  </textarea>
 </li>

</ul>

You click on the "Specifics and it activates the field. Can this be done with an input tag instead of a label tag?

Example:

<ul>
 <li>   
  <input type="checkbox" for="name2">Other...</input>
  <input id="name2" name="name2" />
 </li>
</ul>

jsfiddle of complete work thus far: http://jsfiddle.net/Sederu/gaZDW/


Solution

  • You will need a little EMCAScript for that.

    <label for="name3">
          <input type="checkbox" id="name3activaitor" onclick="if(this.checked){ document.getElementById('name3').focus();}" />
          Other...
        </label>
    <input type="text" id="name3" name="name3" />

    The inline handler sees if the checkbox has been checked, and if it has, focuses the text input. I put the checkbox in the label just to symantically group it with the label as it preforms the same function, but you can put the checkbox anywhere you would like.

    If you are looking to enable/disable the input field rather than just focus it, you can do like so

    <input type="checkbox" onclick="var input = document.getElementById('name2'); if(this.checked){ input.disabled = false; input.focus();}else{input.disabled=true;}" />Other...
    <input id="name2" name="name2" disabled="disabled" />