开发者

Auto Tab when Return Key is Pressed/Scanned (php/mysql/javascript)

Hoping yet again you can help me solve a problem I've been battling with over the last few weeks..

I have a simple web-based database that I'm using to record the serial numbers of products leaving my warehouse. The system is behind our firewall and I'm not really concerned about SQL injections or anything like that.

At present the web form has the following fields:

Row 1: Product UPC (R_UPC) Row 1: Product Serial Number (R_SerialNumber) Row 2: Product Part Number (R_PartNumber) Row 2: Product Description (R_Description) Row 3: Specialist (R_Specialist) Row 3: Fulfilled By (R_FulfilledBy)

When we scan the barcode of the product, the part number and description fields are usually completed from data within the 'Products' database, however the auto-tab functionality breaks this lookup. I'm confident it's a simple fix but I just cant quite figure it out..

The barcode scanners are configured to automatically press return upon scanning the barcode which then searched the 'Products' database for a match. So I'm looking to have it so that after scanning the UPC field it automatically tabs to the next input field (Product Serial Number) and once the serial number is scanned it'll automatically tab ahead 3 boxes (to the Specialist field).

I've managed to get this pretty much working - pressing enter on the appropriate fields tabs to the correct box. However the lookup that is performed to populate the 'Part Number' and 'Description' input fields.

The goal behind this is to improve the efficiency and the general ease of use on the web-form so that we don't need to keep hitting the tab key. I'd also like to make use of something like innerText/AJAX where possible for the 'Part Number' and 'Description' fields so that they can't accidentally be edited by the user, reducing the chance for garbage data.

Here's snippits of what is probably relevant:

<!-- Tab on Return -->
<SCRIPT LANGUAGE="JavaScript">
nextfield = "R_UPC"; // name of first box on page
netscape = "";
ver = navigator.appVersion; len = ver.length;
for(iln = 0; iln < len; iln++) if (ver.charAt(iln) == "(") break;
netscape = (ver.charAt(iln+1).toUpperCase() != "C");

function keyDown(DnEvents) { // handles keypress
// determines whether Netscape or Internet Explorer
k = (netscape) ? DnEvents.which : window.event.keyCode;
if (k == 13) { // enter key pressed
if (nextfield == 'done') return true; // submit, we finished all fields
else { // we're not done yet, send focus to next box
eval('document.req_form.' + nextfield + '.focus()');
return false;
  }
 }
}
document.onkeydown = keyDown; // work together to analyze keystrokes
if (netscape) document.captureEvents(Event.KEYDOWN|Event.KEYUP);
</script>

<!-- Autocomplete Specialist Field -->
<script type="text/javascript">

// FUNCTION: Get product info from UPC
function productDetails(UPC){

// SEND AJAX REQUEST, POST UPC
$.ajax({
    type: "POST",
    url: "../includes/get_product_detail.php",
    data: "UPC=" + UPC,
    dataType: 'json',
    success: function(data){

        // FROM JSON STRING RETURN DESCRIPTION AND ADD TO form_description INPUT
        $('#form_description').val(data.description);
        $('#form_part').val(data.part_number);

    }
});

}

$(document).ready(function() {

// ADD KEYPRESS EVENT HANDLER
$('#form_upc').keypress(function(event) {
    // IF RETURN KEY IS PRESSED, FIRE productDetails FUNCTION
    if (event.which == '13') {

        // FIRE FUNCTION USING VALUE IN form_upc
        productDetails($('#form_upc').val());

    }
});
// Autocomplete Specialist Field
$("#form_specialist").autocomplete("../includes/get_specialist_list.php", {
    width: 260,
    matchContains: true,
    mustMatch: true,
    //minChars: 0,
    //multiple: true,
    //highlight: false,
    //multipleSeparator: ",",
    selectFirst: false
});


});
</script>
<!-- End -->

<!-- Disable Enter Button on Barcode Scanners causing accidental submission of data to database -->
<script language="JavaScript">

function disableEnterKey(e)
{
 var key;     
 if(window.event)
      key = window.event.keyCode; //IE
 else
      key = e.which; //firefox     

 return (key != 13);
}
</script>
<!-- End -->

<!-- Input Validation -->
<script language="JavaScript" type="text/javascript">
<!--
function checkform ( form )
{

// ** Validate Part Number Entry **
if (form.form_part.value == "") {
 alert( "Please enter Product Part Number" );
 form.form_part.focus();
 r开发者_如何学Pythoneturn false ;
}
if (form.form_part.value == "Invalid UPC") {
 alert( "INVALID Data Entered - Please Rescan UPC" );
 form.form_part.focus();
 return false ;
}
// ** END Part Number Validation **

// ** Validate Specialist Entry **
if (form.form_specialist.value == "") {
 alert( "Please enter Specialist Name" );
 form.form_specialist.focus();
 return false ;
}
// ** END Specialist Validation **

// ** Validate Fulfilled By Entry **
if (form.form_bohspecialist.value == "") {
 alert( "Please enter BoH Specialist Fulfilling Order" );
 form.form_bohspecialist.focus();
 return false ;
}
// ** END Fulfilled By Validation **
return true ;
}
//-->
</script>
<!-- END -->

And here's get_product_detail.php:

// VARIABLES
include("main.config.inc.php");

// connect to the MySQL server
$cxn = mysql_connect($runnerdbServer, $runnerdbUser, $runnerdbPass)
or die ("Sorry, could not connect to the server.");

// connect to the DB
$db = mysql_select_db($runnerdbName, $cxn)
or die ("Sorry, could not connect to the correct database.");

// GET UPC
$upc = $_POST['UPC'];

$sql = "SELECT * FROM Products WHERE P_UPC = '$upc'";

$result = mysql_query($sql) or die ('Product could not be queried');
$num = mysql_num_rows($result);

// ONLY ONE PRODUCT SHOULD MATCH
if ($num == 1){

$row = mysql_fetch_assoc($result);

$json['upc'] = $row['P_UPC'];
$json['part_number'] = $row['P_PartNumber'];
$json['description'] = $row['P_Description'];


} else {

// DUPLICATE ENTRIES?
$json['upc'] = 0;
$json['part_number'] = "Invalid UPC";
$json['description'] = "Invalid UPC";

}

// GENERATE JSON STRING
echo json_encode($json);

?>

And here's the html form side to things:

<form name ="req_form" autocomplete="off" action="../includes/new_request.php" method="post">
        <table width="100%" border="0">

          <tr>
            <td>* Product UPC: <br />                   <input type="text" name="R_UPC" onFocus="nextfield ='R_SerialNumber';" id="form_upc"/></div></td>
            <td>Product Serial Number: </br />                  <br/><input type="text" name="R_SerialNumber" onFocus="nextfield ='R_Specialist';" id="form_serial"/></div></td>
          </tr>
          <tr>
            <td>* Product Part Number: <br />                 <input type="text" name="R_PartNumber" id="form_part" /></div></td>
            <td>Product Description: <br />               <input type="text" name="R_Description" id="form_description"/></div></td>
          </tr>
          <tr>
            <td>* Specialist: <br />                  <input type="text" id="form_specialist" name="R_Specialist"  onFocus="nextfield ='R_FulfilledBy';"/></td>
            <td>* Fulfilled By: <br />
            <?php

                // Connect to DB
                connecttodb($runnerdbServer,$runnerdbName,$runnerdbUser,$runnerdbPass);
                function connecttodb($runnerdbServer,$runnerdbName,$runnerdbUser,$runnerdbPass)
                {
                global $link;
                $link=mysql_connect ("$runnerdbServer","$runnerdbUser","$runnerdbPass");
                if(!$link){die("Could not connect to MySQL");}
                mysql_select_db("$runnerdbName",$link) or die ("could not open db".mysql_error());
                }

                $tp=$_GET['U_Name']; // getting the value from query string
                $query="SELECT U_Name FROM Users ORDER BY U_Name ASC";
                $result = mysql_query ($query);
                ?>

                <select name="R_FulfilledBy" id="form_bohspecialist">
                <?
                while($nt=mysql_fetch_array($result)){

                echo "<option value='$nt[U_Name]'>$nt[U_Name]</option>";

                }
                echo "</select>";

            ?>
            </td>
          </tr>

            <td><input type="submit" id="form_submit" value="Submit" /></td>
          </tr>
      </table>
            </form>

Any help is greatly appreciated! :)


I dont think there is a nice solution for this. The browser steps through form elements when you hit tab based on default ordering and the special tabIndex attribute. Recreating this behaviour should be possible, but I'll let this to you to figure out.

// since you already are using jQuery, also use it to bind event handler
$('form[name=request_form').bind('keyup', function (e) {
  // jQuery normalizes e.which for you
  if (13 === e.which) {
    // get idnex of the element that triggered the event
    // use Array method indexOf for this
    var currentIndex = Array.prototype.indexOf.call(this.elements, e.target);
    // have we stepped through all form elements?
    if (currentIndex >= this.elements.length) {
      // submit form, should happen through default action
      // if not, uncomment the following line.
      // this.submit();
    } else {
      // focus next element
      form.elements[currentIndex + 1].focus();
    }
  }
});

And I agree with the commentators: even if the application is inside your firewall, you really should protect against SQL injections. Even your employees might try to dump your database or an attacker is able to penetrate/bypass your firewall.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜