Javascript: Cant fetch value of input number box - javascript

Hello almighty internetz!
Im totally new on javascript, and i cant get the script to fetch numbers from input boxes, plus the sums together and write it out.
Have been sitting on Google for an hour now, so im asking you guys/girls for help!
http://jsfiddle.net/heWM2/5/
<form action="" id="brod">
<p>Pris per kartong
<input name="Prisperkartong" type="number" id="priskart" name="pris">
</p>
<p>Antal kartonger i leverans
<input name="Kartongilev" type="number" id="kartilev">
</p>
<input type="button" onClick="calculateTotal()" value="Räkna">
<div id="print"></div>
</form>
And the Javascript:
function getPrisperkartong() {
var Prisperkartong = parseInt(document.brod.priskart.value, 10);
if (isNaN(Prisperkartong)) return;
document.bord.priskart.value = Prisperkartong;
}
function getKartongilev() {
var Kartongilev = parseInt(document.brod.kartilev.value, 10);
if (isNaN(Kartongilev)) return;
document.bord.kartilev.value = Kartongilev;
}
function calculateTotal() {
var total = getPrisperkartong() + getKartongilev();
var divobj = document.getElementById('print');
divobj.style.display = 'block';
divobj.innerHTML = "Pris $" + total;
}

If you are accessing the input boxes through the form, you need to use the name field to identify the form as well as the input boxes. Your get functions should also return the value, not assign it back to the original input box. See this updated fiddle for a fixed, working example.
http://jsfiddle.net/heWM2/6/

Related

Trying to take input from HTML and do computation with it in Javascript

I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?
<div class = "text">How much energy do you use?</div>
<input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<!-- Multiply InputValue by 3 and Add 2 —->
I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.
try this, first query input value then calculate your desire numbers then alert the user,
like this <!-- Multiply InputValue by 3 and Add 2 —->
function getInputValue() {
const inputVal = document.getElementById("q1").value; //query input value
const calculatedValue = ((inputVal *3) +2); // first multiply input value with 3
// then add 2
alert(calculatedValue); // show the calculated value through an alert
};
It's not that hard. try to play with the below code. Cheers!!
<html>
<body>
<label for="insertValue">Enter Your Value:</label>
<input type="text" id="insertValue">
<button onclick="Multiply()">Multiply</button> <!-- Calling to the JS function on button click -->
<p id="answer"></p>
<!-- Always link or write your js Scripts before closing the <body> tag -->
<script>
function Multiply() {
let value = document.getElementById("insertValue").value; //get the inserted Value from <input> text box
let answer = 0;
//Your Multiplication
answer = value * 2 * 3;
//Display answer in the <p> tag and it id ="answer"
document.getElementById("answer").innerText = "Your Answer is: "+ answer;
}
</script>
</body>
</html>
Easy (to understand) Solution:
<div class="text">How much energy do you use?</div>
<input id="q1" type="text" placeholder="# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<br>
<output id="a1"></output>
<script>
var input = document.getElementById("q1");
var output = document.getElementById("a1");
function getInputValue() {
output.textContent = (input.value * 3) + 2;
}
</script>

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

Dynamically adding HTML form fields based on a number specified by the user [duplicate]

This question already has answers here:
Dynamically creating a specific number of input form elements
(2 answers)
Closed 1 year ago.
I've a form field named Number of messages, and based on what number the user specifies, I want the exact number of text fields to be dynamically generated below to allow users to enter specified number of messages.
I have browsed through some examples where JQuery is used to generate dynamic form fields, but since I'm not acquainted with JQuery, those examples are a bit too complex for me to grasp. I do know the basics of JavaScript, and would really appreciate if I could find a solution to my query using JavaScript.
function addinputFields(){
var number = document.getElementById("member").value;
for (i=0;i<number;i++){
var input = document.createElement("input");
input.type = "text";
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
and html code will be
Number of members:<input type="text" id="member" name="member" value=""><br />
<button id="btn" onclick="addinputFields()">Button</button>
<div id="container"/>
fiddle here
You can try something similar to this...
var wrapper_div = document.getElementById('input_set');
var btn = document.getElementById('btn');
btn.addEventListener('click', function() {
var n = document.getElementById("no_of_fields").value;
var fieldset = document.createElement('div'),
newInput;
for (var k = 0; k < n; k++) {
newInput = document.createElement('input');
newInput.value = '';
newInput.type = 'text';
newInput.placeholder = "Textfield no. " + k;
fieldset.appendChild(newInput);
fieldset.appendChild(document.createElement('br'));
}
wrapper_div.insertBefore(fieldset, this);
}, false);
No. of textfields :
<input id="no_of_fields" type="text" />
<div id="input_set">
<p>
<label for="my_input"></label>
</p>
<button id="btn" href="#">Add</button>
</div>
It is a simple task which is made simpler with jQuery. You need to first get the value from the input field for which you can use .val() or .value. Once you get the value, check if it is an integer. Now, simply use .append() function to dynamically add the elements.
HTML
<form id="myForm">
Number of Messages: <input id="msgs" type="text"> </input>
<div id="addmsg">
</div>
</form>
JAVASCRIPT
$("#msgs").on('change', function()
{
var num = this.value;
if(Math.floor(num) == num && $.isNumeric(num))
{
$("#addmsg").text('');
for(var i = 0; i < num; i++)
{
$("#addmsg").append("<input type='text'/><br/>");
}
}
});
Fiddle
Note, everytime the value in the input changes, I am first clearing the div by:
$("#addmsg").text('');
And then I loop and keep adding the input field. I hope this helps!

3 text box Math in Javascript

Hi I am NewBee in Javascript. This is my second week.
Below is the code that has a form with three input fields.
The relationship of the fields is:
the second field is twice the value of the first field
the third field is the square of the first field
I have managed to do the above but i am not able to do the below :
If a user enters a value in the second or third field, the script should calculate the appropriate value in the other fields. Currently the code works well ONLY if I enter the value in the first field.
I hope I explained well in other words : how do I enter say 144 in the last textbox and the other 2 textboxes show 12 and 24 respectively. Or If I enter 24 first and first and the third text boxes show 12 and 144.
Thanks
Vipul
<html>
<head>
<script>
window.onload = init;
function init() {
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
function doMath(){
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMath()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= doMath()>
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= doMath()> <br><br>
</form>
</body>
</html>
take a look at the code below:
<html>
<head>
<script>
window.onload = init;
var init = function(){
var button = document.getElementById("usrButton");
button.onclick = save;
onkeyup = doMath;
}
var doMathbase = function(){
console.log('here');
var base = document.getElementById("base").value;
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value = (base*2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
var doMathBase2Time = function(){
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo").value;
var base = document.getElementById("base").value = (baseNumber_timesTwo/2);
var baseNumber_square = document.getElementById("baseNumber_square").value = (base*base) ;
}
</script>
</head>
<body>
<form>
<input type="text" name="base" id="base" onkeyup= "doMathbase()">
<br><br>
<input type="text" name="baseNumber_timesTwo" id="baseNumber_timesTwo" onkeyup= "doMathBase2Time()">
<br><br>
<input type="text" name="baseNumber_square" id="baseNumber_square" onkeyup= "doMathBaseSquare()">
<br><br>
</form>
</body>
You need to bind another function to the second and third field. I did it to the second. Now if you entered a number in the second field it return the 'base' number and the square of the base.
Try do it for the third :)
This should fit your needs:
Fiddle
//declaring those earlier saves you to get those by ID every
//time you call "doMath()" or something else
var base = document.getElementById("base");
var baseNumber_timesTwo = document.getElementById("baseNumber_timesTwo");
var baseNumber_square = document.getElementById("baseNumber_square");
function clearUp() {
base.value = "";
baseNumber_timesTwo.value = "";
baseNumber_square.value = "";
}
function doMath() {
//check which of the fields was filled
if(baseNumber_timesTwo.value){
base.value = baseNumber_timesTwo.value / 2;
}
if(baseNumber_square.value){
base.value = Math.sqrt(baseNumber_square.value);
}
//fill other fields according to that
baseNumber_timesTwo.value = (base.value*2);
baseNumber_square.value = (base.value*base.value) ;
}
As you see: There is no need to write more than one arithmetic function if you make sure that only one value is given at the time of evaluation (this is achieved by the cleanUp()
method)
However there are still some flaws in this solution! Since you are a js beginner I would suggest you to read the code and think about possible solutions for those problems as a little exercise :-)
- You cannot enter a 2 (or more) digit number in any field, why not? What do you have to change in order to allow such numbers as input?
- Why is it better (in this case!) to set the values to " " instead of '0' in the cleanUp function? Why does the code break when you try using '0' instead of "" ?
- Why does doMath() only check for values in the last two field (baseNumber_timesTwo and baseNumber_square) while ignoring the 'base' field?
Greetings, Tim

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources