Click an H3 and focus on a form field

Asked

Viewed 89 times

2

I am organizing a contact form, divided into several parts.

One of the things I need is that when the user clicks an H3 (but it can also be a div, anchor or button) a specific field of this form is focused.

How could I accomplish that?

2 answers

7


To use a h3 can make use of an anchor associated with the ID of the input.

Would that be:

<h3><a href="#a">Clica-me para o input A</a></h3>
<h3><a href="#b">Clica-me para o input B</a></h3>

<input type="text" id="a">
<input type="text" id="b">

or as @Ricardo also suggested use the label thus:

<label for="a">
    <h3>Clica-me para o input A</h3>
</label>
<label for="b">
    <h3>Clica-me para o input B</h3>
</label>

<input type="text" id="a">
<input type="text" id="b">

And in these cases it makes no difference where on the page the elements are provided that each ID is unique (not repeated within the page).

  • Sergio my click is not focusing on your first option... Maybe this is the snipped built-in OS

  • @Miguel is possible, he is a bit buggy :) You can test here: https://jsfiddle.net/eon3x98u/

3

There are a few ways you can solve your problem.
The simplest would be using elements HTML, thus:

<label for="minha_input"><h3>Input</h3></label>
<input type="text" id="minha_input">

If not, an alternative is to do via Java Script, thus:

function myFocus() {
  document.getElementById('minha_input').focus();
}
 <h3 onclick="myFocus()">Input</h3>
<input type="text" id="minha_input">

I hope I’ve helped.

  • Dei +1 at the suggestion of label but I see no reason to use Javascript when HTML has native ways to do this.

  • I fully agree @Sergio. I gave +1 in your reply too, as I was not aware that href was using # identified the input id.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.