Erico Chan
Erico Chan

Reputation: 1170

Multiple input lose focus on click

I have a form containing address fields as such http://jsfiddle.net/DP3aw/2/

For some reason I have to put the address in multiple text inputs as it is now.

When you click on the 2nd or 3rd input, the focus will jump to the first text field, why is that happening? is there anyway I can prevent that? or do I have to use js/jQuery to stop it from happening?

Thanks!

Upvotes: 3

Views: 2623

Answers (1)

Tim M.
Tim M.

Reputation: 54359

It's because you have the all of your INPUT elements inside the LABEL tag. Clicking on a label focuses the associated input. Since all of your inputs are inside the label, they all trigger it, causing the focus to jump to the first input (the one that is associated).

Fixed version: http://jsfiddle.net/DP3aw/3/

Broken

<label for="OrgAddr"><span>Address<strong>*</strong></span>
<div><input id="OrgAddr" name="OrgAddr" type="text" class="required" value=""></div>
<div><input id="OrgAddr2" name="OrgAddr2" type="text" value=""></div>
<div><input id="OrgAddr3" name="OrgAddr3" type="text" value=""></div></label>

Fixed

<label for="OrgAddr"><span>Address<strong>*</strong></span></label>
<div><input id="OrgAddr" name="OrgAddr" type="text" class="required" value=""></div>
<div><input id="OrgAddr2" name="OrgAddr2" type="text" value=""></div>
<div><input id="OrgAddr3" name="OrgAddr3" type="text" value=""></div>

Possible Improvement

Here's a more semantically correct version that uses a FIELDSET for the general grouping and labels for each individual input. It also demonstrates how clicking on a label will focus its associated input element.

http://jsfiddle.net/njY3U/1/

<fieldset>
<legend>Address</legend>
    <label for="street1">Street 1</label>
    <div><input type="text" id="street1" /></div>

    <label for="street2">Street 2</label>
    <div><input type="text" id="street2" /></div>

    <label for="city">City</label>
    <div><input type="text" id="city" /></div>

    <!-- ETC -->
</fieldset>

Upvotes: 4

Related Questions