Adding Number Result in NaN - javascript

<script>
function myFunction(val) {
const ele = document.querySelectorAll('input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
}
</script>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<p id="result"></p>
<br>
<p><input type="submit" name= "submit" id="submit" value="Submit"/></p>
</form>
Why the result is NaN? But if I remove the value="Submit" in the last 5th line, then everything working fine. Why? and what should I do to solve this problem?

Your
const ele = document.querySelectorAll('input');
will iterate over all inputs, including the <input type="submit" name= "submit" id="submit" value="Submit"/>.
When you don't use value="Submit", that element doesn't have a real .value, so it defaults to the empty string:
console.log(submit.value);
console.log(submit.value.length);
<input type="submit" name="submit" id="submit">
In contrast, <input value="Submit"/> will have a .value of Submit, which can't be turned into a number.
Select only your inputs with input classes instead:
function myFunction() {
const ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
}
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<p id="result"></p>
<br>
<p><input type="submit" name="submit" id="submit" value="Submit" /></p>
Also note that duplicate IDs are invalid HTML, and event handlers should be attached properly using Javascript instead of using inline handlers:
const inputs = document.querySelectorAll('input.input');
inputs.forEach((input) => {
input.addEventListener('keydown', () => {
const sum = [...inputs].reduce((a, input) => a + Number(input.value), 0);
document.getElementById('result').textContent = sum.toFixed(2);
});
});
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" class="input">
<input type="text" class="input">
<p id="result"></p>
<br>
<p><input type="submit" value="Submit"></p>
</form>

Because you are selecting all the input tag, you should be specific on selecting like querySelectorAll('input[type="text"]'). so it will select only text input tags. Try this one
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction(val) {
const ele = document.querySelectorAll('input[type="text"]');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
}
</script>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<p id="result"></p>
<br>
<p><input type="submit" name= "submit" id="submit" value="Submit"/></p>
</form>
</body>
</html>

Because document.querySelectorAll('input'); selecting all inputs including submit button as well which has value='submit' and value submit is not a number (NAN). When you remove value attribute from the submit button it returns nothing.

Related

Using JavaScript to check for user-input

I'm submitting a form with input text to my server through my web client. What I'm trying to do is to check whether the user has passed in text into the input field before sending the form by hitting the submit button.
What I have tried so far:
var form = document.getElementById("id");
document.getElementById("id").addEventListener("click", function() {
var input = document.getElementById("content").value;
if (input == "") {
alert("write something in the textfield");
} else {
form.submit();
}
});
<form action="" method="post" id="id">
<input type="text" name="name" id="content">
<button type="submit" id="submit-id">submit text</button>
</form>
Any good tips on how to do this?
You want preventDefault on the submit event
document.getElementById("id").addEventListener("submit", function(e) {
const input = document.getElementById("content").value;
if (input.trim() === "") {
alert("write something in the textfield");
e.preventDefault()
}
});
<form action="" method="post" id="id">
<input type="text" name="name" id="content">
<button type="submit" id="submit-id">submit text</button>
</form>
Alternatively just add required attribute - no need for script:
<form action="" method="post" id="id">
<input type="text" name="name" id="content" required>
<button type="submit" id="submit-id">submit text</button>
</form>
you can use the simple code snippet instead :
<form action="" method="post" id="id">
<input type="text" name="name" id="content" required>
<button type="submit" id="submit-id">submit text</button>
</form>
function submitIt(e) {
var formData = new FormData(e);
var object = {};
formData.forEach(function(value, key) {
object[key] = value;
});
if (object.name == "") {
alert("null");
} else {
alert("ok");
return true;
}
return false;
}
<form onsubmit="return submitIt(this)">
<input type="text" name="name">
<button>submit text</button>
</form>

button Function onclick not display in text filed

I'm writing a code that display content in text field on button submit click, but the code below is not working
<script>
function myFunction() {
var x = document.getElementById("cost").value;
if (document.getElementById("cost").value;) {
var netprofit = x-(16/100*x);
document.getElementById("net").value = +netprofit;
else if (document.getElementById("cost").value;) {
var commission = netprofit * 35/100;
document.getElementById("comm").value = +commission;
}
}
}
</script>
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="submit" value="Calculate" onclick="myFunction()">
</form>
I expect result to display in an input text onClicking button
As Harpel pointed out, you have to prevent the form from submitting. This is default behavior for forms that contain a input of type submit. I'd also suggest reorganizing your code a bit (vars for each input you selecting, etc). Something like the below:
<script>
function myFunction(event) {
event.preventDefault();
var costInput = document.getElementById("cost");
var netInput = document.getElementById("net");
var commInput = document.getElementById("comm");
if (costInput.value) {
var netprofit = costInput.value - (16/100 * costInput.value);
netInput.value = netprofit;
} else if (costInput.value) {
var commission = netprofit * 35/100;
commInput.value = commission;
}
}
</script>
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="submit" value="Calculate" onclick="myFunction(event)">
</form>
One additional thing; I'm not sure what the if statement is supposed to be checking, as it seems to be checking the same condition. If that's the case, you can just place both calculations for the input values into one if check like:
if (costInput.value) {
var netprofit = costInput.value - (16/100 * costInput.value);
netInput.value = netprofit;
var commission = netprofit * 35/100;
commInput.value = commission;
}
Your input type is submit. So it will always submit form and reload the page. You can do in function like
"return false" from your function,
event.preventDefault() add in your function //it will avoid the default behavior (in your case submit form).
Or use button in your HTML in place of ("input" with type "submit").
Here is working snippet, but i don't know why you are writing same condition in "if" and "else if"
function myFunction(e) {
e.preventDefault();
var cost = document.getElementById("cost").value;
if (cost) {
cost = +cost;
var netprofit = cost - (16 / 100 * cost);
var commission = netprofit * 35 / 100;
document.getElementById("net").value = +netprofit;
document.getElementById("comm").value = +commission;
}
}
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="submit" value="Calculate" onclick='myFunction(event)'>
</form>
<form action="" method="POST">
<input type="text" id="cost" placeholder="kindly enter the cost value of project"><br><br>
<input type="text" name="" id="net" readonly="readonly"><br><br>
<input type="text" name="" id="comm" readonly="readonly"><br><br>
<input type="button" value="Calculate" onclick="myFunction()">
</form>
<script>
function myFunction() {
var x = document.getElementById("cost").value;
if (document.getElementById("cost").value) {
var netprofit = x - (16 / 100 * x);
document.getElementById("net").value = +netprofit;
}
else if (document.getElementById("cost").value) {
var commission = netprofit * 35 / 100;
document.getElementById("comm").value = +commission;
}
}
</script>
Output

How do I make each new output appear in a new box?

I would like for every different item inputted to be outputted in a new box.
<!DOCTYPE html>
<html>
<body>
Form to get the input
<form id="form1">
<input name="item" type="text" size="20">
</form>
Box that should be duplicated to hold the new input.
<div class="box">
<p class="output"></p>
<div>
<button onclick="outputItem()">Add</button>
javascript:
<script>
function outputItem() {
var x = document.getElementById("form1");
item = x.elements.namedItem("item").value;
document.getElementById("output").innerHTML=item;
</script>
</body>
</html>
I am not sure if this is even close to what you want, but give this a try:
function outputItem() {
var els = document.querySelectorAll("#form1 input");
var box = document.querySelector('.box');
box.innerHTML = '';
els.forEach(
function(el) {
var newEl = document.createElement('div');
newEl.innerHTML = el.value;
box.appendChild(newEl);
}
);
}
<form id="form1">
<input name="item" type="text" size="20" value="item"><br/>
<input name="eggs" type="text" size="20" value="eggs"><br/>
<input name="milk" type="text" size="20" value="milk"><br/>
<input name="grains" type="text" size="20" value="grains"><br/>
<input name="legumes" type="text" size="20" value="legumes"><br/>
</form>
<button onclick="outputItem()">Add</button>
<hr/>
<div class="box"></div>
This creates a new <div> for every input and copies the .value from the <input> into the new <div>. Then it adds the <div> into the output area.

Multiplying an input on a textbox and showing the answer on an alert (javascript)

I am trying to get an alert box to show up with the result of a multiplication operation when the user clicks on the submit button but I can't seem to get it right
function formAlert3() {
var x = document.getElementById('quantity').value;
var result = x * 120;
alert(result);
return false;
}
<form name="form3" onsubmit="formAlert3(); return false;">
<fieldset>
<label for="tel">quantity:</label>
<input type="text" name="quantity" id="quantity">
</fieldset>
</form>
<input type="submit" data-inline="true" value="Send" data-theme="b">
The submit button is outside the form.It need to be inside the form
function formAlert3(e) {
e.preventDefault();
var result = document.getElementById('quantity').value * 120;
alert(result);
return false;
}
<form name="form3" onsubmit="formAlert3(event)">
<fieldset>
<label for="tel">quantity:</label>
<input type="text" name="quantity" id="quantity">
</fieldset>
<input type="submit" data-inline="true" value="Send" data-theme="b">
</form>
You can do:
Call the formAlert3() function from the onclick event on the submit button
Out of the input formAlert3 you get a string, so you can use the Unary plus (+) to convert it into a number
Code:
function formAlert3() {
var x = document.getElementById('quantity');
var result = +x.value * 120;
alert(result);
return false;
}
<form name="form3">
<fieldset>
<label for="tel">quantity:</label>
<input type="text" name="quantity" id="quantity">
</fieldset>
</form>
<input type="submit" data-inline="true" value="Send" data-theme="b" onclick="formAlert3()">

Javascript dynamically created form field validation

I have created a form with a dynamically created field and i am trying to find a way to validate all the fields with javascript. I just want to alert the user that a field is null. Here is my code:
<script>
var counter = 0;
function addInput(divName){
counter++;
var Ai8ousa = document.createElement('div');
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>";
document.getElementById(divName).appendChild(Ai8ousa);
}
function validations(form){
var field;
var i=0;
do{
field=form['field[]'];
if (field.value=='')
{
alert('The field is null!!!');
return false;
}
i++;
}while(i<counter);
}
</script>
<form action="" method="post" onsubmit="return validations(this)" >
<div id="dynamicInput">
Field : <input type="text" name="field[]" /> <br />
</div>
<input type="button" value="New field" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit" />
</form>
I was expecting that will work but i was obviously wrong:(
With this code if i haven't pressed the "New field" button and press submit i will get the alert as expected. But on all other cases i am not getting anything!
Thanks for your time anyway, and sorry if i have made grammar mistakes!
<script type="text/javascript">
var counter = 0;
function addInput(divName){
counter++;
var Ai8ousa = document.createElement('div');
Ai8ousa.innerHTML = "Field: "+(counter +1) + "<input type='text' name='field[]'>";
document.getElementById(divName).appendChild(Ai8ousa);
}
function validations(form){
var field;
var i=0;
do{
field=form[i];
if (field.value=='')
{
alert('The field is null!!!');
return false;
}
i++;
}while(i<counter);
}
</script>
<form action="" method="post" onsubmit="return validations(this)" >
<div id="dynamicInput">
Field : <input type="text" name="field[]" /> <br />
</div>
<input type="button" value="New field" onClick="addInput('dynamicInput');">
<input type="submit" value="Submit" />
</form>
I don't understand this line: field=form['field[]'];, so I changed it to field=form[i];
http://jsfiddle.net/sZ4sd/

Categories

Resources