Scan barcode into a specific textbox - javascript

I am working on bar-code scanners. The bar-code scanner that I am using is a plug-n-play type and scans the code automatically wherever you place the cursor. But what i want is that whether i can scan it to a specific text-box on a web page everytime my scanner reads a code
For eg, if my form looks like this
<input type="text" name="txtItem" id="txtItem" class="m-wrap w-120" tabindex="6">
<input type="text" name="itemId" id="itemId" class="m-wrap w-120" tabindex="6">
<input type="text" name="itemName" id="itemName" class="m-wrap w-120" tabindex="6">
<input type="text" name="itemQty" id="itemQty" class="m-wrap w-120" tabindex="6">
so everytime i scan a code it should always appear in the txtitem text-box no matter where my current focus is.
Can anybody guide me or help me find a solution here??

Some Barcode Scanners act just like another input device. The form cannot tell the difference between information being entered by a keyboard vs. a scanner unless you use a timer to monitor how quickly it is entered.
Some scanners "paste" the values in to the focused control - others send each individual key stroke.
The following JSFiddle is able to detect when input occurs when characters are sent individually on a single control:
http://jsfiddle.net/PhilM/Bf89R/3/
You could adapt this to make it a delegate for the whole form and remove the input from the control it was input into and put it into the correct form.
The test html for the fiddle is this:
<form>
<input id="scanInput" />
<button id="reset">Reset</button>
</form>
<br/>
<div>
<h2>Event Information</h2>
Start: <span id="startTime"></span>
<br/>First Key: <span id="firstKey"></span>
<br/>Last Ley: <span id="lastKey"></span>
<br/>End: <span id="endTime"></span>
<br/>Elapsed: <span id="totalTime"></span>
</div>
<div>
<h2>Results</h2>
<div id="resultsList"></div>
</div>
The Javascript for the sample fiddle is:
/*
This code will determine when a code has been either entered manually or
entered using a scanner.
It assumes that a code has finished being entered when one of the following
events occurs:
• The enter key (keycode 13) is input
• The input has a minumum length of text and loses focus
• Input stops after being entered very fast (assumed to be a scanner)
*/
var inputStart, inputStop, firstKey, lastKey, timing, userFinishedEntering;
var minChars = 3;
// handle a key value being entered by either keyboard or scanner
$("#scanInput").keypress(function (e) {
// restart the timer
if (timing) {
clearTimeout(timing);
}
// handle the key event
if (e.which == 13) {
// Enter key was entered
// don't submit the form
e.preventDefault();
// has the user finished entering manually?
if ($("#scanInput").val().length >= minChars){
userFinishedEntering = true; // incase the user pressed the enter key
inputComplete();
}
}
else {
// some other key value was entered
// could be the last character
inputStop = performance.now();
lastKey = e.which;
// don't assume it's finished just yet
userFinishedEntering = false;
// is this the first character?
if (!inputStart) {
firstKey = e.which;
inputStart = inputStop;
// watch for a loss of focus
$("body").on("blur", "#scanInput", inputBlur);
}
// start the timer again
timing = setTimeout(inputTimeoutHandler, 500);
}
});
// Assume that a loss of focus means the value has finished being entered
function inputBlur(){
clearTimeout(timing);
if ($("#scanInput").val().length >= minChars){
userFinishedEntering = true;
inputComplete();
}
};
// reset the page
$("#reset").click(function (e) {
e.preventDefault();
resetValues();
});
function resetValues() {
// clear the variables
inputStart = null;
inputStop = null;
firstKey = null;
lastKey = null;
// clear the results
inputComplete();
}
// Assume that it is from the scanner if it was entered really fast
function isScannerInput() {
return (((inputStop - inputStart) / $("#scanInput").val().length) < 15);
}
// Determine if the user is just typing slowly
function isUserFinishedEntering(){
return !isScannerInput() && userFinishedEntering;
}
function inputTimeoutHandler(){
// stop listening for a timer event
clearTimeout(timing);
// if the value is being entered manually and hasn't finished being entered
if (!isUserFinishedEntering() || $("#scanInput").val().length < 3) {
// keep waiting for input
return;
}
else{
reportValues();
}
}
// here we decide what to do now that we know a value has been completely entered
function inputComplete(){
// stop listening for the input to lose focus
$("body").off("blur", "#scanInput", inputBlur);
// report the results
reportValues();
}
function reportValues() {
// update the metrics
$("#startTime").text(inputStart == null ? "" : inputStart);
$("#firstKey").text(firstKey == null ? "" : firstKey);
$("#endTime").text(inputStop == null ? "" : inputStop);
$("#lastKey").text(lastKey == null ? "" : lastKey);
$("#totalTime").text(inputStart == null ? "" : (inputStop - inputStart) + " milliseconds");
if (!inputStart) {
// clear the results
$("#resultsList").html("");
$("#scanInput").focus().select();
} else {
// prepend another result item
var inputMethod = isScannerInput() ? "Scanner" : "Keyboard";
$("#resultsList").prepend("<div class='resultItem " + inputMethod + "'>" +
"<span>Value: " + $("#scanInput").val() + "<br/>" +
"<span>ms/char: " + ((inputStop - inputStart) / $("#scanInput").val().length) + "</span></br>" +
"<span>InputMethod: <strong>" + inputMethod + "</strong></span></br>" +
"</span></div></br>");
$("#scanInput").focus().select();
inputStart = null;
}
}
$("#scanInput").focus();
The code above does not support copy/paste, but in our situation this is unlikely to happen anyway.

You need to listen on "paste" event using jQuery
$("input").on("paste",function(e){
$("#txtItem").focus();
});
Here is a example:
http://jsfiddle.net/T6VdS/

I would think the scanner is just being seen as a text input device like a keyboard and outputting text. Unless there is a way to identify that text then the answer is likely to be that there isnt an easy solution.
If the code you are receiving is always in the same form and can be identified with a regular expression you might be able to move it into the correct box by somehow buffering the input (I would expect the scanned code to come in a series of keypresses that are far faster than a human would input) and running a regex over it...

Add a prefix to the text that the scanner outputs (almost all scanner will let you do this) and then when any input starts with that prefix you know its the scanner.
To catch the input with jquery you might do something like this:
//presuming the scanner acts like a keyboard
$(document).keypress(function (e) {
//do something to match the 'key presses'
//focus to the input and put the rest of the string in there
});

The best way is to put
data into scanned code. Almost all scanners support such programming. Many of them can be programmed via control barcodes, that printed in manual.
I use the Ctrl+Char for Symbol scanner,
F9 data F10 for Honeywel bluetooth scanner.
Wasp scanner does not support Ctrl+character combination. So I use
[Data] format for Wasp.
Then I catch the first symbol (say [ char) in program an position the cursor in search box. Upon receiving the last character (in my case ] char) send the contents of into search routine.

Related

Pressing enter in a html input box and following a hyperlink

In my php file I have the following:
<a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='. $_GET['page'] .'&record=' . $record_number . '"">' . $record_number . '</a>
This sends a user somewhere based on the current page value and record value, it is framed in a pagination type situation, so it goes to the next record, it works, its fine.
I also have a text input box, the idea is that a user can type a number and press enter and if that record exists the user goes to that record. If for instance the user chooses record 23, the code would be like this:
<a class="page-link" href="'.$_SERVER['PHP_SELF'].'?page='. $_GET['page'] .'&record=23"">23</a>
So far so good, obviously I'll add in an if ($record_number >= $max_record) for good measure.
Now the question, I would like the users to be able to enter a value into an input box, press enter and follow the hyperlink, how is this achieved?
<input type="text" style="width:200px;" class="form-control float" id="defaultFormControlInput" placeholder="Go to record" aria-describedby="defaultFormControlHelp">
--- UPDATE ---
The below is the 'enter' function so the event listener knows when the enter key is pressed. Given #imvain2's answer below a 'Go' hyper link is displayed and when the link is clicked it functions as required. However, I would like to bypass the link creation so that when 'enter' is pressed then the link is followed without the need for creating a hyperlink first.
document.querySelector('#input').addEventListener('keypress', function (e) {
if (e.key === 'Enter') {
// code for enter
let url = "?page=artefact&record=" + e.target.value;
goLINK.classList.toggle("active");
goLINK.href = url;
}
});
You can use javascript.
I'm using URLSearchParams to get the query string parameter for page. Then in an keyup event I'm looking for the enter button and putting together the URL and adding it an anchor and displaying that anchor by toggling a class called active
let input = document.querySelector("#defaultFormControlInput");
let goLINK = document.querySelector(".goLINK");
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
input.addEventListener("keyup",function(e){
if(e.keyCode == 13){
let url = "?page=" + (params.page || "1") + "&record=" + e.target.value;
goLINK.classList.toggle("active");
goLINK.href = url;
}
});
.goLINK{display:none;}
.goLINK.active{display:block;}
<input type="text" style="width:200px;" class="form-control float" id="defaultFormControlInput" placeholder="Go to record" aria-describedby="defaultFormControlHelp">
<a class="goLINK" href="">Go</a>

HTML Input type text not accepting space keystrokes

I’m having a very odd issue with an input type text field… it won’t accept “space” keystrokes. For example, if I want to write John Smith, the input only would allow JohnSmith (no spaces). There are a couple of particularities about this field. It is dynamically created, and it has been embedded inside a SumoSelect (jQuery Dropdown Plugin) dropdown list. The idea is that if I need to enter a new option that’s is not available, I can enter it in the input field, and it is added to the dropdown list.
Adding option JS code:
$('#aip').SumoSelect();
$('.aipPanel .options').append('<li class="opt" id="addAIP" style="padding-right: 0;width: 94%;"><input placeholder="Add new AIP" style="width:75%;" id="addNewAIPInput" onkeypress="myFunction(event)" type="text"/><a class="btn btn-large" href="#" style="background:#699;line-height:30px;padding:.3em;width:20%;margin-left:0.8em;height:28px;color:#fff;font-weight:700;border-radius: 4px;" id="addNewAIPBtn"><i class="fas fa-plus-square"></i></a></li>');
$("#addNewAIPBtn").click(function() {
var inputValue = $('#addNewAIPInput').val();
if (inputValue !== '') {
$('#aip')[0].sumo.add(inputValue);
$('#aip')[0].sumo.reload();
$('#aip')[0].sumo.selectItem(inputValue);
}
});
I added an onkeypress function just for testing. It recognizes all keystrokes except... "space":
function myFunction(event) {
var x = event.which || event.keyCode;
console.log("The Unicode value is: " + x);// It works just fine!!!
if(event.which === 32){
console.log('space entered'); // Nothing happens here!!!
event.target.value = event.target.value + ' ';// just for testing
}
}
Everything else works just fine. The new option is added to the dropdown list. I can enter any letter on the input box, but not "spaces".
Any ideas what could be happening here?

Extracting data from array after HTML form submission (keypress event)

So I have a HTML form with a keypress event listener recording the charCode of the key pressed and then convert that charCode to a String of the letter related to the key.
Each time a letter is entered to the form, a new entry is created in input_array[].
I have each letter in the alphabet stored as a SVG within JS variables in a different part of my main.js file and I would like to be able to read what letters have been stored in input_array[] and then display the SVG appropriate to that letter on a new page once the form has been submitted.
I've tried using the method below to extract the data from the array, but it fires on the first keypress and therefore I can't get all of the array data to then display the 4 letters. I also feel like there has to be a more efficient way.
var letter_one = input_array[0];
var letter_two = input_array[1];
var letter_three = input_array[2];
Here's a JSFiddle, to show a basic version of what I'm trying to do. If you open the console you will see how input_array[] is being created.
I'm still very new to this language, so any help would be greatly appreciated.
As you suspected, this is much simpler than you're making it :)
When the form is submitted you can just snag the value from the input:
function handleSubmit() {
var val = document.getElementById('user_input').value;
validate(val);
console.log(val);
var letter_one = val[0];
var letter_two = val[1];
var letter_three = val[2];
var letter_four = val[3];
return false; // stops POST for dev
}
https://jsfiddle.net/1htpm6ag/
That being said, if you are actually doing this on a POST then on the page you are POSTing to you'll have to snag this from the POSTed form data, which is entirely different. Are you trying to do this in client side JS or a POST handler?
If I am understanding you correctly is sound like you want to do the following.
On Page 1 user enters text into textfield.
On Submit send that text to page 2.
On Page 2 convert that text into an array of letters to associate with SVG paths to display.
If the above is the case you need a lot less javascript.
Page 1: Should only have your form with your text box and a submit button so the data is submitted to the next page using the GET method.
Page 2: Here is where you will need the Javascript to retrieve that data sent across and process it into your array of letters. I would also filter for non-letter characters as well.
I have created an example form in the code below that submits to itself and then the javascript script tag will pull the variable from the url and process it into an array of letters. In your case you would move the Javascript to page 2.
<script type="text/javascript">
(function(){
function getParamValue(param) {
var urlParamString = location.search.split(param + "=");
if (urlParamString.length <= 1) return "";
else {
var tmp = urlParamString[1].split("&");
return tmp[0];
}
}
function isLetter(c) {
return c.toLowerCase() != c.toUpperCase();
}
var user_input = getParamValue('user_input');
var char_array = null;
if(user_input !== ''){
char_array = user_input.split("");
char_array = char_array.filter(isLetter);
for(var i in char_array){
console.log('Char ' + i + ' = ' + char_array[i]);
}
}
})();
</script>
<body>
<form id="user_form" class="" action="?" method="GET">
<input type="text" name="user_input" />
<input type="submit" value="submit">
</form>
</body>

Get Dropdown Box to Appear from TextBox

The following excel vba macro will open a webpage and insert "500010" into a text box. If you manually type the same number into the textbox, a dropdown box will appear with further selections. This doesn't occur with the programmatic number entry. I've tried a number of ways to programmatically get this dropdown box to appear, a few are shown in my code, but to no avail.
Sub test()
URL = "http://www.bseindia.com/markets/equity/EQReports/StockPrcHistori.aspx?expandable=7&flag=0"
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
ie.navigate URL
Do Until (ie.readyState = 4 And Not ie.Busy)
DoEvents
Loop
ie.Document.getElementById("ctl00_ContentPlaceHolder1_GetQuote1_txtscrip_code").Value = 500010
' click the textbox to get the dropdown box to appear
ie.Document.getElementById("ctl00_ContentPlaceHolder1_GetQuote1_txtscrip_code").fireevent ("onClick")
ie.Document.getElementById("ctl00_ContentPlaceHolder1_GetQuote1_txtscrip_code").Click
end sub
If I look at the source code for the webpage, I see the following prior to information about the textbox.
<script type="text/javascript">
function cleartext1(a) {
if (a.value == "Scrip code/Scrip Name")
a.value = '';
}
function Filltext1() {
a.value == "Scrip code/Scrip Name"
}
function ClearTextBox(a)
{
if (a.value == a.defaultValue) a.value = "";
}
function FillTextBox(a)
{
if (a.value == "") a.value = a.defaultValue;
}
function HiddenValue(hdn) {
var hvalue = document.getElementById(hdn).value;
if (hvalue != "")
{
var s1=hvalue.split("|");
location.href = "/StockReach/AdvanceStockReach.aspx?scripcode=" + s1[0];
return true;
}
else
return false;
}
// function chk(e)
// {
// if(window.event)
// {
// var key=window.event.keyCode;
// if (key == 13)
// {
// var btn = document.getElementById('btnGetQuote');
// // HiddenValue('hdnIdAsset');
//
// btn.click();
// //btn.focus();
// }
// }
// }
</script>
<div id="ctl00_ContentPlaceHolder1_GetQuote1_Pn1" onkeypress="return noenter(event);">
<table border="0" cellspacing="0" cellpadding="2" align="left">
<tr>
<td style ="padding-right:10px;">
<input value="" id="divshow" type="hidden" />
<input value="" id="hdnIdAsset" type="hidden" /><input name="ctl00$ContentPlaceHolder1$GetQuote1$hdnValue" type="hidden" id="ctl00_ContentPlaceHolder1_GetQuote1_hdnValue" />
<input name="ctl00$ContentPlaceHolder1$GetQuote1$txtscrip_code" type="text" maxlength="500" id="ctl00_ContentPlaceHolder1_GetQuote1_txtscrip_code" value="Scrip code/Scrip Name" class="textbox2" onclick="javascript:selecttxt(this);" onkeypress="javascript:noenter(event);return chkkey(event,this);" onfocus="cleartext1(this);" onblur="FillTextBox(this)" onkeyup="javascript:showDivSelect(event,'Asset','http://www.bseindia.com/common/backpageAsset.aspx',this,this.value,3,'0',false);" style="width:160px;" />
I'm not very familiar with writing javascript functions for vba, but I tried putting the following in my macro, but it created an error.
f = "function (hiddenvalue) 'http://www.bseindia.com/markets/equity/EQReports/StockPrcHistori.aspx?/StockReach/AdvanceStockReach.aspx?scripcode=500010').value = 'True';}"
ie.Document.parentWindow.execScript f, "jscript"
ie.Document.getElementById("ctl00_ContentPlaceHolder1_GetQuote1_txtscrip_code").Click
Am I on the right track, is a javascript function in my code what's needed here? Can someone help me come up with the code to get the dropdown box to appear?..TIA, Ron
The input box where you write the value 500010 calls a javascript function 'showDivSelect' in event 'onkyeup'. Inside of this function ajax call is made to the page http://www.bseindia.com/common/backpageAsset.aspx and the results are shown in the div 'divSelAsset_1' (has display:none). So you have to fire 'onkeyup' event from VBA but have to pass the corrent event argument (which is prpbably the IDOMKeyboardEvent instance ... is it possible to create KeyboardEvent object in VBA?).
Dim evt As IDOMKeyboardEvent
Set evt = doc.createEvent("KeyboardEvent")
' evt.Key = "5" ... Key is read-only, so how to say which Key should the event be for?
Dim txtscrip_code As HTMLInputElement
Set txtscrip_code = ie.document.getElementById("ctl00_ContentPlaceHolder1_GetQuote1_txtscrip_code")
txtscrip_code.Focus
txtscrip_code.FireEvent "onkeyup()", evt
... But this will not work :-(.
Maybe you could try to call the function 'showDivSelect' from VBA directly. This function has this signature:
function showDivSelect(e, flag, page, objtxtinput, valobjtxtinput, mintxtlength, what, varbool, bSusp)
Execute javascript from VBA could be possible like this:
ie.document.parentWindow.execScript("code", "JavaScript")
Have a look e.g. here:
http://msdn.microsoft.com/en-us/library/ie/ms536420(v=vs.85).aspx
In javascript there you can create keyboard event like this:
In JavaScript, how can I create my own Keyboard event?
Good luck!

In JavaScript, how do I detect whether or not the input contains letters?

My code is below, it outputs what the user is typing in the text box. It should output an error message if the user puts anything other than a number. I'm confused as to how to do this, though. Quite frankly, I'd settle with it being able to detect whether or not the first letter of input is a B, but I can't quite figure that out either and the former option is preferred.
HTML
<label for="bannerID">Banner ID: B</label><input type="text" name="bannerID" id="bannerID" onkeyup="showBannerID()" value="" /><br />
<p id="bannerOutput"></p>
JavaScript
function showBannerID() {
var textInput = document.getElementById('bannerID').value;
if (textInput.length == 0) {
document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Field can't be empty!</strong>";
}
else if (textInput.charAt(0) == "B") {
document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Please omit the B! It's not necessary.</strong>
}
else {
document.getElementById('bannerOutput').innerHTML = "Your Banner ID is: <strong>B" + textInput + "</strong>.";
}
}
You can use regular expressions to search for anything other than numbers:
if (/[^\d]/.test(textInput)) {
/* error stuff */
}
You can use isNaN() (Not a Number) as a condition.
isNaN(123) would give false, isNaN("hello") would give true.

Categories