How to get input value using val() with js and jquery - javascript

I have been trying to take values of 4 inputs that are in a table and get the sum of the numbers on the input with a for loop but i keep getting 0 (the sum that i have defined)
Debugged everything and I am pretty sure the problem is in the "var x"- it just won't get any information from the inputs.
$(function () {
$("#inventoryForm").submit(function (event) {
var table = $("table")
var error = false;
event.preventDefault();
$(".inventoryInput").each(function(){
if($(this).val() < 0) {
error = true; //Indicate there was an error
$("#inventoryError").slideDown().text("Positive numbers only");
return false; //This stops the iteration
}
});
//Stop processing if there was an error
if (error) return;
if (!error) {
$("#inventoryError").hide();
}
$("#inventorySubmit").hide();
$("#inventoryChange").show();
$("#withdraw").show();
$(".inventoryInput").attr('disabled','disabled');
var sum = 0;
var money = table.find("td:nth-child(2)");
for (var i = 0; i<money.length; i++) {
var x = money.eq(i).val();
sum += x;
$("#totalMoney").text(sum);
}
console.log(money);
});
$("#inventoryChange").click(function () {
$("#inventorySubmit").show();
$("#inventoryChange").hide();
$("#withdraw").hide();
$(".inventoryInput").removeAttr('disabled');
});
});
.hidden {
display: none;
}
.error {
display: none;
color: red;
border: dotted 3px yellow;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<title>ATM</title>
<body>
<header>
<h1>Litman - Steklov ATMs</h1>
</header>
<section id="inventory">
<form id="inventoryForm">
<table>
<thead>
<tr>
<th>Bill</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>20</td>
<td>
<input id="inventoryInput" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>50</td>
<td>
<input id="inventoryInput2" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>100</td>
<td>
<input id="inventoryInput3" class="inventoryInput" type="number">
</td>
</tr>
<tr>
<td>200</td>
<td>
<input id="inventoryInput4" class="inventoryInput" type="number">
</td>
</tr>
</tbody>
</table>
<p id="inventoryError" class="error hidden">Validation errors will be here</p>
<p>Total Money: <span id="totalMoney"></span>
</p>
<button id="inventorySubmit" type="submit">Finish</button>
<button id="inventoryChange" type="button" class="hidden">Change</button>
</form>
</section>
<section id="withdraw" class="hidden">
<form>
<div>Withdraw:
<input type="number">
</div>
<p class="error hidden">Validation errors will be here</p>
<button type="submit">Process</button>
</form>
</section>
<section id="result" class="hidden">
<div>You Got:</div>
<button type="button">Finish</button>
</section>
</body>
</html>

The problem is indeed with
var x = money.eq(i).val();
money is an array of tds. So money.eq(i) is a td. What you want to get to is the actual input. So the solution is
var x = money.eq(i).find('input').val();
To elaborate on your further commend. If you fill in all 4 inputs using
var x = parseInt(money.eq(i).find('input').val());
it will sum them as expected. It will throw NaN when one of the inputs is empty because parseInt('') returns NaN, so you should check if the input actually has a value or not..
var input = money.eq(i).find('input').val();
var x = input ? parseInt(input) : 0
To further explain my code.
var input = money.eq(i).find('input').val();
This gets the value of the actual input, whatever that value may be.
var x = input ? parseInt(input) : 0
This checks whether the value of the input is empty or not. If it is empty then x=0 otherwise x=parseInt(input). So if the input is not empty, the value if being parsed to an int and assigned to x.
sum += x
x is being added to the final sum.

Related

How to display a message beside respective input in an html table?

I have created a table inside a form and one column consists of input elements. I have written a JavaScript function to validate each input. If invalid, the corresponding error message should be displayed beside respective input. In my case, for any input, the error message is always displayed beside the first input.
I tried using <div> and <span> tags with respective id values. For every invalid input the error message is displayed beside the first input and not the corresponding input.
Html table
<table>
<tr>
<td>S.No</td>
<td>Particulars</td>
<td>Amount</td>
<td></td>
</tr>
<tr>
<td>01</td>
<td>Annual Rent (Only of residential unit not owned by employer)</td>
<td><input type="number" name="ann_rent"><div id="ar_invalid"></div></td>
</tr>
<tr>
<td>02</td>
<td>Mediclaim (U/s. 80D of I.T. Act)</td>
<td><input type="number" name="medi"><div id="medi_invalid"></div></td>
</tr>
<tr>
<td>03</td>
<td>Interest paid for Home Loan</td>
<td><input type="number" name="home_int"><div id="home_invalid"></div></td>
</tr>
<tr>
<td>04</td>
<td>National Pension</td>
<td><input type="number" name="nat_pen"><div id="pen_invalid"></div></td>
</tr>
</table>
Javascript function
function validate() {
var a,b,c,d;
a = document.getElementsByName("ann_rent")[0].value;
b = document.getElementsByName("medi")[0].value;
c = document.getElementsByName("home_int")[0].value;
d = document.getElementsByName("nat_pen")[0].value;
if(!a || a < 0) {
document.getElementById("ar_invalid").innerHTML = text;
return false;
}
if(!b || b < 0) {
document.getElementById("medi_invalid").innerHTML = text;
return false;
}
if(!c || c < 0) {
document.getElementById("home_invalid").innerHTML = text;
return false;
}
if(!d || d < 0) {
document.getElementById("pen_invalid").innerHTML = text;
return false;
}
}
Table is inside this form
<form action="process_form.php" method="post" onSubmit="return validate();">
CSS
td, th {
text-align: left;
padding: 8px;
}
table {
margin-top: 30px;
margin-bottom: 10px;
font-family: arial, sans-serif;
width: 100%;
}
If user enters a negative value in input name="home_int", then the error message should be displayed beside input home_int. But actually, the error message is getting displayed beside input name="ann_rent". This situation is occurring for every input.
use th for headers. Add a new td for the error message
<table>
<tr>
<th>S.No</th>
<th>Particulars</th>
<th>Amount</th>
<th></th>
</tr>
<tr>
<td>01</td>
<td>Annual Rent (Only of residential unit not owned by employer)</td>
<td><input type="number" name="ann_rent"></td>
<td><div id="ar_invalid"></div></td>
</tr>
</table>
css
table td, table th {
padding: 20px;
border-spacing: 10px;
}
table {
border-collapse: collapse;
}
Assuming you have a button to submit for form validation which goes something like this:
<input type="submit" name="s" value="ds"/>
What happening is when your function gets inside the first if it then returns false and form will not be submitted so the other ifs wont perform any action in this situation so when you type any negative number in the first if, other ifs whether they are positive or negative wont work and the code will execute the message in the first div
but it will work and will show the message in the desired div if you will only put a negative number inside a specific textbox and all before will be positive
Change the "errors" divs to similar as below so you can have a simpler javascript code:
HTML:
<form action="/" method="post" onSubmit="return validate();">
<table>
<tr>
<td>S.No</td>
<td>Particulars</td>
<td>Amount</td>
<td></td>
</tr>
<tr>
<td>01</td>
<td>Annual Rent (Only of residential unit not owned by employer)</td>
<td><input type="number" name="ann_rent"><div id="ann_rent_invalid"></div></td>
</tr>
<tr>
<td>02</td>
<td>Mediclaim (U/s. 80D of I.T. Act)</td>
<td><input type="number" name="medi"><div id="medi_invalid"></div></td>
</tr>
<tr>
<td>03</td>
<td>Interest paid for Home Loan</td>
<td><input type="number" name="home_int"><div id="home_int_invalid"></div></td>
</tr>
<tr>
<td>04</td>
<td>National Pension</td>
<td><input type="number" name="nat_pen"><div id="nat_pen_invalid"></div></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
and in javascript:
function validate() {
var text = "error";
var required = ["ann_rent", "medi", "home_int", "nat_pen"];
var errors = 0;
required.forEach(function(element) {
var toselect = element + "_invalid";
var reqV = document.getElementsByName(element)[0].value;
if(!reqV || reqV < 0) {
document.getElementById(toselect).innerHTML = text;
errors++;
} else {
document.getElementById(toselect).innerHTML = null;
}
});
if(errors > 0){
return false;
}
}

Trying to alert value of same selector in two iterations, getting correct value in 1st iteration and incorrect one in second. Why?

JSFiddle here.
In the following SSCCE,there are two .inner-table elements. I have used JQuery each() to iterate through them. Then inside each .inner-table, I iterate through each <tr> to find out and alert the value of the <input>.color-name element, by using val() function.
The problem is that in the first iteration, the alert showing value of <input>.color-name shows correct value I entered into the text field, but in the second iteration (i.e. for the second inner-table), the alert seems to show an empty string no matter what I write into the text field.
The question is why? What am I doing wrong?
$(document).on("click", "#button", function(event) {
//event.preventDefault();
alert('Button clicked.'); //check
var colorName;
var dataJSON = {};
$(".inner-table").each(function() {
var dataUnit = [];
dataJSON.dataUnit = dataUnit;
var iterationCount = 1;
$(this).find("tbody tr").each(function() {
alert("Iteration " + iterationCount); //check
//alert($(this).html());//check
if ($(this).find("td .color-name").length) {
colorName = $(this).find("td .color-name").val();
alert(colorName); //check
}
iterationCount++;
});
var color = {
"colorName": colorName
};
dataJSON.dataUnit.push(color);
});
console.log("dataJSON > " + JSON.stringify(dataJSON)); //check
});
.outer-table tr {
margin: 30px;
}
.inner-table {
border: 2px solid yellow;
background-color: wheat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">
Click
</button>
<table class="outer-table">
<tbody>
<tr>
<td colspan="3">
<table class="inner-table">
<tbody>
<tr>
<td>
<p class="input-label">Name of Color</p>
<input class="input-field color-name" type="text" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<!-- ------------------------------------------------- -->
<!-- ------------------------------------------------- -->
<!-- ------------------------------------------------- -->
<tr>
<td colspan="3">
<table class="inner-table">
<tbody>
<tr>
<td>
<p class="input-label">Name of Color</p>
<input class="input-field colorName" type="text" />
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
you are using a wrong class name in the second td. you are using "colorName" it should be "color-name"
You should read more on the each API here: http://api.jquery.com/jQuery.each/. You should change your callback function to accept parameters including the iteration variable, rather than declaring your own. I think that is start of your solution. In the jsfiddle, the iterator variable never seems to advance in the alerts popped up.

How to read an array of integers from an element to get values from it?

I make a code , that randomly display an 6-item array in a div.
i want to read the array and pass it to function to calculate the mean of it?
HTML
what i must do , how can i store the data of div(id="numbers" )
and push it in array ?
<pre>
<div >
<form action="" method="post" name="meanForm" onsubmit='return false' id="formmine">
<table width="100%" border="0"
<tr>
<td colspan="3" style="background-color:#06F ;color:#FFF">Answer this problem</td>
</tr>
<tr>
<td style="color:green; font-size:20px">What is the mean of these numbers </td>
<td colspan="2" ><div id="numbers"></div>
</td>
</tr>
<tr>
<td colspan="3"> </td>
</tr>
<tr id="answerANDpic">
<td height="62" colspan="3" align="center" > <input name="" type="text" size="15" maxlength="100" height="50" style=" border: solid #0C0 ; border-width:thin" id="answer" onkeydown="searchm(this)"/> </td>
</tr>
<tr>
<td colspan="3" ><div id ="explain" ></div></td>
</tr>
<tr>
<td> </td>
<td><input name="" type="button" id="newEx" style="background-color:green ; color:white" align ="left" value="New Problem" class="send_feed" onclick="randomArray(6,0,99)" /></td>
<td><input name="" type="button" id="solution" style="background-color:#606 ; color:#FFF " align="left" class="send_feed" value="Solution" onclick="solution()"/></td>
</tr>
</table>
</form>
</div>
in JS
var myNumArray = randomArray(6,0,99);
function random_number(min,max) {
return (Math.round((max-min) * Math.random() + min));
}
function randomArray(num_elements,min,max) {
var nums = new Array;
for (var element=0; element<num_elements; element++) {
nums[element] = random_number(min,max);
}
document.getElementById("numbers").innerHTML=nums;
calcMean(nums);
}
function calcMean(nums) {
var num=0;
for (var i=0;i<nums.length;i++) {
num += parseFloat( nums[i], 6 );
}
var divide=num/nums.length;
var mean=(parseInt(divide,10));
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
return mean,maxi,mini;
}
function searchm(ele) {
if(event.keyCode == 13) {
// alert(ele.value); // i get the value and put it on alert
var inans= ele.value;
return inans;
}
}
function soltuion(){
//read array saved in div id="numbers"
// call calcMean()
//get the mean and max min values
}
See comments in code below. Your code is not far off working.
function calcMean(nums){
var num=0;
for (var i=0;i<nums.length;i++){
// parseFloat only has one argument
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
num += parseFloat( nums[i])
// If the numbers in the nums array
// are already floats, you don't need parseFloat
// So maybe you can do... ?
// num += nums[i]
}
// The line below might divide by zero, so check
if (nums.length == 0) {
return 0;
}
var divide=num/nums.length;
// No need to reparse a number.
mean=divide
// This code suggests that nums is already filled with numbers
// See comment in for-loop above
var maxi = Math.max.apply(Math,nums);
var mini = Math.min.apply(Math,nums);
// This returns all 3 numbers
return [mean,mini,maxi];
// If you want just the mean,
// return mean;
}

How can I update a set of text fields on key press and avoid resetting a form on submit?

I'm trying to make a simple converter like this one, but in JavaScript, where you enter an amount in tons and it displays a bunch of different numbers calculated from the input, sort of like this:
This is what I've tried:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output")
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" />
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
This works, to the extent that when you press the button, it calculates and displays the right number. However, it also seems to reset the form when I press the button, and I'm hoping to eliminate the need for the button altogether (so on every key press it recalculates).
Why is the form resetting, and how could I extend this to not need the button at all?
Here is the fiddle link for it:
Calculator
Use the below code to achieve what I think you want to :
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Please check this FIDDLE.
All you need to adding attributes data-formula to your table cells.
HTML
<table border="1">
<tr>
<td>
<input type="text" id="initial-val" />
</td>
<td>card board</td>
<td>recycled</td>
<td>reusable</td>
</tr>
<tr>
<td>lovely trees</td>
<td data-formula='val*5'></td>
<td data-formula='val+10'></td>
<td data-formula='val/2'></td>
</tr>
<tr>
<td>what is acres</td>
<td data-formula='val*2'></td>
<td data-formula='val*(1+1)'></td>
<td data-formula='val*(10/5)'></td>
</tr>
</table>
JAVASCRIPT
$(function () {
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var $input = $('#initial-val'),
$cells = $('td[data-formula]');
$input.on('keyup', function () {
var val = $input.val();
if (isNumber(val)) {
$.each($cells, function () {
var $thisCell = $(this);
$thisCell.text(
eval($thisCell.attr('data-formula').replace('val', val.toString()))
)
});
} else {
$cells.text('ERROR')
}
});
});
You'll need:
a drop down option that allows the user to select what type of calculation they want to do and then display an input field OR multiple input fields
an input field for user input
a submit button with a onclick() event which passes your input into your calculation
(you may want to do some validation on this so they can only enter numbers)
validation examples
your Javascript file that takes the input from your box on submit and performs your calculation
display the information back to user... something like innerHtml to an element you've selected or:
var output = document.getelementbyid("your outputbox")
output.value = "";
output.value = "your calculated value variable";
Here is a tutorial for grabbing user input.
Assuming your calculations are all linear, I would suggest that you create an array of the coefficients and then just loop that array to do the calculation and print it out. Something like this:
HTML:
<table>
<tr>
<th></th>
<th>Recycled Cardboard</th>
<th>Re-usable Cardboard</th>
</tr>
<tr>
<th>Trees Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Acres Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Energy (in KW)</th>
<td></td><td></td>
</tr>
<tr>
<th>Water (in Gallons)</th>
<td></td><td></td>
</tr>
<tr>
<th>Landfill (Cubic Yards)</th>
<td></td><td></td>
</tr>
<tr>
<th>Air Pollution (in Lbs)</th>
<td></td><td></td>
</tr>
</table>
Javascript:
function showStats(cardboardTons) {
var elements = $("td");
var coeffs = [17, 34, 0.025, 0.5, 4100, 8200, 7000, 14000, 3, 6, 60, 120];
for(var i=0;i<coeffs.length;i++)
elemnts.eq(i).html(cardboardTons * coeffs);
}
Once you get input from the user, pass it into the showStats function as a number and it will go through all of the cells in the table and calculate the proper number to go in it.

How can I make a table in a cell a variable?

I have a table in a cell that displays the numbers a user enters with buttons (using onclick and a showthis function. I need to be able to store the value as a variable in order to perform operations on it. How can I do this?
PS: I am using JavaScript and HTML
<script language="JavaScript" type="text/javascript">
function showthis(first){
document.getElementById("displaycell").innerHTML+=first;
}
</script>
<body>
<h1 align="center"> RPN Calculator </h1>
<table summary align="center" border="1" cellpadding="1" cellspacing="3">
<tr>
<th id="displaycell" colspan="5" type="text"> </td>
</tr>
<tr>
<td>
<button type="button" onclick="showthis('1')">1</button>
</td>
<td>
<button type="button" onclick="showthis('2')">2</button>
</td>
<td>
<button type="button" onclick="showthis('3')">3</button>
</td>
<!-- ... -->
Firstly you should not be using += with innerHTML. It means that you will end up with the numbers appending to the cell's internal value rather than overwriting it.
function showthis ( number ) {
var cell = document.getElementById('displaycell');
cell.innerHTML = "";
cell.appendChild( document.createTextNode( number ));
}
Would be a much better way to handle that.
Next, within showthis you are best off storing the value in a variable so that you can access it directly from javascript in the future.
var displayStore = 0;
function showthis ( number ) {
var cell = document.getElementById('displaycell');
cell.innerHTML = "";
cell.appendChild( document.createTextNode( number ));
// you can either do this in a variable local to the <td> DOM Object like so
cell.currentDisplayNumber = number;
//or in a global variable like so
displayStore = number;
}
Finally, to access that variable again you can either read it out of the displaystore <td> or read it from your variable.
function DoStuff0 () {
var number = Number( document.getElementById( 'displaycell' )).innerHTML;
// rest
}
function DoStuff1 () {
var number = document.getElementById('displaycell').currentDisplayNumber;
// rest
}
function DoStuff2 () {
var number = displayStore;
// rest
}
Is this what you wanted? http://jsfiddle.net/CWQY2/
HTML:
<h1 align="center"> RPN Calculator </h1>
<table summary align="center" border="1" cellpadding="1" cellspacing="3">
<tr>
<th id="displaycell" colspan="5"> </th>
</tr>
<tr>
<td> <button type="button" onClick="showthis('1')">1</button> </td>
<td> <button type="button" onClick="showthis('2')">2</button> </td>
<td> <button type="button" onClick="showthis('3')">3</button> </td>
</tr>
</table>
JS:
function showthis(first){
document.getElementById("displaycell").innerHTML += first;
}
​
​

Categories

Resources