Sharath Chandra Sharath Chandra - 5 months ago 28
Javascript Question

disabling and enabling enter keypress event in javascript

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>


$(document).keypress(
function(event){
if (event.which == '13') {

event.preventDefault();

$("#j").focus();


}


});


</script>
</head>
<body>
<form id = "form1" action ='<?php echo $_SERVER['PHP_SELF']; ?>' method = "post">
<input type = "text" name = 'i' id = 'i' autofocus>
<input type = "text" name = 'j' id = 'j'>
<input type = "submit" name = 'submit' value = 'submit'>
</form>

</body>
</html>

<?php


echo $_POST['i'];
echo $_POST['j'];


?>


In the above code, I initially disable enter key press event. I am using a barcode scanner which already gives a carriage return. This lets me focus to the next input field after the first input field is scanned using the barcode scanner. However i wish to submit the form when the second field is input with data through the scanner. How do I achieve this?

Answer

First add oninput function to the input tag with id j

<input type = "text" name = 'j' id = 'j' oninput="clickSubmitButton()">

Then provide id to submit button.

<input type = "submit" name = 'submit' id='submitbutton' value = 'submit'>

At last add the javascript code to click the button automatically.

function clickSubmitButton(){
document.getElementById("submitbutton").click(); //id of the submit button to be clicked
}
Comments