Scan QR Code value into an input field - javascript

This is the scanner I am using...
On Web : https://atandrastoth.co.uk/main/pages/plugins/webcodecamjs/
On Git : https://github.com/andrastoth/WebCodeCamJS
It's working 100%. But I need to add some custom extra's.
When the QR Code is scanned it outputs my result into this paragraph tag.
<p id="scanned-QR"> The scanned code text value is printed out here </p>
However I need it to be an input field so I can use it's value in a url.
How can I set an input field equal to the value submitted to the Paragraph tag?
I have tried these methods and they failed :
Method 1
<input id="scanned-QR"> The scanned code text value is printed out here </input>
Method 2
<p id="scanned-QR" onchange="update"></p>
<input id="code_id_value" type="text" name="" value="">
<br>
<script>
function update(){
var code_id_value = document.getElementById("scanned-QR").innertext;
document.getElementById("code_id_value").value = code_id_value;
}
</script>

The key that you're missing is that the T in .innertext needs to be capitalised (as .innerText).
In addition to this, using inline event handlers is bad practice, and you should consider using .addEventListener() instead of onchange.
This can be seen working in the following:
document.getElementById("scanned-QR").addEventListener("click", update);
function update() {
var code_id_value = document.getElementById("scanned-QR").innerText;
document.getElementById("code_id_value").value = code_id_value;
}
// Demo
update();
<p id="scanned-QR">Text</p>
<input id="code_id_value" type="text" name="" value="">
Hope this helps! :)

So this is the solution I came up with.
Here's my paragraph and input function
<p id="scanned-QR" onchange="update">SCAN.BZ</p>
<input id="code_id_value" type="text" name="" value="">
Here's my function. WITH a interval for every millisecond or faster "I think it's every millisecond".
It runs smoothly and doesn't lag. and the result is practically immediate.
<script type="text/javascript">
setInterval(update,1);
function update() {
var code_id_value = document.getElementById("scanned-QR").innerHTML;
document.getElementById("code_id_value").value = code_id_value;
}
update();
</script>
Thanks for the help "Obsidian Age" Really appreciate it. :)

Related

InnerHTML problems with Tip Calculator function

I'm trying to write a simple Tip Calculator for a computer science class I'm in. It's in HTML/JavaScript. The actual Tip Calculating function is written in JavaScript. I've been told to use innerHTML to display the output of the function in HTML. So from my understanding, innerHTML works by writing any value/variable (in this case the output of my function) to an HTML container with whatever id is defined.
At first I thought maybe it was just my code being in the wrong order. But I've tried moving the function definition around and that wasn't any help. I've verified that the input ID is correct when pulling the variables from HTML. I've done a lot of reading on similar problems and I can't seem to find what I'm doing wrong.
So heres where I define my function, and use innerHTML to write the output. The function is defined before the actual user input.
function calculateTip(){
var checkAmount = document.getElementById("amountBox").value;
var percentTip = document.getElementById("tipBox").value;
var tipTotal = checkAmount * (percentTip / 100);
document.getElementById("tipVar").innerHTML = tipTotal;
}
<body>
<P>
Enter the check amount:
$<input type="numeric" id="amountBox" size=10 value="">
<br>
Tip percentage:
%<input type="numeric" id="tipBox" size=4 value="">
</P>
<input type="button" value="Calculate Tip"
onclick="calculateTip();" >
<hr>
<div id="tipVar"></div>
</body>
So, I'm expecting when you enter the check amount and tip percentage and click the "Calculate Tip" button, it will run the function and innerHTML will write the output of the function to the page in the div container. However when I click the button seemingly nothing happens. If anyone has any help/guidance I'd greatly appreciate it.
You have a typo in the code:
use document.getElementById("tipVar").innerHTML = tipTotal;
Your code was not working because tipVar was undefined, It's an ID and should be used as a string.
I have updated the question snippet and it should work now.
You need to put "tipVar" in quotations inside your function.
Otherwise the value of an undefined variable called tipVar is passed in instead, and it finds no element by that id.
You just forgot the quotes on getElementById("tipBox");
<html>
<body>
<p> Enter the check amount:
<input type="numeric" id="amountBox" size=10 value="">
<br>
Tip percentage:
<input type="numeric" id="tipBox" size=4 value="">
</P>
<input type="button" value="Calculate Tip" onclick="calculateTip();">
<hr>
<div id="tipVar"></div>
<script>
function calculateTip(){
var checkAmount = document.getElementById("amountBox").value;
var percentTip = document.getElementById("tipBox").value;
var tipTotal = checkAmount * (percentTip / 100);
document.getElementById("tipVar").innerHTML = tipTotal;
}
</script>
</body>
</html>

Trying to understand JS functions - what am I doing wrong?

I'm currently working my way through a beginner's JavaScript course on Treehouse and keep getting stuck on functions. In effort to understand better, I tried creating a calculator which converts human years to dog years. Here is my code so far:
HTML:
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
JS:
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); };
The page flickers and I keep seeing the form, no result.
I know this code is incorrect but I don't understand why. I also know I can just copy other people's code from Github and have a functioning calculator but that kind of defeats the purpose of learning. I would rather know why my code doesn't work and what I can do to fix it. (I double, triple checked that the HTML and JS files were properly linked, which they are.)
Any JS wizards out there care to chime in?
Edit: When I enter an age into the form, it merely reloads, rather than displaying the age in dog years (which is the desired outcome).
Your code works, although as you've indicated it's not great.
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); };
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
Some notes for improvement:
Avoid document.write
Forms should have submit buttons (either <input type="submit" value="Calculate"> or <button type="submit">Calculate</button>
The parentheses around your arithmetic are superfluous: var dogYear = humanYears * 7; is sufficient
Not everything needs an id attribute, although that makes DOM queries easy and quick
You should handle the form's submit event as opposed to the button's click event as you'll want to handle if, say, I submit the form by pressing Enter on my keyboard
You don't need the extra function around calculate, document.getElementById('calculate').onclick = calculate; would suffice
With those notes in mind, here's how I'd improve your calculator:
var form = document.getElementById('calculator');
function calculate() {
var years = form['humanYears'].value,
dogYears = years * 7;
document.getElementById('answer').innerText = dogYears;
}
form.addEventListener('submit', calculate, false);
<form id="calculator">
<p>
<label>
What is your current age in human years?<br>
<input type="text" name="humanYears">
</label>
</p>
<p>
<button type="submit">Calculate</button>
</p>
<p>
Answer: <span id="answer"></span>
</p>
</form>
Things I've changed:
I'm using <p> tags to control whitespace instead of <br> which will further let me customize presentation with CSS if I choose to. You cannot style <br> elements.
I'm modifying a portion of the DOM, not the entire DOM
I've bound my event handler with addEventListener which is way less obtrusive
I'm accessing form elements through the natural structure the DOM provides instead of running a full DOM query for each element
I've reduced some code
Here your working code with as little changes as possible:
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears"></label> <br>
<button type="text" id="calculate">Calculate</button>
</form>
</div>
<script>
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = (humanYears * 7);
document.write(dogYears);
}
document.getElementById("calculate").onclick = function(){calculate(); return false; };
</script>
Assuming you put everything in one file the script tags are missing. If not then you still need a script tag to load the JS file.
Your function needed a "return false;". If you omit that, the page will reload after writing your output and won't see the output. That happens because the default behaviour of a button in a form is to reload the page. By returning "false" you suppress that.
The main problem is that document.write doesn't do what you imagine it does:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open, which will clear the document.
See the documentation for document.write: https://developer.mozilla.org/en-US/docs/Web/API/Document/write
A better way to this is to have an empty element on the page, which you then change the contents of:
function calculate() {
var humanYears = document.getElementById("humanYears").value;
var dogYears = humanYears * 7;
document.getElementById('output').innerText = dogYears;
}
document.getElementById("calculate").onclick = calculate;
<div id="calculator">
<form>
<label>What is your current age in human years? <br>
<input type="text" id="humanYears">
</label>
<br>
<button type="button" id="calculate">Calculate</button>
<div id="output"></div>
</form>
</div>
I've also made some small improvements to your script:
Changed the indentation of your HTML to be more readable
Changed your button to have type="button" - otherwise your form will submit and the page will reload when you click the button. In this case, you actually don't even need a form element, but it's not hurting anything. Alternatively, you could add return false to your calculate function - this would tell the browser not to submit the form and thus not reload the page
Changed how you're adding the onclick handler - there's no need to wrap the calculate function in another function. In javascript, functions can actually be passed around like a variable. This is why I set the value of onclick to just be calculate - notice however that I left out the (). You want the onclick to be a reference to the function, otherwise the calculate function would be executed immediately, and the onclick would be set to the return value of the function - in this case, that would be undefined.

Converting text to lowercase/uppercase with a pending a radio button

I am writing a Javascript program that takes a users input text, then (pending a radio button check – lowerCase/UpperCase) converts the input text to either lowercase/upperCase and outputs the value back to the form.
Purely trying to learn on my own Javascript. I am moderately new (but savvy) to JS. Pretty solid on HTML, CSS, Java, but BRAND new with interacting with page elements.
I have dug around for two days to try and solve this. I have even checked out a few books at my local library. (Currently reading the text, Microsoft guide to CSS/HTML, and JS). What other books would you recommend in order to under JS more?
Here is the code below. Although I know one can use CSS in order to convert this and I have done this. I'm purely just wanting to figure out Javascript.
<!DOCTYPE html>
<html>
<head>
<title> Case Changer By: Elliot Granet</title>
<style>
function convert(){
var convertedText = document.test.input.value;
if(document.getElementById("lowerCase").checked = true){
var output = convertedText.toLowerCase();
}else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
convert();
</head>
The rest -
<body>
<h3>Choose your Conversion method below:</h3>
<form action="getElementById">
<fieldset>
<input id="lowerCase" type="radio" name="case" value="lowerCase">Lower Case<br>
<input id ="upperCase" type="radio" name="case" value="upperCase">Upper Case<br><br>
</fieldset>
<fieldset>
<textarea id="inputText" name="input" form="inputText">Enter text here to be Converted...</textarea>
</fieldset><br>
<fieldset>
<textarea id ="outputText" name="output" form="outputText">Converted text will appear here...</textarea>
</fieldset>
<input type="button" value="Convert">
</form>
</body>
</html>
You need to make few changes to make this function work.
style is an invalid tag to put js code. You need to put it inside <script> tag
If you are writing this function inside header yo may come across error since before DOM is ready it will try to get value of textarea with id inputText.
document.getElementById(idName').value but not is right syntax to get the value of element using id
Attaching convert() with the button. So when you will click on button the function will execute.
5.document.getElementById("lowerCase").checked = true this is wrong.It mean that checkbox will get checked as = will assign the value . Instead you need to compare the value. So use == or ===
if you declare var output inside if loop it wont be available inside else. So you need to declare it outside the if-else loop
Hope this snippet will be useful
HTML
<input type="button" value="Convert" onclick="convert()">
JS
window.load =convert; // convert function will be called after window is ready
function convert(){
var output; //variable declaration outside if-else loop
var convertedText = document.getElementById('inputText').value; //document.getElementById
if(document.getElementById("lowerCase").checked == true){ // == comparision
output = convertedText.toLowerCase();
}
else {
output = convertedText.toUpperCase();
}
document.getElementById('outputText').value = output;
}
EXAMPLE

JavaScript Inputs

For my college coursework I have been asked to create a program the works out the cost for painting a room by taking the measurements and multiplying them all together. I've done all of the Pseudo and Flow Charts and stuff. But I'm stuck with this bit. I want the user to input a number into the text field(If there is a way to limit the to just number please let me know :P) and then once the user presses a button it will write the value below without having to change/refresh the webpage. The code below should work(I think) But anyways, any help is greatly appreciated :)
Aaron~
<form id="frm1" action="form_action.asp">
Number of walls: <input type="number" name="numberOfWallsInput" value="From 4 to 10"><br>
Width of walls in meters: <input type="text" name="wallWidthInput" value="From 1 to 25"><br>
Height of walls in meters: <input type="text" name="wallHeightInput" value="From 2.4 to 6"><br>
</form>
<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x = document.getElementById("numberOfWallsInput");
document.getElementById("demo").innerHTML=x;
}
</script>
First off, you have no element with an ID of "numberOfWallsInput"; your input element has a name of numberOfWallsInput instead. Either add this as an ID, or use getElementsByName() instead.
Then you need to pull the value, not just the element:
var x = document.getElementsByName("numberOfWallsInput")[0];
document.getElementById("demo").innerHTML = x.value;
JSFiddle demo.
You have to provide id attribute to your inputs in order for them to be retrieved by document.getElementById.
Otherwise in your case use document.forms[0].numberOfWallsInput.value.
Better is naming your form :
<form name="form1">
<input name="myinput"/>
</form>
Then javascript:
var value = document.forms.form1.myinput.value;
JSFiddle :
http://jsfiddle.net/ug5hh/

Simple HTML input onkeypress event not working

I'm new here (and to web development in general), and I have been trying to understand why my function is not being executed on the specified event.
I found this post, and it seems exactly like what I want, but even this did not work:
html <input type="text" /> onchange event not working
Any help would be appreciated. My exact code follows. I have some text input fields (actually search boxes), and ultimately I want to have it check a checkbox when the user enters data into the text fields, but it doesn't even seem to call the function.
I have tried a few variants while reading the post mentioned above. Here are some input field attributes I have tried:
<input type="date" name="dt" size="10" value="2012-07-21" onChange="SetCheckBox('d')" />
<input type="search" size="10" name="sl" value="" onChange="SetCheckBox('n')" />
<input type="search" size="10" name="sf" value="" onkeypress="SetCheckBox('n')" />
<input type="search" size="20" name="st" value="" onkeypress="SetCheckBox(this);" />
and here is my javascript:
<script language="javascript" type="text/javascript">
Function SetCheckBox(id) {
alert (id.value);
document.write('test');
}
</script>
I have tried not passing any arguments and just doing a document.write, but it doesn't seem to be calling the function. And yes, javascript is enabled and working elsewhere on the page just fine!
The script is in the body, just below the form.
The (lack of) behavior is the same in multiple browsers.
Thank you for any help you can provide.
Ray
For javascript the function keyword is lowercase.
Function SetCheckBox(id)
needs to be:
function SetCheckBox(id)
Also, you're not passing object to get an id, so...
function SetCheckBox(id) {
var ele = document.getElemenyById(id);
alert (ele.value);
document.write('test');
}
Several issues apart from the already mentioned uppercase F in Function
your function passes a variable called id but expects a field
you pass a string that is not an ID and not referring to a field
only the last version using (this) will work, but there is no value to alert
document.write will WIPE the page and all scripts on it when it is invoked after page load (e.g. not inline)
So code should be EITHER
function SetCheckBox(id) {
var val = document.getElementById(id).value
alert (val);
document.getElementById('someContainer').innerHTML=val;
}
OR
function SetCheckBox(fld) {
var val = fld.value
alert (val);
document.getElementById('someContainer').innerHTML=val;
}
Based on your description, my guess is you want to do this: DEMO
<input type="date" id="dt" name="dt" size="10" value="2012-07-21"
onkeypress="SetCheckBox(this)" />
<input type="checkbox" id="dtChk" />
using this script
function SetCheckBox(fld) {
var checkbox = document.getElementById(fld.id+"Chk");
// check if something is entered, uncheck if not
checkbox.checked=fld.value.length>0;
}
and maybe even with this addition
window.onload=function() {
document.getElementById("dt").onkeypress();
}
which will check the box if the field is not empty at (re)load time
in javascript function keyword is written in small letters and here you wrote F in caps.
onkeypress and onchange event should works
<body>
<script type="text/javascript">
function SetCheckBox() {
alert("1");
}
</script>
<input id = "test" value="" onkeypress="SetCheckBox();" />
<input id = "test1" value="" onchange="SetCheckBox()" />
</body>

Categories

Resources