我知道这是一个常见的问题,但找不到答案。好久不见了。
我们有n个输入字段,每个字段都有唯一的ID和名称。我们正试图在用户标签时将焦点放在下一个输入上。发生了什么是光标转到URL栏。
Javascript:
$(document).ready(function () {
console.log("main.js called");
var next, nextId;
function hideLabels() {
$('input').focus(function () {
var $inputId = $(this).attr('id');
$('label[for="' + $inputId + '"]').removeClass('hide');
});
$('input').focusout(function () {
var $inputId = $(this).attr('id');
if ($(this).val().length !== 0) {
$(this).addClass('set');
$('label[for="' + $inputId + '"]').addClass('hide');
next = $(this).next('label').next('input');
nextId = "#" + next.attr('id');
$('label[for="' + nextId + '"]').removeClass('hide');
next.removeClass('hide');
focusNextInput(nextId);
} else if ($(this).val().length === 0) {
$(this).removeClass('set');
$('label[for="' + $inputId + '"]').removeClass('hide');
}
});
}
function focusNextInput (nId) {
$(nId).css('background', 'red');
$(nId).focus();
};
});
HMTL:
<article>
<label for="input1" class="inputLabel">Label 1</label>
<input type="text" placeholder="a fantabulous placeholder" id="input1" class="form">
<label for="input2" class="inputLabel hide">Label 2</label>
<input type="text" placeholder="a fantabulous placeholder" id="input2" class="form hide">
<label for="input3" class="inputLabel hide">Label 3</label>
<input type="text" placeholder="a fantabulous placeholder" id="input3" class="form hide">
<label for="input4" class="inputLabel hide">Label 4</label>
<input type="text" placeholder="a fantabulous placeholder" id="input4" class="form hide">
<label for="input5" class="inputLabel hide">Label 5</label>
<input type="text" placeholder="a fantabulous placeholder" id="input5" class="form hide">
<label for="input6" class="inputLabel hide">Label 6</label>
<input type="text" placeholder="a fantabulous placeholder" id="input6" class="form hide">
<label for="input7" class="inputLabel hide">Label 7</label>
<input type="text" placeholder="a fantabulous placeholder" id="input7" class="form hide">
<label for="input8" class="inputLabel hide">Label 8</label>
<input type="text" placeholder="a fantabulous placeholder" id="input8" class="form hide">
<label for="input9" class="inputLabel hide">Label 9</label>
<input type="text" placeholder="a fantabulous placeholder" id="input9" class="form hide">