Converting JavaScript Object to Float - javascript

I am currently trying to make an application where I can add up the columns of an HTML table. I am able to add inputs to the table but when I try to add up the columns I get, "NaN" error.
/* Function to calculate income */
function Add() {
// Variables from input field
var table = document.getElementById("Expenses");
var name = document.getElementById("Name").value;
var price = parseFloat(document.getElementById("Price").value);
if (price == "" && name == "") {
alert("Please enter in values.");
} else {
// Insert a default row from here:
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
col0.innerHTML = name;
col1.innerHTML = "$" + parseFloat(price);
document.getElementById("Name").value = "";
document.getElementById("Price").value = "";
console.log(typeof col1);
}
}
/* Function to add up last column */
function Calculate() {
var table = document.getElementById("Expenses");
var sumVal = 0;
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
for (var i = 1; i < table.rows.length; i++) {
sumVal += parseFloat(table.rows[i].cells[1]);
}
col0.innerHTML = "All Expenses";
col1.innerHTML = sumVal;
}
<div class="body">
<div class="container">
<div class="center">
<h3>Enter Expenses Below</h3>
<ul class="info">
<li>
<input type="text" placeholder="Name of Expense" id="Name">
</li>
<li>
<input type="number" min="0" placeholder="Price of Expense" id="Price">
</li>
</ul>
</div>
</div>
<table class="topmargin results-field" id="Expenses">
<tr>
<th>Name of Expense</th>
<th>Price of Expense</th>
</tr>
</table>
<div class="container1">
<div class="center1">
<button type="button" id="Add" onclick="Add()">Add</button>
<button type="button" id="Remove" onclick="Remove()">Remove</button>
<button type="button" id="Calculate" onclick="Calculate()">Calculate</button>
<button type="button" id="Print" onclick="window.print()">Print</button>
</div>
</div>
</div>
Any help is appreciated. Thank you.

Cell is a td element so we should get its innerHTML or innerText and remove '$' symbol from it. And for loop should be table.rows.length-1 because of last sum row. And it's clean now!
/* Function to calculate income */
function Add() {
// Variables from input field
var table = document.getElementById("Expenses");
var name = document.getElementById("Name").value;
var price = parseFloat(document.getElementById("Price").value);
if (price == "" && name == "") {
alert("Please enter in values.");
} else {
// Insert a default row from here:
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
col0.innerHTML = name;
col1.innerHTML = "$" + parseFloat(price);
document.getElementById("Name").value = "";
document.getElementById("Price").value = "";
console.log(typeof col1);
}
}
/* Function to add up last column */
function Calculate() {
var table = document.getElementById("Expenses");
var sumVal = 0;
var Entry = table.insertRow(-1);
var col0 = Entry.insertCell(0);
var col1 = Entry.insertCell(1);
for (var i = 1; i < table.rows.length-1; i++) {
sumVal += parseFloat(table.rows[i].cells[1].innerHTML.replace('$',''));
}
col0.innerHTML = "All Expenses";
col1.innerHTML = "$" + sumVal;
}
<div class="body">
<div class="container">
<div class="center">
<h3>Enter Expenses Below</h3>
<ul class="info">
<li>
<input type="text" placeholder="Name of Expense" id="Name">
</li>
<li>
<input type="number" min="0" placeholder="Price of Expense" id="Price">
</li>
</ul>
</div>
</div>
<table class="topmargin results-field" id="Expenses">
<tr>
<th>Name of Expense</th>
<th>Price of Expense</th>
</tr>
</table>
<div class="container1">
<div class="center1">
<button type="button" id="Add" onclick="Add()">Add</button>
<button type="button" id="Remove" onclick="Remove()">Remove</button>
<button type="button" id="Calculate" onclick="Calculate()">Calculate</button>
<button type="button" id="Print" onclick="window.print()">Print</button>
</div>
</div>
</div>

Related

How do I make a dynamic drop down menu using JavaScript

I have it so you type in on a form a maximum number then it creates a table after clicking a button.
I want it so after you click the button to add the row it writes a drop down menu in the table that goes from 0 to the number you put in the form
This is my HTML code:
<html>
<head>
<title>Form Generator</title>
<link rel="stylesheet" type="text/css" href="../css/converter.css"/>
<script language="JavaScript" src="../js/exercise2.js" type="text/javascript">
</script>
</head>
<body>
<p>
<button class="button" data-modal="M2KM">Form Generator</button>
</p>
<div id="M2KM" class="modal">
<div class="modal-content">
<div class="form">
<a class="close">×</a>
<form action="">
<textarea rows="1" name="Section" id="Section" cols="10">Section</textarea>
<textarea rows="1" name="Max" id="Max" cols="10">Max</textarea>
<textarea rows="1" name="Comment" id="Comment" cols="10">Comment</textarea>
<textarea rows="1" name="Mark" id="Mark" cols="10">Mark</textarea>
<input type="button" value="Add Row" name="Add Row" onclick="conversionTable('table')" />
<input type="reset" value="Clear" name="Clear">
</form>
<div id="conversion">
<table id="table">
<thead>
<tr>
<th>Section</th>
<th>Max</th>
<th>Comment</th>
<th>Mark</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
This is my JavaScript Code:
function conversionTable(tagId, from, to)
{
var section = document.getElementById("Section").value;
var max = document.getElementById("Max").value;
var comment = document.getElementById("Comment").value;
var mark = document.getElementById("Mark").value;
from = 0;
to = 1;
var total = 0;
var arr = [];
var conv = document.getElementById(tagId) ;
var pre = document.createElement("pre");
conv.appendChild(pre);
var body= conv.appendChild(document.createElement("tbody"));
for (var i=from; i<to; i++)
{ row = body.appendChild(document.createElement("tr"));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(section));
data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(max));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(comment));
data=row.appendChild(document.createElement("select"));
data.setAttribute("id", "mySelect");
row.appendChild(data);
var z = document.createElement("option");
z.setAttribute("value", "volvocar");
var t = document.createTextNode("1");
z.appendChild(t);
document.getElementById("mySelect").appendChild(z);
total = total + mark;
var obj = {section: section, max: max, comment: comment, mark: mark};
arr.push(obj);
}
}
This is a screenshot showing test data:
Here's a simplified example that adds a select element with a number of options equal to the number entered by the user.
See comments in the code for an explanation of how it works.
// Identifies existing HTML elements
const maxInput = document.getElementById("max");
const button = document.getElementById("button");
const table = document.getElementById("table");
// Calls `addDropdown` when `button` is clicked
button.addEventListener("click", addDropdown);
// Defines the event listener
function addDropdown(event) { //(`event` object is available if we want it)
// Gets value from input
let max = parseInt(maxInput.value);
// Exits function early if maxInput doesn't have a number
if(!max){ return; }
// Defines the new elements
const row = document.createElement("tr");
const cell = document.createElement("td");
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let optNumber = -1;
while(++optNumber <= max){
let optionElement = document.createElement("option");
optionElement.value = "opt" + optNumber;
optionElement.innerHTML = "Option " + optNumber;
dropdown.appendChild(optionElement);
}
// Adds the elements to the page
cell.appendChild(dropdown);
row.appendChild(cell);
table.appendChild(row);
}
<label>
<span>Enter maximum value for dropdown:</span>
<input id="max" value="5" />
</label>
<br />
<button id="button">Add Dropdown in New Row</button>
<div id="container">
<table id="table"></table>
</div>

How can I make the user add a new field using a button using javascript?

I have a script posted down below, and I want the user to add a new field, when the new field gets added I want a new var to be added.
Live example:
User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.
I don't have an idea of how to do the above honestly.
<!DOCTYPE html>
<html lang="en">
<form name="TRF" method="post">
<p style="color:white">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="jumbotron">
<h1 class="text-center">Accepted Format</h1>
<hr>
<div class="row">
<h6 class="text-uppercase"><strong><center>Accepted Format</center></strong></h6>
<table style="width:100%" id="theTable">
<tr>
<td>Applicant's Name:</td>
<td><input type="text" name="accname" size="75" placeholder="" required></td>
</tr>
<tr>
<td>Reason 1:</td>
<td><input type="text" name="R1" size="75" placeholder="" required></td>
</tr>
<tr>
<td id="bla">Reason 2:</td>
<td><input type="text" name="R2" size="75" placeholder="" required></td>
</tr>
</table>
<h3>CODE:</h3>
<textarea id="box" cols="100" rows="10"></textarea>
<p><a class="btn btn-success btn-lg" onclick="generateCode2()" role="button">GENERATE CODE</a></p>
</div>
<button id="newField">
add new field
</button>
</center>
</div>
</div>
</div>
</div>
<html>
<head>
<script>
function generateCode2() {
var AccoutName = document.forms["TRF"]["accname"].value;
var Reason1 = document.forms["TRF"]["R1"].value;
var Reason2 = document.forms["TRF"]["R2"].value;
document.getElementById("box").value =
"[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]"+
"[hr]"+
"\n"+
"[b]Dear[/b] "+AccoutName+
"\n"+
"After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. "+
"\n"+
"Reason One: " +Reason1+
"\n"+
"Reason Two: " +Reason2+
"\n"+
"Welcome to the Family. "+
"\n"+
""
}
var newField = document.getElementById("newField");
var counter = 3;
function createNewField() {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td1.innerHTML = "Reason " + counter + ":";
var inp = document.createElement("input");
inp.type = "text";
inp.size = "75";
inp.name = "R" + counter;
inp.value=document.getElementById("box").value;
td2.appendChild(inp);
document.getElementById("theTable").appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
counter++;
}
newField.addEventListener("click", createNewField);
(function () {
var onload = window.onload;
window.onload = function () {
if (typeof onload == "function") {
onload.apply(this, arguments);
}
var fields = [];
var inputs = document.getElementsByTagName("input");
var textareas = document.getElementsByTagName("textarea");
for (var i = 0; i < inputs.length; i++) {
fields.push(inputs[i]);
}
for (var i = 0; i < textareas.length; i++) {
fields.push(textareas[i]);
}
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) {
field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })");
}
if (typeof field.onpaste == "function") {
var oninput = field.oninput;
field.oninput = function () {
if (typeof oninput == "function") {
oninput.apply(this, arguments);
}
if (typeof this.previousValue == "undefined") {
this.previousValue = this.value;
}
var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != "");
if (pasted && !this.onpaste.apply(this, arguments)) {
this.value = this.previousValue;
}
this.previousValue = this.value;
};
if (field.addEventListener) {
field.addEventListener("input", field.oninput, false);
} else if (field.attachEvent) {
field.attachEvent("oninput", field.oninput);
}
}
}
}
})();
</script>
</head>
</color>
</font>
</div>
</div>
</div>
</html>
User clicks on the "add new field"
var gets added below var Reason2 called Reason3, Reason4, etc.
"Reason Three: " +Reason3+ gets added below Reason Two on line 51.
In Javascript it's possible to create html elements at runtime using the createElement() function. In your case we need to create quite a lot of individual elements to replicate the structure of the table. Those are <tr> <td> <input>.
The tr element needs to be added to the table, the td containing the text 'Reason #:' as well as the td holding the input element are childs of tr. To add a dynamically created element to the DOM, the appendChild() function is used.
The input element needs some special treatment because it contains an unique id. The two html-made elements you have are 'R1' and 'R2' - so a new one should follow that pattern and start with 3. This is done by setting up a global variable , appending it to the name and increment it afterwards.
Finally we need to add a 'Create new field' button.
Take a look at this example (you have to scroll down to see the button):
var newField = document.getElementById("newField");
var counter = 3;
function createNewField() {
var tr = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
td1.innerHTML = "Reason " + counter + ":";
var inp = document.createElement("input");
inp.type = "text";
inp.size = "75";
inp.name = "R" + counter;
td2.appendChild(inp);
document.getElementById("theTable").appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
counter++;
}
newField.addEventListener("click", createNewField);
function generateCode2() {
var AccoutName = document.forms["TRF"]["accname"].value;
var reasons = "";
for (var a = 1; a < counter; a++) {
reasons += "Reason " + a + ": " + document.forms["TRF"]["R" + a].value + "\n";
}
document.getElementById("box").value =
"[center][img width=500 height=500]https://i.imgur.com/FuxDfcy.png[/img][/center]" +
"[hr]" +
"\n" +
"[b]Dear[/b] " + AccoutName +
"\n" +
"After reading your Application, Imperials staffs have decided to [color=green][b]Accept[/b][/color] you. " +
"\n" + reasons +
"Welcome to the Family. " +
"\n" +
""
}
<form name="TRF" method="post">
<p style="color:white">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="jumbotron">
<h1 class="text-center">Accepted Format</h1>
<hr>
<div class="row">
<h6 class="text-uppercase"><strong><center>Accepted Format</center></strong></h6>
<table style="width:100%" id="theTable">
<tr>
<td>Applicant's Name:</td>
<td><input type="text" name="accname" size="75" placeholder="" required></td>
</tr>
<tr>
<td>Reason 1:</td>
<td><input type="text" name="R1" size="75" placeholder="" required></td>
</tr>
<tr>
<td id="bla">Reason 2:</td>
<td><input type="text" name="R2" size="75" placeholder="" required></td>
</tr>
</table>
<h3>CODE:</h3>
<textarea id="box" cols="100" rows="10"></textarea>
<p><a class="btn btn-success btn-lg" onclick="generateCode2()" role="button">GENERATE CODE</a></p>
</div>
<button id="newField">
add new field
</button>
</center>
</div>
</div>
</div>
</div>

Trying to remove each line of HTML element using a newly created button

var Operator = document.getElementById("operation");
var Desc = document.getElementById("description");
var Amount = document.getElementById("value");
var budget = 0.00;
var income = 0.00;
var expenses = 0.00;
var IncomeList = document.getElementById("incomeList");
var ExpenseList = document.getElementById("expenseList");
document.getElementById("submit").addEventListener("click", function() {
var DButton = document.createElement("button");
var t = document.createTextNode("Delete");
//document.body.appendChild(DButton);
DButton.appendChild(t);
// Converts the fake (non-existant)numbers into real (functionable) numbers
var aValue = parseFloat(Amount.value);
// if the operator is +, budget and income will increase by whatever you type in the value
if (Operator.value == "+") {
budget = budget += aValue;
income = income += aValue;
// The value that was typed along with description in will appear in the Income list in each line
IncomeList.innerHTML = IncomeList.innerHTML + Desc.value + ": " + aValue;
IncomeList.appendChild(DButton);
IncomeList.innerHTML = IncomeList.innerHTML + "<br>";
} else {
budget = budget -= aValue;
expenses = expenses -= aValue;
ExpenseList.innerHTML = ExpenseList.innerHTML + Desc.value + ": " + aValue;
ExpenseList.appendChild(DButton);
ExpenseList.innerHTML = ExpenseList.innerHTML + "<br>";
}
// Declaring statements to make it easier to input
document.getElementById("budget").innerText = budget;
document.getElementById("incomeTotal").innerText = income;
document.getElementById("expenseTotal").innerText = expenses;
});
<div id="wrapper">
<div id="top">
<p id="day">Available Budget in January 2018:</p>
<p id="budget">0.00</p>
<div id="income" class="highlight">
<h1>Income</h1>
<p id="incomeTotal">+0.00</p>
</div>
<div id="expenses" class="highlight">
<h1>Expenses</h1>
<p id="expenseTotal">-0.00</p>
</div>
</div>
<div id="controls">
<select id="operation">
<option>+</option>
<option>-</option>
</select>
<input type="text" placeholder="Add description" id="description" required/>
<input type="number" min="1" placeholder="Value" id="value" />
<button id="submit">✓</button>
</div>
<div id="content">
<div id="incomeList">
<p>INCOME</p>
</div>
<div id="expenseList">
<p>EXPENSES</p>
</div>
</div>
</div>
Hi, this is a budget tracker I made to practice JavaScript. So whenever users type a description and an amount and press submit, the list will show up along with a delete button that erases each line. How should I approach this method? Because the button is newly created by createElement, I do not know how to make this a handler...Thank you.
Append a row container instead of concatenating to the HTML string, and then you can attach a listener to the button that calls .remove() on the row.
It's often a good idea to avoid assigning to innerHTML when possible - it will corrupt all existing Javascript references to any elements inside. If you want to assign text alone, use textContent rather than innerHTML or createTextNode. (it's faster, safer, and more predictable)
var Operator = document.getElementById("operation");
var Desc = document.getElementById("description");
var Amount = document.getElementById("value");
var budget = 0.00;
var income = 0.00;
var expenses = 0.00;
var incomeList = document.getElementById("incomeList");
var expenseList = document.getElementById("expenseList");
document.getElementById("submit").addEventListener("click", function() {
const parent = Operator.value === "+" ? incomeList : expenseList;
const row = parent.appendChild(document.createElement('div'));
var DButton = row.appendChild(document.createElement("button"));
DButton.textContent = 'delete';
DButton.onclick = () => row.remove();
var aValue = parseFloat(Amount.value);
row.appendChild(document.createTextNode(Desc.value + ": " + aValue));
if (Operator.value == "+") {
budget = budget += aValue;
income = income += aValue;
} else {
budget = budget -= aValue;
expenses = expenses -= aValue;
}
// Declaring statements to make it easier to input
document.getElementById("budget").innerText = budget; document.getElementById("incomeTotal").innerText = income; document.getElementById("expenseTotal").innerText = expenses;
});
<div id="wrapper">
<div id="top">
<p id="day">Available Budget in January 2018:</p>
<p id="budget">0.00</p>
<div id="income" class="highlight">
<h1>Income</h1>
<p id="incomeTotal">+0.00</p>
</div>
<div id="expenses" class="highlight">
<h1>Expenses</h1>
<p id="expenseTotal">-0.00</p>
</div>
</div>
<div id="controls">
<select id="operation">
<option>+</option>
<option>-</option>
</select>
<input type="text" placeholder="Add description" id="description" required/>
<input type="number" min="1" placeholder="Value" id="value" />
<button id="submit">✓</button>
</div>
<div id="content">
<div id="incomeList">
<p>INCOME</p>
</div>
<div id="expenseList">
<p>EXPENSES</p>
</div>
</div>
</div>

HTML, JS - Display Loop's Output By Calling <div> From HTML To JS

I have a situation where user may insert the Total Quantity and also the Total Pass and Total Fail. I have created a function where when the number of Total Pass inserted, the loop (of entering the pass score) will run according to the iterations inputted.
However, I do not want to have the loop to display the line Enter The Score : in the JavaScript function. Therefore, I want the function to call a div from the HTML itself.
For example, I want the <div id="outputPass"><p>Enter the score : <input type="text" /></p></div> to be called in the loop function which I have created in the document.getElementById('btnPass').onclick = function().
I have inserted some comments in the code section.
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" />&nbsp<input type="button" value="Key In Score" id="btnPass" onclick="return validate();"></p><br />
<!--This Div-->
<div id="outputPass">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" />&nbsp<input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
You can make the following changes to achieve what you are looking for:
Initially we're giving an id of pscore/fscore (for pass and fail respectively) to the <p></p> tags and hiding them.
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
We're accessing them in the javascript code in the form of variables pscore and fscore respectively. (Make sure they are declared globally outside)
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
Then in the iterations we can just make a clone of the pscore/fscore , give a class of pscore/fscore to the <p></p> tags and remove the id of pscore/score (to avoid duplicate IDs), changing the display to block and append it to the output container by using the following:
var cln = pscore.cloneNode(true);
cln.style.display="block";
cln.className ="pscore";
cln.removeAttribute("id");
item.appendChild(cln);
var cln = fscore.cloneNode(true);
cln.style.display="block";
cln.removeAttribute("id");
cln.className ="fscore";
item.appendChild(cln);
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = pscore.cloneNode(true);
cln.style.display = "block";
cln.className = "pscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = fscore.cloneNode(true);
cln.style.display = "block";
cln.className = "fscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass"></p><br />
<!--This Div-->
<div id="outputPass">
<p id="pscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>

How to give jsp path to a function in javascript

I have a jsp page which is
"addSource.jsp"
present in eclipse as shown in the picture.
Now my question is i have a javascript function where i have to give "addSource.jsp" in it so that it can move to that page from the current jsp page on button click.The code is as follows
function addRow(type) {
if (type == '') {
alert("Field is empty");
}
else {
var table = document.getElementById('my_table'); //html table
var rowCount = table.rows.length; //no. of rows in table
var columnCount = table.rows[0].cells.length; //no. of columns in table
var row = table.insertRow(rowCount); //insert a row
var cell1 = row.insertCell(0); //create a new cell
var element1 = document.createElement("input"); //create a new element
element1.type = "text"; //set the element type
element1.setAttribute('id', 'source'); //set the id attribute
element1.setAttribute('name','source'+rowCount);
element1.setAttribute('value',type);
cell1.appendChild(element1);
}
}
function generate1() {
var table = document.getElementById('my_table');
var rowCount = table.rows.length;
alert(rowCount);
var f = document.form;
f.target="";
f.method="post";
f.action= 'addSource.jsp?rowCount='+rowCount;
}
<form id="form">
<input type="text" id="origin" name="element"/>
<table id="my_table">
<thead><tr>
<th>Source</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<input type="button" value="Add row" name="add" onClick="addRow(document.forms[0].element.value)" />
<input type="submit" value=" Save" />
You can use location.href Add an id to your form (for example formId) and use something like this:
<script type="text/javascript">
document.getElementById("formId").onclick = function () {
location.href = "addSource.jsp";
};
var x=1
function appendRow(type)
{
var d = document.getElementById('div');
d.innerHTML += "<input type='text' id='source' name='source' value='"+ type +"'><br >";
}
<form action="Source" method="post">
<input type="text" id="origin" name="origin"/>
<div id="div">
<button onclick ="appendRow(document.forms[0].origin.value)" value="Add Row">Add Row</button>
</div>
<input type="submit" name="Save" value=" Save" />
<hr/>
</form>
Controller
#RequestMapping(value = "/Source",params="Save", method = RequestMethod.POST)
public String source(Model model,HttpServletRequest req,HttpServletResponse res,#RequestParam("source") List<String> ola) {
System.out.println("size is:" +ola.size());
for(int i=0; i<ola.size() ;i++) {
String srh = ola.get(i);
System.out.println("srh value is:" +srh);
}
return "redirect:/createPoints";
}

Categories

Resources