Search code examples
javascripthtmlformsbarcode-scanner

Javascript preventing submit of a form after carriage return


I'm using a barcode-scanner to add data to some html fields. What I want to do is the following

  1. focus on first field
  2. scan and enter data into the first field
  3. switch the focus to the second field
  4. scan and enter data into the second field
  5. submit form

I tried two approaches:

  • Catching the carriage return sent by the hand scanner
  • Catching every keystroke in the textfield

Posted is the latter one.

It works sofar, but only if I leave my debug alerts in the code... If I remove them, the form is submitted...

Any idea why?

    <html>
<head>
<head>
<title>Webinterface</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>

<script type="text/javascript">
    function processForm(e) {
    if (e.preventDefault) e.preventDefault();
    return false;
}
function checkFieldC(text)
{
    if(text.length==6){
        alert("C1");
        if(document.comform.Destination.value.length>0){
            alert("C2a");
            document.forms["comform"].submit();
            return true;
        }else{    
            alert("C2b");
            document.comform.Destination.focus();            
            return false;
        }
    }
    return false;
}
function checkFieldD(text)
{

    if(text.length==9){
        if(document.comform.Container.value.length>0){
            alert("D2a");
            document.forms["comform"].submit();
            return true;
        }else{    
            alert("D2b");
            document.comform.Container.focus();            
            return false;
        }
    }
    return false;
}
</script>

<form method="POST" name="comform" action="DoSomething.php">

<br>
<table width="90%"  border="0">

    <tr>
        <td valign="top" width="150">Container (6 digits)</td>
        <td><input name="comvalue[]" type="text" id="Container" size="10" maxlength="6" onkeyup="checkFieldC(this.value)" ></td>
    </tr>
    <br>
    <tr>
        <td valign="top" width="150">Destination:</td>
        <td><input name="comvalue[]" type="text" id="Destination" size="10" onkeyup="checkFieldD(this.value)"></td> 

    </tr>

    <tr>
     <td>Confirm</td>
     <td><button name="s2" onClick="submit()" class="cssButton1">Confirm</button></td>
    </tr>    
</table>
</font>
</form>
</body>
</html>

Solution

  • Ok, I found a solution deep in this post how to prevent buttons from submitting forms

    After defining the button type

    <button type="button">Button</button>
    

    it works perfectly. Thanks for your support :)