How to navigation one textbox to another textbox using arrow key in JavaScript

I am woking on a funtion which will be used for navigating between controls by Up/Left/Right/Down arrow keys and on enter key. my code is like below.

HTML Code

<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="<?=$getInvoiceNumber?>" 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 class="col-md-1">
		<div class="form-group">
			<label>User</label>
			<input name="user" class="form-control"  readonly value="" type="text">
		</div>
	</div>

	<div class="col-md-1">
		<div class="form-group">
			<label>Balance Point</label>
			<input name="balance_point" class="form-control"  readonly value="" type="text">
		</div>
	</div>
</div>
	

JavaScript Code (Method 1)

$("input").keydown(function(e){
	if (e.keyCode==40 || e.keyCode==39) {
	  $(this).parent().parent().next().find('input').focus();
	}
	  else  if (e.keyCode==37 || e.keyCode==38) {
	  $(this).parent().parent().prev().find('input').focus();
	}
});

JavaScript Code (Method 2: select value in textbox using shift key)

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;
});

Leave a Reply

Your email address will not be published. Required fields are marked *