javascript passing input without entering input fields/forms - javascript

Yesterday i wrote a question here but the way i did that request was kinda confusing.
Now I'll try it different.
I have a barcode handscanner which just scans the barcode and writes the input into an input field.
It's just the same as a guy who typs 10 digits and presses return in less then 5ms.
example : 2134463342 + return
Now i have a form which was set to autofocus on reload and i can get the input from the scanner.
I want to be able to do scans and passing them into a database without entering the input field.
example: User does something else like browsing the webpage than the user scans something without entering the input field.
I have copied some code from a site:
var chars = [];
$(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
console.log(e.which + ":" + chars.join("|"));
if (pressed == false) {
setTimeout(function(){
if (chars.length >= 10) {
var barcode = chars.join("");
console.log("Barcode Scanned: " + barcode);
// assign value to some input (or do whatever you want)
$("#barcode").val(barcode);
}
chars = [];
pressed = false;
},500);
}
pressed = true;
});
});
$("#barcode").keypress(function(e){
if ( e.which === 13 ) {
console.log("Prevent form submit.");
e.preventDefault();
}
});
The code works fine, my Question is:
Is it possible to do that operation without entering the input field/form?
thanks

#alexMmM
did you tried CSS to hide the inputbox??? style= display:none or style= visibility:hidden property ???
It hides your input box and gives a virtual feel that it has been done without entering into input fields...

Related

perform javascript event when url entered in the textbox

I have a showPreview option for an entered URL on my site just like Facebook shows a preview of the URL.
When the User enters the url, the following condition gets verified:
$('#text').keyup(function(e) {
allowPosting = true;
if ((e.which === 13 || e.which === 32 || e.which === 17) && trim($(this).val()) !== "")
}
Key code:
13 - Enter
45 - Insert
17 - control
Now the function is being called when the user copy and pastes the URL or Selects the URL from the preview and presses Enter key
What I want:
The preview should be shown if the user types in the URL, even if the user does not press the enter key or copy and pastes the URL.
What should I do?
Here is your code, this will do everything you wrote:
$('#text').keyup(function(e) {
allowPosting = true;
if (/(^|\s)((http:\/\/|https:\/\/)[a-zA-Z0-9!*'();:#&=+$,\/?#[\]\-_.~]+)/.test($("#text").val()) && trim($(this).val()) !== "")
{
// DO STUFF
}
});
It will also check if the input is a link or not, so that the user can enter "http://google.com/" and not e.g. "asdf"!
check the .val() after every keyup, not only on Enter, and if it is an URL, do the rest
Try change in place of keyup :
$('#text').change(function(){...});

How to detect new empty line in textarea with Javascript?

I would like to detect a new empty line in a text area and if the user just pressed enter in the text area, without entering any data to return false and echo a message. I have made some research and thought of something like this:
var validatef ....
var code = (e.keyCode ? e.keyCode : e.which);
if (validatef == 'a value here' || code == 13) {
somevarhere.textcontent = 'Message';
return false;
}
else {....}
But it doesn't seem to work.
You can detect an empty line in a textarea by checking for the values:
\r\n (works fine for me) or \n
Just replace the text a value here with \r\n or \n what best suits you.
EDIT:
Check How to count string occurrence in string? to count regex appearances. So you can make a for loop to show the error message on /\s/g.
Hope it helps.
Try this
$('textarea').on('keypress', function(e) {
var val = $('textarea').val();
if (e.which == 13) {
if(! /\S/.test(val)) {
alert("no data");
}
}
});
this alerts no data for each keypress.
This is in jQuery but it will be similar even in plain Javascript
Here is the demo http://jsfiddle.net/TUCx8/
just test if the user pressed enter twice
/\n\n/.test(this.value)
According to the first sentence of the question, this may be one of possible solutions:
var enters = 0;
$('textarea').keypress(function(event) {
if (event.which == 13)
enters++;
else
enters = 0;
if (enters > 1) {
alert('You hit 2 new lines!');
}
});
Live example http://jsfiddle.net/fp6xk/
Another one solution is to check an empty line right before the end of text:
(function(){
$('textarea').keyup(function(event) {
if (/(\r?\n){2}$/.test($(this).val())) {
alert('2 consecutive empty lines at the end!');
}
});
})();
It would work independent of consecutive enter presses.
http://jsfiddle.net/fp6xk/4/

How to prevent user from entering decimals?

I've got an order page on my site. Some order items can have decimal quantities, some can't.
What's the best way to prevent the user from entering decimal quantities? (Apart from an alert box and setting the field to zero)?
Intercept key events for the field, detect illegal characters upon input, keep them from getting entered in the field and add a temporary msg near the field (inserted into the page) that explains what characters or values are allowed. pop up alerts are a bad way to give feedback in the middle of typing.
Then, validate again before submission because there are other ways to get data into fields (drag/drop, copy/paste, etc...) that you might not have caught everything.
Here's a jQuery example of both an integer only and a decimal only field with temporary messages displayed when invalid keys are typed:
Working jsFiddle: http://jsfiddle.net/jfriend00/CkDTy/
$(".integer").keypress(function(e) {
if (e.which < 48 || e.which > 57) {
showAdvice(this, "Integer values only");
return(false);
}
});
$(".decimal").keypress(function(e) {
// 46 is a period
if (e.which != 46 && (e.which < 48 || e.which > 57)) {
showAdvice(this, "Decimal numbers only");
return(false);
}
if (e.which == 46 && this.value.indexOf(".") != -1) {
showAdvice(this, "Only one period allowed in decimal numbers");
return(false); // only one decimal allowed
}
});
function showAdvice(obj, msg) {
$("#singleAdvice").stop(true, false).remove();
$('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
$("#singleAdvice").delay(4000).fadeOut(1500);
}
Here's a little jQuery that prevents non-numerical inputs:
$(function() {
$('input').bind('keyup', function(event) {
var currValue = $(this).val();
if(currValue.search(/[^0-9]/) != -1)
{
// Change this to something less obnoxious
alert('Only numerical inputs please');
}
$(this).val(currValue.replace(/[^0-9]/, ''));
});
});
You can add an event (on key press) and detect if a decimal point has been pressed by the user or not. Also on form submission, use regular expressions to check if the submitted data is correct (because the user can forge the data using live editor like firebug). Also make sure to double check that on your server side in case if user disabled javascript.
for example:
<input type="text" onkeypress="checkDecimal();" />
<input type="submit" onclick="checkBeforeSubmit();" />
function checkDecimal() {
// your code goes here
}
function checkBeforeSubmit() {
// your code goes here
}
You better to use the same function cause it's basically the same thing and invoke it from both events.
On server side, check the submitted data again

Custom keyboard / replace keys

I want to change behavior of my keyboard so when user on an input box press key a a = 97 it changes to b 97+1.
I want it for cross browser
jQuery.keypress will get you the event when the users types something, and String.fromCharCode gets you the character + 1. The tricky part is dealing with the selection.
To get the selection, I used the jQuery field selection plugin, and to make sure it doesn't keep jumping back to the end I used this answer to another question. Here is the final code:
$(function() {
$("#target").keypress(function (evt) {
if (evt.which >= 65 && evt.which <= 122) {
var sel = $(this).getSelection();
var val = $(this).val();
var out = val.substring(0, sel.start) + String.fromCharCode(evt.which+1) + val.substring(sel.end, val.length);
$(this).val(out);
$(this).selectRange(sel.start + 1, sel.start + 1);
return false;
}
});
});
jsFiddle
I restricted it to a-zA-Z but you can customize that however you want.
I tested the following in Firefox and Chrome. Using "keypress" allows the use of other keys, and using charCode allows using lower and uppercase letters:
document.getElementById("textbox").addEventListener("keypress",function(event){
event.preventDefault();
this.value+=(String.fromCharCode(event.charCode+1))
},false);
I just now saw the jQuery tag, so you could also do:
$("#textbox").bind("keypress",function(event){
event.preventDefault();
this.value+=(String.fromCharCode(event.charCode+1));
});

Create an autocompleter like the Facebook status update

I'm trying to create a div with contenteditable like the Facebook status update. Then I mean I want to show an autocomplete box when the user have written #.
How would you do that. Currently I'm just playing with keypress and check if the keycode = 64. Somehow that works, but it doesn't validate if there's a space before the alfa, or if the user has unfocused the box, then focused it again.
Any ideas? Or do you know about any plugin that works something like that?
Tnx
I'd probably do it with keypress too.
but we need to check the cursor position to check the character before the '#'.
here's the function I used from http://javascript.nwbox.com/cursor_position/cursor.js
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate();
r.moveEnd('character', o.value.length);
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text);
} else {
return o.selectionStart;
}
}
then with jquery I wrote this keypress callback function:
txt.keypress(function(event) {
if (event.which == 64) {
var index = getSelectionStart(this)
var prevChar = txt.val().substring(index - 1, index);
// now you can check if the previous char was a space
}
});

Categories

Resources