我目前正在通过Wordpress使用联系表单插件,因此输出的HTML和JS如下所示:
$('.form .form--field label').click(function() {
$(this).parents('.form--field').addClass('form--field--focus');
$('input').filter(':first').focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form--field form--field__firstname">
<label for="firstname" class="form--field__label">First Name</label>
<span>
<input type="text" name="firstname">
</span>
</div>
这个设计让我对它产生了一些麻烦,但无论如何,我试图找出当用户点击标签时如何强制关注相应的输入。目前,这就是我所处的位置。如果有人有任何意见或建议,我们将不胜感激。
答案 0 :(得分:1)
for
上的<label>
属性会查找id
不 a name
。下面的例子可以在没有JavaScript的情况下使用
<div class="form--field form--field__firstname">
<label for="firstname" class="form--field__label">First Name</label>
<span>
<input type="text" id="firstname" name="firstname">
</span>
</div>
虽然如果你真的想用JavaScript / JQuery做这件事而不是被束缚到使用标签你可以这样做$(this).next().children().focus();
$('.form--field__label').click(function() {
$(this).next().children().focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form--field form--field__firstname">
<label class="form--field__label">First Name</label>
<span>
<input type="text">
</span>
</div>
<div class="form--field form--field__secondname">
<!-- using a span instead of label as an example !-->
<span class="form--field__label">Second Name</span>
<span>
<input type="text">
</span>
</div>
答案 1 :(得分:1)
设置输入id =&#34; firstname&#34;因为你想要专注于标签点击。这是html中的内置功能。</ p>
<input type="text" id="firstname" name="firstname">
此处有更多详情https://www.w3schools.com/tags/tag_label.asp
对于多个输入,您可以像这样使用它
<form action="/action_page.php">
<label for="male">Male</label>
<input type="radio" name="gender" id="male" value="male"><br>
<label for="female">Female</label>
<input type="radio" name="gender" id="female" value="female"><br>
<label for="other">Other</label>
<input type="radio" name="gender" id="other" value="other"><br><br>
<input type="submit" value="Submit">
</form>
如果你仍然坚持,你可以像这样使用它
$('.form--field label').click(function() {
//It will look next sibling which is span and then find input in it and then focus it
//so it doesn't focus on other children elements
$(this).next('span').find('input').focus();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form--field form--field__firstname">
<label class="form--field__label">First Name</label>
<span>
<input type="text" name="firstname">
</span>
<br>
<label class="form--field__label">Last Name</label>
<span>
<input type="text" name="lastname">
</span>
</div>
&#13;