I am experiencing an issue with my form that contains around 10 input text boxes. When I press the enter key from an input text box, it skips the text boxes in between and goes directly to the submit button. This problem occurs only when using the keyboard as the mouse navigation works fine.
function getElement(elm){
var elem = document.getElementById(elm);
return elem;
}
function sendData(){
getElement('submit-button').addEventListener("click",function(){
getElement("success-txt").removeClass('display-none');
if(getElement('pbarcode')){
var pbarcode = $('#pbarcode').val();
var pname = $('#pname').val();
var pprice = $('#pprice').val();
var poprice = $('#poprice').val();
$.ajax({
url:'getdata.php',
method:"post",
data:{pbarcode:pbarcode,pname:pname,pprice:pprice,poprice:poprice},
cache: false,
onSuccess: function(response){
alert('success');
},
onFailure: function(response){
alert('failure');
}
});
}
else{
alert("error");
}
});
}
function showWarnMessage(){
getElement("submit-button").addEventListener("click",function(){
alert("you entered submit button");
var data1 = $('#pbarcode').val();
var data2 = $('#pname').val();
var data3 = $('#pprice').val();
var l3 = data3.length;
var l1 = data1.length;
var l2 = data2.length;
var flag = 0;
if(l1 < 1){
flag = 1;
}
if(l2 < 1){
flag = 1;
}
if(l3 < 1){
flag = 1;
}
alert(flag);
if (flag == '0'){
alert(flag + "go");
sendData();
}
});
}
showWarnMessage();
ul,li {
list-style : none;
padding :0px;
margin : 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="create-user" method="post">
<ul id="create-new-user-page">
<li>
<span>Product Barcode</span>
<input type="number" id="pbarcode" name="barcode" class="form-data" required>
</li>
<li>
<span>Product Name</span>
<input type="text" class="form-data" name="pname" id="pname" required>
</li>
<li>
<span>Product Price</span>
<input type="number" class="form-data" name="pprice" id="pprice" required>
</li>
<li>
<input type="submit" id="submit-button" Value="Submit" name="submit_data">
</li>
</ul>
</form>
I have attempted to use event.preventDefault(); on 'enter' click on text boxes in order to address this issue. Here are the codes:
event.preventDefault();
function preventDefault(elem){
getElement('elem').addEventListener('keypress',function(){
if (event.keyCode == 13) {
event.preventDefault();
alert('calling ')
}
});
}
preventDefault('pname');
preventDefault('pprice');
preventDefault('pname');
preventDefault('pbarcode');
However, this approach also yields the same result. I am looking for a solution that allows the form to work seamlessly with the enter key, moving from one input text box to another instead of going straight to the submit button.