JavaScript Inputs - javascript

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/

Related

Use text box value multiple times to update text on web page

I need to display boilerplate text on a web page and give visitors the ability to update the text by submitting a value in a text box. I have two issues:
I can only use the text box value once but I want to use it multiple. I understand this is due to using document.getElementById. I should be using document.getElementByClassName however I am having troubles making this work.
I would like to include a default value within the boilerplate text that would then be replaced by the value from the text box. For example "your company" would be replaced with "XYZ Company" (or whatever the user submits in the text box).
I have the following code:
<!DOCTYPE html>
<html>
<body style="text-align:center;">
Company Name:
<input type="text"
id="myText"
value="">
<button type="button"
onclick="myFunction()">
Submit
</button>
<p>I would like to use the name, <strong><span id="demo"></span></strong>, multiple times in this text. I'd like to use it <strong><span id="demo"></span></strong> and again <strong><span id="demo"></span></strong>.</p>
<script>
// Here the value is stored in new variable x
function myFunction() {
var x =
document.getElementById("myText").value;
document.getElementById(
"demo").innerHTML = x;
}
</script>
</body>
</html>
What am I missing? Any direction is appreciated. Thanks in advance.
First of all, you should be using the classes, since ids are meant to be unique. Second, when calling getElementById() (or even querySelector()), you are only getting the first element that matches the query. You should give all of the the elements a shared class, select them all with querySelectorAll(), then loop over them all, as in the following:
<!DOCTYPE html>
<html>
<body style="text-align:center;">
Company Name:
<input type="text"
id="myText"
value="">
<button type="button"
onclick="myFunction()">
Submit
</button>
<p>I would like to use the name, <strong><span class="demo"></span></strong>, multiple times in this text. I'd like to use it <strong><span class="demo"></span></strong> and again <strong><span class="demo"></span></strong>.</p>
<script>
// Here the value is stored in new variable x
function myFunction() {
var x =
document.getElementById("myText").value;
// select all elements with class ('.') of 'demo'
const allDemoElements = document.querySelectorAll(".demo");
// loop over each element, and alter innerHTML
allDemoElements.forEach(el => {
el.innerHTML = x;
});
}
</script>
</body>
</html>

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>

Scan QR Code value into an input field

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. :)

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.

Create unique name for <input> in form

Okay, first thing, I had a lot of trouble thinking of a title for this, and also of what to search for in Google. So that may just be me being stupid, but here is what I would like you help with.
I have a form, that has a button that will add additional input fields, but I would like the the name of the field to iterate everytime the button is pressed. E.g. the first time it will be:
<input type="textfield" name="field1" value=""/>
Then the second time it is pressed, it will be:
<input type="textfield" name="field2" value=""/>
I also have a small example of what I currently have here: http://jsfiddle.net/5gh75/14/
Please let me know if you can help me, or if you require more info thanks :)
The best way to handle this is to name them all field[].
When handled by the server-side code, it will build an array for you. For instance, in PHP you would get $_POST['field'][0], $_POST['field'][1] and so on.
For your example:
JQuery
var i=0;
$('span.add').click(function () {
$('<input>').attr({
type: 'textfield',
name: 'program'+i
}).appendTo('#addsoftware');
i++;
});
JSFiddle.
But #Kolink-s answer is much better.
Edit: I just saw the previous posts after sending this. Using an array would definitely be better, and JQuery is always nice :).
Just use some javascript:
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
idx = 0;
function add() {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "textfield");
element.setAttribute("name", "field" . idx);
element.setAttribute("value", "");
idx++;
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
Select the element and hit Add to add it in form.
<BR/>
<INPUT type="button" value="Add" onclick="add()"/>
<span id="fooBar"> </span>
</FORM>
</BODY>
</HTML>
I took this example from: Add more text fields dynamically in new line (html)

Categories

Resources