Autofocus on input and accept letters, digits and scanned barcodes - javascript

I have to accept either input from keyboard or 2d barcode scanner.
The input is mixture of alpha numeric, also I want user to be able to use Ctrl+v to paste their input. Currently if I try Ctrl+v, only v key is detected and shown.
Also my cursor autofocus does not work, no matter what I try.
See below the javascript.
<script>
var codes = "";
var codes_el = document.getElementById('codes');
var output_el = document.getElementById('output');
function process_key(event) {
var letter = event.key;
if (letter === 'Enter') {
event.preventDefault();
letter = "\n";
event.target.value = "";
}
// match numbers and letters for barcode
// if (letter.match(/^[a-z0-9]$/gi)){
if (letter.match(/^[a-z0-9\n-]$/gi)) {
codes += letter;
}
codes_el.value = codes;
output_el.innerHTML = codes;
}
</script>
<script>
function testAttribute(element, attribute) {
var test = document.createElement(element);
if (attribute in test) {
return true;
} else
return false;
}
window.onload = function() {
if (!testAttribute('input', 'autofocus'))
document.getElementById('codes').focus();
//for browser has no autofocus support, set focus to Text2.
}
</script>
and here is the html part.
Formatted HTML:
<div class="barcode_box">
<br>
<form method="POST" action="scanned.php">
<input onkeydown="process_key(event)" />
<input type="submit" value="Submit" />
<input type="hidden" name="codes" id="codes" autofocus/>
</form>
<pre id="output">
</pre>
<br>
</div>

Related

Mask the first 2 characters in input form

Hello i trying to hide/change (with *) the 1-st and 2-nt characters in input form, but value do not changed.
E.x if in my input form i put sarahlovecode in input form show **rahlovecode, but when submit get the full value sarahlovecode
HTML:
<input type="text" class="input" name="secret_word" id="secret_word">
And Js i using is:
$.fn.mask = function( regexp, matchGroup, callback ) {
this.on("blur", function(e){
$(this).data("value", this.value);
var result;
while (result = regexp.exec(this.value)) {
var matches = result.slice(1);
if (callback){
var substitute = callback(matches[0]);
} else {
var substitute = Array(matches[matchGroup-1].length + 1).join("*");
}
matches[matchGroup-1] = substitute;
this.value = matches.join("");
}
})
this.on("focus", function(e){
this.value = $(this).data("value") || "";
});
}
// With Regular expression
phoneRegexp = new RegExp("(.*?)(.{1})$", "g");
$("#secret_word").mask(phoneRegexp, 2);
ref: https://www.sitepoint.com/community/t/mask-input-fields-without-affecting-validation/37100/15
And it's working but change the value with **, same as input word.
Suggestion to fix this?
Thanks.
You need to change the value of the input back when you submit the form. Add a function on the event "onsubmit" of the form:
<form onsubmit="fix_asterisk();">
<fieldset>
<input type="text" class="input" name="secret_word" id="secret_word">
</fieldset>
<input type="submit">
</form>
Then in the javascript add the function:
<script>
function fix_asterisk(){
let input = document.getElementById("secret_word");
input.value = $(input).data("value");
}
</script>

HTML/JS Text recognition variable displayer

I cannot get the <div id="output"> section to display the variable txtOutput or maybe the variable txtOutput is not being defined or changed.
I would appreciate help on re-defining this variable or how to display it. (the empty text box feature works though)
function smartinput() {
var txtInput = document.forms["form"]["inputA"].value;
var txtOutput;
var input = txtInput.value;
if (txtInput == null || txtInput == "") {
alert("Please put text in Input");
return false;
} else if (txtInput == "Hi") {
return output.value = "Hello";
}
document.getElementByID("Output").innerHTML = txtOutput;
}
<p><strong>Note:</strong> The output element is not supported in Edge 12 or Internet Explorer and earlier versions.</p>
<h1> Smart Responder Test 1 </h1>
<form name="form">
<fieldset>
<label> Input: </label>
<textarea cols="30" rows="2" name="inputA" id="txtInput"></textarea>
<p></p>
<input type="button" value="Submit" onclick="smartinput()" />
<p></p>
<label>Output: </label>
<div id="Output"></div>
</fieldset>
</form>
Firstly, you made a typo for method getElementById, correct that.
Secondly, you are defining variable txtOutput but not using it later, rather you use output. Just change output to txtOutput:
function smartinput() {
var txtInput = document.forms["form"]["inputA"].value;
var txtOutput;
var input = txtInput.value;
if (txtInput == null || txtInput == "") {
alert("Please put text in Input");
return false;
} else if (txtInput == "Hi") {
txtOutput= "Hello";
}
document.getElementById("Output").innerHTML = txtOutput;
}
And you don't need txtOutput.value because it is only a variable for result.
Some errors
you should put getElementById in place to ...byID
If it is empty or null, just put it like this !(elem or value)
The output element is not a text area so value will not work. Change it to innerHTML or innerText
TxtInput and input are the same in your code
function smartinput() {
var txtInput = document.forms["form"]["inputA"];
var input = txtInput.value;
var output = document.getElementById("Output");
if (!input) {
alert("Please put text in Input");
return false;
} else if (input == "Hi") {
return output.innerHTML = "Hello";
}
}
<p><strong>Note:</strong> The output element is not supported in Edge 12 or Internet Explorer and earlier versions.</p><h1> Smart Responder Test 1 </h1><form name="form"><fieldset><label> Input: </label><textarea cols="30" rows="2" name="inputA" id="txtInput"></textarea><p></p><input type="button" value="Submit" onclick="smartinput()" /><p></p><label>Output: </label><div id="Output"></div></fieldset></form>

"NaN" result when multiplying more than one value in an array by a number

Note: please pay no attention to my beginnings on the "Decrypt" function, button, etc. It has no relevance towards this question.
I've looked practically everywhere for a fix on here and can't seem to find one due to my kinda strange project. I'm a noob at JavaScript so please tell me anything I could improve on. Here's my project: It's basically a Encrypt/Decrypt message thing based on what key you type in.. When you type in the key, and submit it, it gives the key a value based on it's length and ASCII value:
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
So now you've entered a key and it has a value that plays a role in encrypting/decrypting your messages. Here's the text boxes that you enter in and stuff.
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
By the way, the keycheck() function is just something where if you type in the textbox and don't have anything entered as a key, it will alert you to create a key.
So whenever you type into the input textbox, it runs getascii(this.form), which, btw, just gets the ASCII values of all of the characters you typed and stores them as a variable, in which this case, is "code":
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
Which, in turn, runs encrypt(), which places the "code" values into an array(i think, this may be the issue. please tell me.):
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
Which, then again, runs a function called arrmult, which is where the trouble begins (i think).
function arrmult() {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
The above code I got from this website. What it does is takes each individual value of the array assigned as the variable A, in this case all of the ASCII values of whatever you typed in the box, and multiplies them by a certain value, which I have set as the value of the key. Note: When I replace the variable A with a string of numbers, like this:
var a = [127,93,28];
It seems to be working perfectly fine. But, when I use asciiarray instead, it returns back with a value of "NaN", but only when I do more than ONE character. When I only type one character and have the variable a set as this:
var a = [asciiarray];
It works perfectly fine. But when it updates, and has two or more characters, it results as "NaN" even though the value of asciiarray is the exact same as the numbers above. And when you do reply, please help me realize where to replace what I've done wrong, as I'm a JavaScript complete noob.
If you wish to look at the code completely, here it is. You can even copy and paste it into an HTML file if you wish:
<html>
<body>
<head>
<title>Ascii Encryption</title>
</head>
<script>
var code="test"
var sepcode="test"
var keyinp="test"
var keyasciiout="test"
var finalkey="test"
var globalinp="test"
var globalascarr="test"
var multex="test"
var keyasciitwo="test"
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
</script>
<script>
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
</script>
<script>
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
</script>
<script>
function arrmult(none) {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
</script>
<script>
function dec(form) {
var input = (form.input.value)
var inputdiv = (input / finalkey)
var decrypted = String.fromCharCode(inputdiv)
alert(decrypted)
}
</script>
<script>
function keycheck(form) {
if (finalkey != null) {
null
} else {
alert("Please enter a key. This will determine how your encryptions and decryptions are made.")
}
}
</script>
<center>
<br> <br>
<br> <br>
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
</center>
</body>
</html>

Detect text filled by barcode scanner(reader) javascript

The code checks barcodes using a barcode scanner.
Search_code is filled by a user (keyboard) , and insert_code is filled automatically by a barcode scanner.
Currently, code works if both inputs are introduced in barcode scanner values ​​which is not functional for me.
The code needs to run when:
search_code is entered manually ( keyboard ) and
insert_code is filled automatically by the barcode scanner
var search_code = document.getElementById('search_code');
var insert_code = document.getElementById('insert_code');
var result = document.getElementById('result');
var button = document.getElementById('button');
var audio = new Audio('sound.wav');
// respond to button click
button.onclick = function validate(e) {
e.preventDefault();
// show verification result:
if (search_code.value == insert_code.value) {
result.textContent = 'code ok';
result.className = "ok";
audio.play();
} else {
result.textContent = 'code is not ok';
result.className = "not-ok";
}
// clear input when wrong:
if (search_code.value !== insert_code.value) {
insert_code.value = '';
}
return false;
};
function clearField(input) {
input.value = "";
};
....
<form>
<input type="text" name="search_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='introdu codul'" id="search_code" placeholder="introdu codul" autocomplete="off" value=""/><br/>
<input type="" name="insert_code" onfocus="clearField(this, this.placeholder='');" onblur="this.placeholder='scaneaza codul'" id="insert_code" placeholder="scaneaza codul" autocomplete="off" value=""/><br/><br/>
<input type="submit" id="button" name="button" value="verifica COD" />
</form>
</div>
<div id="result"></div>
</div>
<script src="js/action_input.js"></script>
</body>
</html>
Thank you!
To prevent a textbox from being filled by a bar-code reader simply disable onpaste event .
$(document).ready(function(){
$('#search_code').bind("cut copy paste",function(e) {
e.preventDefault();
});
});

How to make a word a link if the user has input # before it?

I am using this code:
<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>
I want i such a way that if the user inputs a word and he has place # before the word without space then how to make the word as a link. Means the tag which happens in facebook. Can it be done with java script and how.
This was just the example to demonstrate i want to intergrate this type in my project as comments. And it will be with php.
Thanks
Here's one example to check. It works with enter keypress and even prevents for adding same tags over again: http://codepen.io/zvona/pen/KpaaMN
<input class='input' type="text" />
<output class='output'></output>
and:
'use strict';
var input = document.querySelector('.input');
var output = document.querySelector('.output');
input.addEventListener('keyup', function(evt) {
if (evt.keyCode !== 13 || !input.value.length || ~output.textContent.indexOf(input.value)) {
return;
}
var tag = document.createElement('a');
tag.appendChild(document.createTextNode(input.value));
if (input.value.startsWith("#")) {
tag.setAttribute("href", input.value);
}
output.appendChild(tag);
input.value = "";
}, false);
<form>Account Info <br>
<input type="text" id="a">First Name<br/>
<output id="result" name="x" for="a"></output>
<button type="button" onclick="changeVal(document.getElementById('a').value)">Click</button>
</form>
<script>
function changeVal(value1){
var dt = value1.split(" ");
document.getElementById("result").innerHTML = "";
for(var t=0; t < dt.length; t++){
if(dt[t].startsWith("#")){
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" <a href='#'>"+dt[t]+"</a>";
}
else{
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" "+dt[t];
}
}
}
</script>
Checkout Jsfiddle demo
https://jsfiddle.net/tum32675/1/
You could use a textarea to input and a render to show the output. Then hiding the input and showing the output only. But that's another
story.
If you use a contentEditable div, you can actually insert and render the html from it in the same component. Check it out!
$(document).on("keyup","#render", function(){
var words = $(this).text().split(" ");
console.log(words);
if (words){
var newText = words.map(function(word){
if (word.indexOf("#") == 0) {
//Starts with #
//Make a link
return $("<div/>").append($("<a/>").attr("href", "#").text(word)).html();
}
return word;
});
}
$(this).empty().append(newText.join(" "));
placeCaretAtEnd( $(this)[0]);
});
Here is the Plunker
Thanks for the attention.

Categories

Resources