Question

I've got a form laid out using the css below. Mostly it works well, but whenever there are two input fields with the <label> tags I cannot click to select the second field. If you click the 1st input field it's fine. If you click into the 2nd input field it automatically jumps focus back to the first one. However, you can tab between the two successfully.

div.largeblock{
    margin:5px 0px 20px 0px;
    background:#d7e5f2;
    border:1px solid #d7e5f2;
}
div.largeblock label{
    display:block;
    margin-bottom:5px;
}
div.largeblock label span{
    display:block;
    float:left;
    margin-right:6px;
    width:130px;
    text-align:right;
}
<label>
   <span>Postcode</span>
   <input type="text" maxlength="4" name="postcode1" required="required" placeholder="Post" />
   <input type="text" maxlength="3" name="postcode2" required="required" placeholder="Code"/>
</label>

I have the same problem where I have a <select> & <input> within 1 label. But for the other 20 or so lines with just 1 <input> it's fine.

Was it helpful?

Solution

When you click on a label, the behaviour in most browsers is to give focus (or check in the case of a checkbox) to the related input.

You need to move the second input tag out of the label tag. Probably into it's own.

OTHER TIPS

A label element should refer to a single input element, using the for attribute that should have the same value as the id of the input element it refers to. Otherwise it won't behave predictably, like in your example where the label focuses the first input, which doesn't make any sense in your example. If you are grouping form elements you should use the element fieldset (which can be styled with css to look like a label).

The correct syntax would be:

<label for="postcode1">Postcode 1</label>
<input type="text" id="postcode1" maxlength="4" name="postcode1" required="required" placeholder="Post" />
<label for ="postcode2">Postcode 2</label>
<input type="text" id="postcode2" maxlength="3" name="postcode2" required="required" placeholder="Code"/>

Or if you want to use fieldset:

<fieldset>
    <legend>Postcode</legend>
    <input type="text" maxlength="4" name="postcode1" required="required" placeholder="Post" />
    <input type="text" maxlength="3" name="postcode2" required="required" placeholder="Code"/>
</fieldset>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top