Bar Code Scanner and Keyboard.
NOTE: My Bar Code Scanner is USB Type.
Then...
What function must be use to trigger the keyboard if i'm at auto.aspx page?
I tried this code but no success:
var barcode = document.getElementById('barcodenum');
barcode.addEventListener("keypress", function() { alert("Please use Barcode Scanner!"); document.getElementById('barcodenum').value = "";}, true);
I'm afraid you can't do that through JavaScript. If you were developing desktop app, it could be done.
EDIT:
The only one solution in JavaScript is measure the time between the keypress events. Barcode scanner is faster then human, so if you set the - experimentally invented - time limet for gaps between two keypresses, you may cope with this problem. (Source of this idea.)
As pointed out by #Robert Skarzycki above, i doubt you can integrate with the scanner using a web page.
On the keypress intercept issue.
Add this to the head section of you page.
<script type="text/javascript">
window.onload = function() {
var barcode = document.getElementById('barcodenum');
barcode.addEventListener("keyup", function() {
alert("Please use Barcode Scanner!");
document.getElementById('barcodenum').value = "";
}, true);
};
</script>
Try this code. I assum that you know about the Jquery. Run this code and type anything from the keyboard while focusing the web page and hit enter key. If this works barcode reader do the same. Configure your barcode reader to pass enter key at the end of code reading. Jquery library
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.4.js'></script>
Jquery
$(document).ready(function() {
var barcode="";
$(document).keydown(function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code==13)// Enter key hit
{
alert(barcode);
}
else if(code==9)// Tab key hit
{
alert(barcode);
}
else
{
barcode=barcode+String.fromCharCode(code);
}
});
});
Related
I'm currently in the learning phase for how the Google JS Client SDK works, since my boss needs me to learn how to integrate a Sign In button to his site to enable people to Authenticate via Google. I am testing the code for the custom Sign In button, with a touch of added functionality (like a Sign Out button), and in the process I've practically copy/pasted the code from their website. Let me show you the code first and then explain the issue, so that you can understand where the code is failing:
<script src="https://apis.google.com/js/client.js?onload=init"></script>
<script type="text/javascript">
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}';
var scopes = 'profile email';
function SignOut() {
// I know, sloppy, but the signOut method from Google doesn't work.
window.location = 'https://accounts.google.com/logout';
// Additional code if necessary.
};
function makeApiCall() {
gapi.client.load('plus', 'v1', function () {
var request = gapi.client.plus.people.get({ 'userId': 'me' });
request.execute(function (response) {
var heading = document.createElement('h4');
var image = document.createElement('img');
image.src = response.image.url;
heading.appendChild(image);
heading.appendChild(document.createTextNode(response.displayName));
document.getElementById('name').appendChild(heading);
alert('User logged in. makeApiCall() has executed.');
})
})
};
function init() {
gapi.client.setApiKey(this.apiKey);
window.setTimeout(checkAuth, 1);
console.log('Up and ready to go.');
};
function checkAuth() {
// Triggers when the page and the SDK loads.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true }, handleAuthResult);
};
function handleAuthClick(event) {
// Triggers after a user click event to ensure no popup blockers interfere.
gapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: false }, handleAuthResult);
return false;
};
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('SignInBtn');
var signoutButton = document.getElementById('SignOutBtn');
if (authResult && !authResult.error) {
var V = JSON.stringify(authResult);
localStorage.setItem('GoogleAuthResult', V);
console.log(V); // Just for testing...
var authTimeout = (authResult.expires_in - 5 * 60) * 1000; setTimeout(checkAuth, authTimeout); // As recommended by a Google employee in a video, so that the token refreshes.
authorizeButton.style.display = 'none'; // Switching between Sign In and Out buttons.
signoutButton.style.display = 'inline-block';
makeApiCall();
} else {
// Immediate:true failed so user is NOT signed in.
// Make the Sign In button the one visible and prep it
// so that it executes the Immediate:false after user click:
authorizeButton.style.visibility = 'inline-block';
authorizeButton.onclick = handleAuthClick;
signoutButton.style.visibility = 'none';
}
};
</script>
The handleAuthClick function does run on the button click, but after taking the user to the Google Sign In page, when that page brings me back, the browser kinda flickers and the handleAuthResult function does not execute. Therefore, nothing changes in the page after the successful sign in; the button displayed is the Sign In button (Sign Out button not visible) and no information is displayed on the 'name' textNode. This happens on Internet Explorer (11), Firefox (39) and Chrome (44). Also, it happens at home on my laptop (straight connection to the web via Cable broadband) and at work (on Windows 8.1 behind an Active Directory).
I began wondering so I started refreshing the browser page and after a couple of refreshes, since the script runs from the beginning, the immediate:true fires again and voilá: user is connected and API call triggers.
So, on my laptop, I changed the function being called back, in the immediate:false line's callback parameter, to the init() function and that fixed the problem: everything runs smoothly from beginning to end. Yet, this is not the way it is supposed to work. I still don't know what is going on with that line.
This morning, on my computer at work (behind Active Directory), that fix didn't work. I have to refresh the page a couple of times so that the script runs from the beginning and the immediate:true triggers recognizing the user's Signed In state and displaying the proper button on screen.
Any ideas on why does this callback fail?
You need to define your apiKey in the first section of your code
var clientId = '{my client id here}'; // for web
var apiKey = '{my api key here}'
Maybe thats the problem.
Google ApiKeys
Could you please let me know how to detect any browser back button click using java script or jquery?
I am using the below :
if(window.history && window.history.pushState){
window.history.pushState({page:this.href}, null, 'this.href');
$(window).on('popstate', function() {
event.preventDefault();
$('#releaseLicenseApp').modal();
});
}
but it is not working in chrome and ie and firefox.
As you mentioned in the comments, you only want to notify the user that there are unsaved changes when he tries to leave the page. This can be done using onbeforeunload:
window.onbeforeunload = function(){
return 'Please save your changes before navigating to other page, if you continue then your unsaved data will be lost.';
};
Please try this on , it's working on chrome, ie and firfox
<script type="text/javascript">
window.history.forward();
function noBack()
{
window.history.forward();
}
</script>
<body onLoad="noBack();" onpageshow="if (event.persisted) noBack();" onUnload="">
I have an asp.net page with an tag in it. If I enable controls (controls="controls") I can play the audio assigned to the tag. I just want to show my own button to play the audio, so I added a simple html button with a javascript function to hit the .play method:
<button id="LeftAudio" class="Audio" onclick="playAudio1()"></button>
function playAudio1() {
// Check for audio element support.
if (window.HTMLAudioElement) {
try {
//debugger;
var oAudio = document.getElementById('dnn_ctr<%=ModuleId.ToString(CultureInfo.InvariantCulture) %>_ViewUFL_Book_audio1');
oAudio.volume = 1.0;
// Tests the paused attribute and set state.
if (oAudio.paused) {
oAudio.play();
debugger;
}
else {
oAudio.pause();
}
}
catch (e) {
// Fail silently but show in F12 developer tools console
if (window.console && console.error("Error:" + e));
}
}
}
The audio plays fine when I step through the javascript (Chrome/Windows), but will not play at all if I am not debugging. I tried putting the debugger; statement before the play command and stepping through the code, and putting it after the play command - both work. Just doesn't work if I let it run normally.
Any ideas??
I just made it on Fiddle and its working for me.
Here is the test on Fiddle: http://jsfiddle.net/jwCXV/4/
How do I achieve this:-
When user types character like 'abcd' and then '>'(an invalid character for my application), I want to set the text back to 'abcd'. Better if we can cancel the input itself as we do in winforms application. This should happen when user is typing and not on a click of button.
I want this to be applied on all text boxes in my web page. This will be easy if the solution is jQuery based. May be something which will start like this.
$("input[type='text']")
SOLUTION
I used both of the answer provided by #jAndy and #Iacopo (Sorry, couldn't mark as answer to both) as below.
$(document).ready(function() {
//makes sure that user cannot enter < or > sign in text boxes.
$("input:text").keyup(purgeInvalidChars)
.blur(purgeInvalidChars)
.bind('keypress', function(event) {
if (event.which === 62 || event.which === 60)
return (false);
});
function purgeInvalidChars() {
if (this.value != this.value.replace(/[<>]/g, '')) {
this.value = this.value.replace(/[<>]/g, '');
}
}
});
Though one issue still remained i.e. It doesn't allow user to select text in the textbox and this only happens on chrome, work fine on IE (for the first time :D), not tested on firefox. It would be glad if anyone can find solution for that or hope people at Google solves it :D.
UPDATE
I solved it by if (this.value != this.value.replace(/[<>]/g, '')) check. Also updated solution.
Thanks again to all the answerers.
You should catch the 'keyup' and 'blur' events and attach them to a function that bonifies the input: don't forget that the user can paste an invalid sequence of characters.
So for example
$('input[type="text"]').keyup(purgeInvalidChars).blur(purgeInvalidChars)
function purgeInvalidChars()
{
this.value = this.value.replace(/[<>]/g, '');
}
surely you will improve the regexp, maybe replacing all characters except the enabled ones.
Sorry, I can't test my code, so you should take it cum grano salis :-)
Example (keypress):
$(document).ready(function(){
$('input:text').bind('keypress', function(event){
if(event.which === 62 || event.which === 60)
return(false);
});
});
Example (keydown):
$(document).ready(function(){
$('input:text').bind('keydown', function(event){
if(event.which === 226)
return(false);
});
});
Just make use of the preventDefault and stopPropagation functions for events. Those are triggered by returning (false) within an event handler.
In this example, I just check for the keycode of < and > which is thankfully on the same key. If we hit that code, we just prevent the default behavior.
Reference: .preventDefault(), .stopPropagation()
$('#textBox').keyup(function(e){
var myText = $('#textBox').val();
myText = myText.replace(">", "");
myText = myText.replace("<", "");
$('#textBox').val(myText);
});
-- Update --
keyup instead keypress
I have written some code using jQuery to use Ajax to get data from another WebForm, and it works fine. I'm copying the code to another project, but it won't work properly. When a class member is clicked, it will give me the ProductID that I have concatenated onto the input ID, but it never alerts the data from the $.get. The test page (/Products/Ajax/Default.aspx) that I have set up simply returns the text "TESTING...". I installed Web Development Helper in IE, and it shows that the request is getting to the test page and that the status is 200 with my correct return text. However, jQuery refreshes my calling page before it will ever show me the data that I'm asking for. Below are the code snippets from my page. Please let me know if there are other code blocks that you need to see. Thank you!
<script type="text/javascript">
$(document).ready(function() {
$(".addtocart_a").click(function() {
var sProdIDFileID = $(this).attr("id");
var aProdIDFileID = sProdIDFileID.split("_");
var sProdID = aProdIDFileID[5];
// *** This alert shows fine -- ProdID: 7
alert("ProdID: " + sProdID);
$.get("/Products/Ajax/Default.aspx", { test: "yes" }, function(data) {
// *** This alert never gets displayed
alert("Data Loaded: " + data);
}, "text");
});
});
</script>
<input src="/images/add_to_cart.png" name="ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$aAddToCart_7" type="image" id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_aAddToCart_7" class="addtocart_a" />
The easiest way is to tell jQuery not to return anything.
$(".addtocart_a").click(function(e){
// REST OF FUNCTION
return false;
});
Good luck! If you need anything else let me know.