JavaScript - 如何使用箭头键将一个文本框导航到另一个文本框
我有很多代码测试但不能正常工作请参阅下面我的html代码和JavaScript代码
<div class="col-md-12" style="margin-top: 15px;">
<div class="col-md-2">
<div class="form-group">
<label>Date & Time</label>
<input name="date_and_time" class="form-control" readonly value="<?=date('Y-m-d H:i:s')?>" type="text">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Invoice Number</label>
<input name="invoice_number" class="form-control" readonly value="39" type="text">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Search Customer by Mobile / Name</label>
<input name="customer_search_mobile_name" class="form-control" value="" type="text">
</div>
</div>
</div>
JavaScript代码
<script type="text/javascript">
$(document).keydown(
function(e)
{
if (e.keyCode == 39) {
$(".form-control:focus").next().focus();
}
if (e.keyCode == 37) {
console.log('hi');
$(".form-control:focus").prev().focus();
}
}
);
</script>
答案 0 :(得分:2)
试用此代码:
<强> HTML 强>
<div class="col-md-12" style="margin-top: 15px;">
<div class="col-md-2">
<div class="form-group">
<label>Date & Time</label>
<input name="date_and_time" class="form-control" value="<?=date('Y-m-d H:i:s')?>" type="text">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Invoice Number</label>
<input name="invoice_number" class="form-control" value="39" type="text">
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label>Search Customer by Mobile / Name</label>
<input name="customer_search_mobile_name" class="form-control" value="" type="text">
</div>
</div>
</div>
<强> JS 强>
var isShift = false;
$("input").keydown(function(e){
if(e.keyCode==16)
isShift = true;
if ((e.keyCode==40 || e.keyCode==39) && !isShift) {
$(this).parent().parent().next().find('input').focus()
}
else if ((e.keyCode==37 || e.keyCode==38) && !isShift) {
$(this).parent().parent().prev().find('input').focus()
}
});
$("input").keyup(function(e){
if(e.keyCode==16)
isShift = false;
});
答案 1 :(得分:0)
<input class="my_input">
<input class="my_input">
<input class="my_input">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$('.my_input').keyup(function(e) {
if (e.keyCode == 39) {
var inputs = $('.my_input'); // array of all inputs
var index = inputs.index(this); // search which of the inputs is active
var newIndex = (index+1) % inputs.length; // index + 1, but cycle back to 0
$('.my_input').eq(newIndex).focus();
}
if (e.keyCode == 37) {
var inputs = $('.my_input'); // array of all inputs
var index = inputs.index(this); // search which of the inputs is active
var newIndex = index - 1; // index - 1
if(newIndex<0) {
newIndex = inputs.length - 1; // cycle to last element
}
$('.my_input').eq(newIndex).focus();
}
return true;
});
</script>