My form contain about 10 input text boxes ,The problem is when I press the enter key from a input text box it's directly going to submit button by skipping the text boxes between them.I added my snippet below.it's working fine when using mouse
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 enteres submitt 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>
What I have been tried so far is using
event.preventDefault();
on 'enter' click on text box ,I added the codes below
function preventDefault(elem){
getElement('elem').addEventListener('keypress',function(){
if (event.keyCode == 13) {
event.preventDefault();
alert('calling ')
}
});
}
preventDefault('pname');
preventDefault('pprice');
preventDefault('pname');
preventDefault('pbarcode');
but which also returns the same result.I would like to have a form which works fine with the enter key.(ie,when I press 'enter' key from one input text box which should move in to the next text box ,instead moving directly in to the form submit button)
</div>