Javascript/InnerHTML add and get integer values - javascript

I have been trying to get the values from the textView box but it's not displaying in the p field at all, and also I am trying to add the 2 values together into one value and display it.
function() {
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + x.elements[i].value;
}
document.getElementById("demo").innerHTML = text;
}
<h2>Finding HTML Elements Using document.forms</h2>
<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value="123"><br>
Last name: <input type="text" name="lname" value="123"><br><br>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>

You need to call the function on the document load. And make these changes inside the function
var myValue = 0;
for (i = 0; i < x.length; i++) {
if (x.elements[i].type === "text")
myValue += Number(x.elements[i].value);
}
document.getElementById("demo").innerHTML = myValue;

Try this. In your code.
document.getElementById("demo").innerHTML =
myfunction(document.forms["frm1"]);
should be called outside the function. Also, you should include a name for the function you've created.
function myfunction(input) {
var text = "";
for (var i = 0; i < input.length; i++) {
text += input[i].value;
}
return text;
}
document.getElementById("demo").innerHTML = myfunction(document.forms["frm1"]);
<h2>Finding HTML Elements Using document.forms</h2>
<form id="frm1" action="/action_page.php">
<label>First name:</label> <input type="text" name="fname" value="123" /><br>
<label>Last name:</label> <input type="text" name="lname" value="123" /><br><br>
<input type="submit"/>
</form>
<p id="demo"></p>

Related

Javascript innerHTML is automatically overwritten and nullified [duplicate]

This question already has answers here:
Clicking a button within a form causes page refresh
(11 answers)
Closed 1 year ago.
I was just practising HTML DOM and Forms, and I wrote a simple code, in which we take values from the form and display them in a <p> tag :
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
<script>
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
</script>
</body>
</html>
The problem is that when I press submit, the "hi" is replaced by " David Beckham " just for a millisecond, and is again changed to "hi". So by pressing submit continuously, I can see the text being changed again and again.
I don't understand what is happening, It is working, but it is not working. I don't see any errors in the code. Maybe it's code-related, or browser-related, or machine-related.
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
I don't why, but it is working in this snippet, but now in my browsers. I am using Macbook Air. I tried running it on both Safari and Chrome. Any help would be appreciated.
That is because onsubmit it will submit the form and refresh the form. So stop the default behaviour using event.preventDefault
function getFormvalue(e) {
e.preventDefault();
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML = text;
}
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="getFormvalue(event)">
First name: <input type="text" name="fname" value="David"><br> Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
You need to prevent form submision
function getFormvalue() {
var x = document.getElementById("myForm");
var text = "";
for (var i = 0; i < x.length; i++) {
if (x.elements[i].value != 'Submit') {
text += x.elements[i].value + " ";
}
}
document.getElementById("demo").innerHTML=text;
}
<html>
<head>
<title>Return first</title>
</head>
<body>
<p id="demo">hi</p>
<form id="myForm" name="myForm" onsubmit="event.preventDefault(); getFormvalue()">
First name: <input type="text" name="fname" value="David"><br>
Last name: <input type="text" name="lname" value="Beckham"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Pin Algorithm - Permuting values from a text-box and displaying the result below?

I'm having trouble permuting the values.
<head>
<link rel="stylesheet" type="text/css" href="PinStyle.css"/>
</head>
<body onload="startTime()">
<h1><div id="txt"></div></h1>
<br>
<h1>Pin Algorithm</h1>
<div class="container"
<form action="/action_page.php">
<input type="text" name="message" id="myInput1" value="" maxlength="1">
<input type="text" name="message" id="myInput2" value="" maxlength="1">
<input type="text" name="message" id="myInput3" value="" maxlength="1">
<input type="text" name="message" id="myInput4" value="" maxlength="1"><br><br>
<input id="demo" type="button" value="Permutation" onclick="permute()" /><br/>
</form>
<p id="demo"></p>
These are my textbox inputs
var test1 = "test1";
test1 = document.getElementById("myInput1").value;
var test2 = "test2";
test2 = document.getElementById("myInput2").value;
var test3 = "test3";
test3 = document.getElementById("myInput3").value;
var test4 = "test4";
test4 = document.getElementById("myInput4").value;
var permArr = [],
usedChars = [];
function permute(test1,test2,test3,test4) {
var i, ch;
input=[test1,test2,test3,test4]
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedChars.push(ch);
if (input.length == 0) {
permArr.push(usedChars.slice());
}
permute(input);
input.splice(i, 0, ch);
usedChars.pop();
}
return permArr
};
document.write(JSON.stringify(permute(var test1,test2,test3,test4)));
var combinations = permute(input);
document.getElementById("demo").innerHTML = combinations;
</script>
</div>
</body>
This is code to permute values typed into a text-box, I am having trouble getting javascript to read the values, find all combinations, and display the results.
Here it is. I adapted the perm() function, which does the actual permutation, from the accepted answer to this question.
<form action="/action_page.php">
<input type="text" name="message" id="myInput1" value="5" maxlength="1" size="1">
<input type="text" name="message" id="myInput2" value="9" maxlength="1" size="1">
<input type="text" name="message" id="myInput3" value="6" maxlength="1" size="1">
<input type="text" name="message" id="myInput4" value="2" maxlength="1" size="1">
<input type="button" value="Permutation" onclick="permute()" />
</form>
<p id="demo"></p>
<script>
function permute() {
// Create an array with the values of all inputs
const ar = [document.getElementById("myInput1").value,
document.getElementById("myInput2").value,
document.getElementById("myInput3").value,
document.getElementById("myInput4").value];
// Get array of permutations
const permutations = perm(ar);
// Convert array to string before printing it
document.getElementById("demo").innerHTML = JSON.stringify(permutations);
}
function perm(ar) {
let ret = [];
for (let i = 0; i < ar.length; i = i + 1) {
let rest = perm(ar.slice(0, i).concat(ar.slice(i + 1)));
if(rest.length) {
for(let j = 0; j < rest.length; j = j + 1) {
ret.push([ar[i]].concat(rest[j]))
}
} else {
ret.push([ar[i]]);
}
}
return ret;
}
</script>

Javascript multidimensional array loop from form inputs

I am having a problem with the array of an array. I need the function clickMe() to allow me to output an array such as [[1,1,1,1,1],[2,2,2,2,2],etc].
My problem is that right now the values come up as [1,1,1,1,1,2,2,2,2,2,etc]. I know a for loop inside a for loop would be the best way for this, but how would I get the inputs in sections of five?
Once I can figure this out, I should be able to pull from those arrays without any issues. I would prefer to keep this completely in Javascript.
var qNumber;
function onEnter() {
var qNumber = document.getElementsByName("numberBox")[0].value;
if(event.keyCode == 13) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem("qNumber", qNumber);
console.log(qNumber + " stored successfully");
} else {
console.log("Sorry, your browser does not support Web Storage...");
}
var qID = document.getElementById("numBox");
var submitBtn = document.getElementById("submitButton");
var a = qNumber - 1;
var b = 0;
while (b < a) {
var formClone = document.getElementsByClassName("formBox")[0];
var listClone = formClone.cloneNode(true);
var text =b+2;
document.getElementById("forms").append(listClone);
b++;
}
return qID.parentNode.removeChild(qID);
}
return qNumber;
}
function clickMe() {
var q = localStorage.getItem("qNumber");
console.log(q);
var inputNow = [];
var allInputs = [];
var eachArray = [];
var inputNow = document.getElementsByTagName("input");
for(x=0; x < inputNow.length; x++) {
allInputs.push(inputNow[x].value);
console.log(allInputs);
}
localStorage.clear();
}
input{
display: block;
}
<div id="forms">
<span id="numBox">
<label for="numberBox">Number of Forms</label>
<input type="number" name="numberBox" onkeydown="onEnter()" />
</span>
<form id="formBox" name="formBox" action="#" onsubmit="return false;">
<label for="info1">Input 1:</label>
<input type="text" name="info1" />
<label for="info2">Input 2:
</label>
<input type="text" name="info2" />
<label for="info3">Input 3:
</label>
<input type="text" name="info3" />
<label for="info4">Input 4:
</label>
<input type="text" name="info4" />
<label for="info5">Input 5:
</label>
<input type="text" name="info5" />
</form>
</div>
<input type="submit" value="Submit" id="submitButton" onclick="clickMe()" />
<div id="content">
<span id="info1">input1</span>
<br/>
<span id="info2">input2</span>
<br/>
<span id="info3">input3</span>
<br/>
<span id="info4">input4</span>
<br/>
<span id="info5">input5</span>
</div>
You can always do something like:
var allInputs = [];
var groupInputs = [];
for (x=0; x < inputNow.length; x++) {
groupInputs.push(inputNow[x].value);
if (groupInputs.length === 5 || x === inputNow.length - 1) {
allInputs.push(groupInputs);
groupInputs = [];
}
}

how to auto sum multiple inputbox inner loop in javascript

I want to calculate my input box inner looping and this bellow is what if done please help me to solve this issue
<?php
$jumlah_form = 3;
for($i=1; $i<=$jumlah_form; $i++){
?>
<input type="text" id="txt1" onkeyup="sum1();" /></br>
<?php
}
?>
<input type="text" id="txt2" value= "0" /></br>
<script>
function sum1() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtFirstNumberValue) ;
if (!isNaN(result)) {
document.getElementById('txt2').value = result;
}
}
</script>
Three input boxes are created by looping, I want to calculate three input box, and parse the result into result box whenever user input number
I think you are asking how to write the JavaScript so that it will add up the total of all the input boxes, no matter how many are created by the PHP?
If so then a good way would be to give all the textboxes the same class. Then, the JavaScript can just select all boxes with that class, loop through them and get the total value.
Here's a worked example using 3 textboxes (as if the PHP had generated them this way):
var textboxes = document.querySelectorAll(".sum");
textboxes.forEach(function(box) {
box.addEventListener("keyup", sumAll);
});
function sumAll() {
var total = 0;
textboxes.forEach(function(box) {
var val;
if (box.value == "") val = 0;
else val = parseInt(box.value);
total += val;
});
document.getElementById("total").innerText = total;
}
<input type="number" id="txt1" class="sum" value="0" /><br/>
<input type="number" id="txt2" class="sum" value="0" /><br/>
<input type="number" id="txt3" class="sum" value="0" /><br/>
<br/><br/> Total: <span id="total"></span>
To generate html with php:
$count = 5;
for($i=1;$i <= $count;$i++) {
echo "<input type='number' id='"."txt".i."' /></br>"
}
To calculate sum from inputs:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
<form onsubmit="submitForm(this); return false;" >
<input type="number" id='text1'>
<input type="number" id='text2'>
<input type="number" id='text3'>
<input type="number" id='text4'>
<input type="number" id='text5'>
<button type="submit" >Calculate</button>
</form>
<div>
<p>Result:</p>
<p id='result'></p>
</div>
<script>
function submitForm(form) {
let toReturn = 0;
const inputs = form.getElementsByTagName("input");
for(let x = 0; x < inputs.length; x++ ) {
toReturn += parseInt(inputs[x].value ? inputs[x].value : 0);
}
document.getElementById('result').innerHTML = toReturn;
return false;
}
</script>
</body>
</html>

Replace text in form using javascript

I have a form that has several fields. The first field is called subject. What I want to do is disable the ability for the user to type in the field, but it still show, and the text they enter into three other fields show up with spaces between the variables in the first field. Example: In this scenario: "Second_Field: John" "Third_Field: Doe" "Forth_Field: New part" then on first field, subject, it will show: John Doe New Part
Thanks for any help.
You can try the following:
<!-- HTML -->
<input type="text" id="subject" disabled="disabled">
<input type="text" id="field1">
<input type="text" id="field2">
<input type="text" id="field3">
// JavaScript
var fields = [];
for (var i = 1; i <= 3; i++) {
fields.push(document.getElementById("field" + i).value);
}
document.getElementById("subject").value = fields.join(" ");
Try this:
<script>
function UpdateText()
{
document.getElementById("subject").value =document.getElementById("Field1").value + " " + document.getElementById("Field2").value + " " + document.getElementById("Field3").value;
}
</script>
<input type="text" id="subject" disabled="disabled"/>
<input type="text" id="Field1" onchange="UpdateText()";/>
<input type="text" id="Field2" onchange="UpdateText()";/>
<input type="text" id="Field3" onchange="UpdateText()";/>
HTML:
<form>
<p><input id="subject" name="subject" disabled size="60"></p>
<p><input id="Second_Field" class="part">
<input id="Third_Field" class="part">
<input id="Fourth_Field" class="part"></p>
</form>
​
JavaScript:
var updateSubject = function() {
var outArray = [];
for (var i=0;i<parts.length;i++) {
if (parts[i].value !== '' ) {
outArray.push(parts[i].value);
}
}
document.getElementById('subject').value = outArray.join(' ');
};
var parts = document.getElementsByClassName('part');
for (var i=0;i<parts.length;i++) {
parts[i].onkeydown = updateSubject;
}
​

Categories

Resources