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!
Related
I have this problem to solve
In this form a user types in a value. (Actually,
a scanner scans a number and virtually types it - without
sending extra keys like Enter)
I need to contantly check - while typing is going on - if the value in the input
box is a 8 digit number (starting with "4") and if it
is, fire the submit action.
I tried to log any changes. But the code below only logs changes after I leave the input box.
<form action="#" onsubmit="return validateFormOnSubmit(this);">
<input name="boarding_id" value="" width="600px" onChange="console.log(this.value);">
<button type="submit" name="action" class="btn btn-primary" value="0">Scan</button>
</form>
Is there a Javascript way to pass the value of the box to a function whenever a single letter is typed?
Note: While the form displays a "scan" button, the goal is to have that button automatically clicked as soon as 8 digits have been entered and been declared valid by a validator function.
It is generally not a good idea to use inline event handlers.
Actually, a scanner scans a number and virtually types it
So, as far as I understand you want to show the result of some scanning function that inputs values and check the input value. Looks like there's not really a need for a change handler. Here's a minimal reproducable example for a dummy scanning function. It uses event delegation for handling the button click.
document.addEventListener(`click`, handle);
function scan(i = 0) {
const inp = document.querySelector(`[name='boarding_id']`);
const showIt = document.querySelector(`#showIt`);
if (i < 1) {
inp.value = 4;
i += 1;
} else {
const nr = 1 + Math.floor(Math.random() * 9);
const currentValue = inp.value;
inp.value += nr;
}
if (i < 8) {
showIt.textContent = `Scanning ...`;
return setTimeout( () => scan(i + 1), 100)
}
showIt.textContent = `Done!`;
document.querySelector(`#scan`).removeAttribute(`disabled`);
}
function handle(evt)
{
if (evt.target.id === `scan`) {
evt.target.setAttribute(`disabled`, `disabled`);
return scan();
}
}
<input name="boarding_id" value="" width="600px" readonly>
<span id="showIt"></span>
<p><button id="scan">Scan</button></p>
const input = document.querySelector('input');
const demo_variable = document.getElementById('demo_variable');
input.addEventListener('input', updateValue);
function updateValue(e) {
demo_variable.textContent = e.target.value;
}
<form action="#" onsubmit="return validateFormOnSubmit(this);">
<input name="boarding_id" value="" width="600px" >
<button type="submit" name="action" class="btn btn-primary" value="0">Scan</button>
<p id="demo_variable"></p>
</form>
You can use the input event, which also triggers when editing happens without the keyboard (mouse drag/drop, context menu, other device...).
Use a regular expression to do the verification. You can access the form via the form property of the input element:
<input name="boarding_id" oninput="/^4\d{7}$/.test(this.value) && this.form.submit()">
It is however better practice to bind events not with HTML attributes, but with JS code. For that purpose give the form element an id attribute (like id="frm"), and then:
const form = document.getElementById("frm");
form.boarding_id.addEventListener("input", (e) => /^4\d{7}$/.test(e.target.value) && form.submit());
You can achieve this in multiple ways. I have shown one below
function myFunction() {
const userInput = document.getElementById("numberinput").value;
document.getElementById("displaynumber").innerHTML = "You typed: " + userInput;
}
function submtValue(value) {
const submitValue =document.getElementById("numberinput").value;
if(submitValue.length === 8) {
// do your validation
alert("Bingo..!!")
}
else {
alert("Minimum length required is 8")
}
}
<input type="number" id="numberinput" oninput="myFunction()">
<p id="displaynumber"></p>
<button type="submit" value="Submit" onclick="submtValue()">Submit</button>
You can add key event like onkeydown or onkeypress on input which will trigger everytime type inside input and once condition fulfilled submit form
i keep trying everything to get these alerts to pop up correctly. i started out using nested functions, then threw them out and put it all in one function, and now when I press enter after filling out any one text box it does nothing at all, just puts the strings in the url, instead of alerting like it was before. I'm not sure if its my function call or anything else because I double checked everything and it all seems to check out to me. here is the entire code that doesnt do anything:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- VARIABLE DECLARATION -->
f1.city.focus();
function check_form()
{
at_sign = email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
}
else if(document.f1.state.value.length != 2 || !(state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
}
else if(document.f1.zip.value.length != 5 || document.f1.zip.value.isNaN()==true)
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
}
else if((at_sign<1) || (email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" action="smartform.html">
<b>City</b>
<input type = "text" name = "city" size = "18" value="" onSubmit = "javascript:check_form()">
<b>State</b>
<input type = "text" name = "state" size = "4" value="" onSubmit = "javascript:check_form()">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="" onSubmit = "javascript:check_form()">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="" onSubmit = "javascript:check_form()">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form()">
</form>
</BODY>
</HTML>
edit: nothing seems to be working that everyone says.. here is my new code:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
f1.city.focus();
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
if(f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
return false;
}
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN()==true))
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
return false;
}
else if((at_sign<1) || (f1.email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
return false;
}
else
{
//document.write("Form completed");
}
return false;
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" onSubmit="return check_form(this)">
<b>City</b>
<input type = "text" name = "city" size = "18" value="">
<b>State</b>
<input type = "text" name = "state" size = "4" value="">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="">
<input type = "submit" name = "button" value = "Done" onclick = "return check_form(this)">
</form>
<b>hi</b>
</BODY>
</HTML>
still get no alerts... i put that hi up and got that.. but no alerts......
alright, I know I should probably be using getElementByID, but my new focus is to find out precisely why my code isn't working. Since my lecture outline examples didnt use this method, I want to figure out why the following code doesnt activate alerts like it used to. I simplified it to this:
<!DOCTYPE html>
<html>
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function check_form()
{
document.write("Form started");
var at_sign = document.f1.email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
document.f1.city.focus();
//return false;
}
else if(document.f1.state.value.length != 2 || !(document.f1.state.charCodeAt('0')>=65 && document.f1.state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
document.f1.state.focus();
//return false;
}
else if(document.f1.zip.value.length != 5 || isNaN(document.f1.zip.value)==true)
{
alert('Please enter a 5 digit zip code');
document.f1.zip.focus();
//return false;
}
else if((at_sign<1) || (document.f1.email.value.length<3))
{
alert('Please enter a valid email address');
document.f1.email.focus();
//return false;
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY onLoad= "javascript:document.f1.city.focus();">
<form name = "f1" action="smartform1.html" onSubmit="javascript:check_form();">
<b>City</b>
<input type = "text" name = "city" size = "18">
<b>State</b>
<input type = "text" name = "state" size = "4">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5">
<b>Email</b>
<input type = "text" name = "email" size = "18">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form();">
</form>
</BODY>
</HTML>
I get no errors in console, and now when I type something in, I get the test line "form started" to appear for a split second, along with some mysterious error, and then it all disapears and shows the form. but my question is, why doesnt an alert happen along the way to this result? it seems like even if the page got overwritten, it should still pop up. also, is there a way to pause it with code/and or debugging before it gets to the point where its overwritten? so my basic question is: why don't the alerts pop up, and how do I get the alerts to popup and the focus to remain in the correct field where the function left off within the if/else statement?
update 2: i did a quick screen cap of the errors and it turns out f1.email etc were undefined and indeed causing the thing to not work. So I still want to know how to pause it with code or in the debugger, the posts and links didnt exactly seem to be clear 100% on it. once im in the consonle and in debug mode, where exactly do i go from there to let the program pause on error?
also: if I declare the getElementByID variables at the top of my script in the header, then use them in the function, should that work without all the other event handling methods? I'm attempting this as i type.
You should put the submit listener on the form and pass a reference to the form, and return whatever value the function returns, e.g.
<form onsubmit="return check_form(this);" ...>
You should reference the controls as properties of form using their name, don't use the name as a global variable. And declare all variables.
So the function looks like:
function check_form(form) {
var at_sign = email.search(/#/);
if (form.city.value.length < 1) {
alert('Please enter a city');
f1.city.focus();
// cancel submit by returning false
return false;
} else if (form.state.value.length != 2 || !(form.state.charCodeAt(0) >=65 && state.charCodeAt(0)<=91)) {
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
...
}
You should probably be using a regular expression or lookup for validating the state value rather than charCodeAt.
Using document.write after the page has finished loading (e.g. when submitting the form) will erase the entire content of the page before writing the new content.
Edit
Here's what's wrong with your new code:
<SCRIPT LANGUAGE="JavaScript">
Get rid of the language attribute. It's not harmful (well, in a very specific case it might be).
f1.city.focus();
f1 has no been defined or initialised (see comments above about element names and global variables)
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
f1.email is an input element, it has no search property, you can't call it. It does have a value property that is a string, perhaps you meant:
var at_sign = f1.email.value.search(/#/);
Then there is:
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
again you have forgotten the value property for two of the three expressions, and forgotten to use f1 in the third. You want:
else if(f1.state.value.length != 2 || !(f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=91))
Note that this requires users to enter the state in capital letters, it might help to tell them about that.
Then there is:
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN() == true))
isNaN is a global variable, not a method of strings. If no value has been entered, then the value is the empty string and isNaN('') returns false. If you want to test that 5 digits have been entered then use:
else if (!/^\d{5}$/test(f1.zip.value))
There is no need to test against true, just use it, nor is there a need to group simple expressions:
else if (f1.zip.value.length != 5 || isNaN(f1.zip.value))
Then finally, if all the test pass:
return false;
that stops the form from submitting. You can omit this return statement, returning undefined will let the form submit. Or return true if you really want.
Ok I want to answer your question but first things first lets walk through your
code and clean it up.
Use this as a template of properly formated code:
<!DOCTYPE html>
<html>
<head>
<title>Smart Form</title>
</head>
<body>
<!-- Code goes here -->
<script type="text/javascript">
</script>
</body>
</html>
Tags & attributes don't need to be capitalized. Javascript comments are like this:
/** Comment. */
Html comments are like this:
<!-- Comment. -->
Also nitpick: attributes should be followed by an equal sign not a space. i.e.
<form name="f1" id="smartForm" action="smartform.html"> ... </form>
Next up proper event binding.
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
Next up I'm going to teach you how to fish real quick so you can figure out why this was broken for you and how to fix these bugs in the future. Open up the developer console. Evergreen browsers (Chrome, Firefox etc...) have good ones these day. The trick you should know is how to evaluate your code so that you can see if you did something wrong or not in how you're accessing your data. So look up how to open up the developer console in your browser for your platform and type this into your console:
1+1
Should evaluate to: 2.
Next type: document
If you click around you can see that you can walk through the dom a little bit.
Next load up your smartForm app with my changes above and type:
document.getElementById('smartForm')
You should see your element. This is how to properly query objects in the dom.
You'll notice that if you type document.smartForm doesn't work. You should get null, this should tell you that there should be a way to get the element from the document. Hint, it's getElementById. So if you put id's on all your inputs then you can make a list of all the document objects you can query:
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
Next you can start querying the values and such like you were doing:
cityElement.value.length != 2
A cleaned up version would look like this:
<!DOCTYPE html>
<html>
<head>
<title>Smart form</title>
</head>
<body>
<form id='smartForm' action='smartform.html'>
<b>City</b>
<input type="text" id="city" size="18">
<b>State</b>
<input type="text" id="state" size="4">
<b>Zip Code</b>
<input type="text" id="zip" size="5">
<b>Email</b>
<input type="text" id="email" size="18">
<input type="submit" value="done">
</form>
<script type="text/javascript">
var validateForm = function(evt) {
var error = false;
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
if (cityElement.value.length != 2 ||
!(state.charCodeAt(0) >= 65 && state.charCodeAt(0) <= 91)) {
error = true;
alert('oops');
cityElement.focus();
}
// etc..
if (error) {
evt.preventDefault();
}
};
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
</script>
</body>
</html>
Ok a couple more things I noticed. charCodeAt is for strings only. "hi".chatCodeAt not element.charCodeAt. Also you have this random variable at_sign.
You can save yourself a TON of time and you can learn how to diagnose where the issues are by reading this: https://developer.chrome.com/devtools/docs/console
Learning how to diagnose where the issues are is the single best skill you can learn while trying to get a grapple on javascript. I cannot emphasize this enough, learn how to debug, and you will learn how to program orders of magnitude faster. Trust me, let debugging tutorials be your bread at butter!
Full working example of your code:
http://codepen.io/JAStanton/pen/tjFHn?editors=101
A little less verbose version:
http://codepen.io/JAStanton/pen/iBJAk?editors=101
onSubmit goes in the form, not the inputs, w/o the javascript: Solved =p
<form onsubmit="return check_form();" ...
There are several mishaps in your code that might also cause errors and prevent that from working
Also, check if there are mistakes (like the HTML comment inside script), if an error happens in javascript and is untreated, all javascript in that context stops working. You can check that with any browser debugger (usually F12 will show you a window and display errors if they happen)
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.
I need some help with something... say I have the following form...
<form name="" id="" method="" action="">
<input type="text" id="text1" name="text1" />
<br />
<br />
<input type="text" id="text2" name="text2" />
<br />
<br />
<input type="text" id="text3" name="text3" />
<br />
<br />
<input type="text" id="text4" name="text4" />
<br />
<br />
<input type="submit" value="let's go" disabled="disabled" />
</form>
Now I want to have a simple script to enable the submit when the values of the text boxes are not an empty string or null...
So I have something like this.. which I will bind to the window.onload
function enableButton(){
var formitemsArray = ['text1','text2','text3','text4'],
i;
// Loop through all items
for(i=0;i<formitemsArray.length;i++){
// validate the length on the keypress...
formitemsArray.onkeypress = function(){
// loop through all the items again
for(j=0;j<formitemsArray.length;j++){
if(formitemsArray[j] == "" || formitemsArray[j] == null ){
// return false or something???
}else{
document.getElementById("submitButton").disabled = false;
}
}
}
}
}
Now I think I'm on the right lines to a solution but I'm getting lost when trying to make sure that all the items are greater than a zero length string as I'm returning false too soon. Can someone set me straight please?
Welcome to event bubbling!
This does the following: listen to an event (onkeypress) on the whole element and all its children! Which means you can do the following:
document.getElementById('form-id').onkeypress = function(e) {
var text1 = document.getElementById('text1'),
text2 = document.getElementById('text2'),
text3 = document.getElementById('text3'),
text4 = document.getElementById('text4')
if (text1.value.length > 0 &&
text2.value.length > 0 &&
text3.value.length > 0 &&
text4.value.length > 0) {
document.getElementById('submit-button').disabled = false
}
// As an aside, for later: if you want to get the element
// that triggered the event, you have to do the following
// to be cross-browser:
var evt = e || window.event, // IE doesn't get the event passed by argument
target = e.target || e.srcElement // 'target' is official, old versions of FF used 'srcElement'
// With the 'target' variable, you can now play.
}
There is another more generic solution, but it might not fit your needs (note that it requires a forEach shim:
// Declare a counter variable
var count = 0
document.getElementById('form-id').onkeypress = function(e) {
// Get all the inputs!
var inputs = this.getElementsByTagName('input')
// Now loop through all those inputs
// Since a NodeList doesn't have the forEach method, let's borrow it from an array!
[].forEach.call(inputs, loopThroughInputs)
}
function loopThroughInputs(input) {
// First check the type of the input
if (input.type === 'text') {
// If the value is correct, increase the counter
if (input.value.length > 0) {
count++
}
// If the 4 inputs have increased the counter, it's alright!
if (count === 4) {
document.getElementById('submit-button').disabled = false
}
}
}
And now this code was proposed by #Esailija, and it is way better and cleaner. However, it also requires ES5-Shim (for the every method):
document.getElementById('form-id').onkeypress = function(e) {
var inputs = [].slice.call( this.querySelectorAll( '[type=text]') );
document.getElementById('submit-button').disabled = !inputs.every(function(input){
return !!input.value;
});
}
(This guy is brillant, just don't tell him)
There are a few ways you can do this... One would be to keep the button enabled but use javascript to check the validity of the form data upon submission. The benefit to this is that the validation code is only run once, when the user clicks submit and is expecting his data to be validated (at least I do) .
function validateForm() {
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
if( formElement.elements[i].value.length === 0 ) {
return false;
}
return true;
}
}
The other way is live validation, which would validate each input onBlur (focus lost). This method has the benefit of showing the user in real time what values are bad, however this can be very resource heavy depending on the number of form elements and the way you introduce the check.
Personally I would go with my first suggestion; however with that said if you choose to validate each element, I would do so like this:
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
formElement.elements[i].addEventListener('blur', function() {
if( this.value.length === 0 ) {
alert('this input is invalid');
}
}, false);
}
The latter method also requires you hold onto a 'state' variable to determine whether or not the form is valid upon submission, or check all the values again.
Hope this sheds some light, and I hope my code examples help some.
If possible use jquery validation plugin instead of re-inventing the code, http://docs.jquery.com/Plugins/Validation its so easy to use.
In this jsfiddle you'll find a way to monitor the progress of form contents. If all the field conditions are fulfilled, a submit button is shown. Maybe it's useful for you. Bare in mind that client side checking of a form may be tampered with, so you always need a server side check too, if your data need to adhere to certain requirements. In other words: client side form checks are merely usability enhancements.
I am brand new in WebDevelopment and I came across the following issue.
I have an html file where a textbox is defined as well as a "View all Contents" button
The user can enter a value in the textbox and submit the data
Then repeat this action multiple times
Every time a new value is entered this value should be stored to a
Javascript array
The user will be able to view the contents of the Javascript array
when clicking on the button "View all Contents".
So my problem is how these values are stored dynamically in Javascript and printed when the user is finished.
Your answer is very much appreciated.
Best Regards
Olga
A very trivial example: http://jsfiddle.net/pimvdb/unEMp/.
<input type="text" id="textbox">
<br>
<input type="button" id="add" value="Add">
<br>
<input type="button" id="view" value="View all Contents">
with:
var arr = []; // the array
document.getElementById('add').onclick = function() {
arr.push(document.getElementById('textbox').value); // add textbox value to array
document.getElementById('textbox').value = ''; // clear textbox value
};
document.getElementById('view').onclick = function() {
alert(arr.join(', ')); // alert array contents as a string; elements are delimited by ', '
};
First you'll want to create your array in the global scope - this means outside of a method body, somewhere in the <script></script> body:
var myArray = new Array();
Next, you'll want to append the array with a new value each time the user clicks a button:
function myButtonClick(){
var myTb = document.getElementById("textBox1");
myArray.push(myTb.value);
myTb.value = ""; // reset the textbox
}
Next, you'll want another button handler for the click on "View All":
function myViewAllButtonClick(){
// will create a string of myArray's values, seperated by new line character
var msg = myArray.join("\n");
// will show the user all of the values in a modal alert
alert(msg);
}
Your HTML might look like:
<input type="text" id="textBox1" />
<input type="button" id="button1" value="Add Value" onclick="myButtonClick();"/>
<input type="button" id="button2" value="Show All" onclick="myViewAllButtonClick();"/>
When you get the hang of things, you can get rid of the "Add Value" button all together and use:
<input type="text" id="textBox1" onchange="onTextChanged(this)"/>
With a handler like:
function onTextChanged(e){
if(e.value == "") return;
myArray.push(e.value);
e.value = "";
}
The onTextChanged handler will fire when the user changes text in the textbox (it won't fire though until the textbox loses focus, which may make it bad for this example, but still a good JS skill to learn/understand).
Happy coding - good luck!
B
JavaScript array could be dynamicaly changed:
var array = [];
function foo() {
array.push('foo');
}
function boo() {
array.push('boo');
}
i put together a small example: http://jsbin.com/izumeb/3
<p><input type="text" id="txt"></input><button onclick="addToAll();">add to selection</button></p>
<p><button onclick="showAll();">show all</button></p>
<p id="all"></p>
and JS
<script>
var values = [];
function addToAll() {
var txt = document.getElementById("txt");
values.push(txt.value);
txt.value = "";
}
function showAll() {
var all = document.getElementById("all");
var str = "";
for (var i=0;i<values.length;++i) {
str += values[i] + "<br/>";
}
all.innerHTML = str;
}
</script>