How to give jsp path to a function in javascript - 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";
}

Related

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>

How to disable button if dynamic textbox are empty

I have disabled my submit button to avoid submission when textbox are not filled. I have multiple dynamic textbox where the function works correctly. But upon adding another row of textboxes, the submit button is already enabled. How can I still disable the textboxes when the user decides to add another row? I need the submit button to be enabled whenever all the textboxes are filled, after and before adding another row.
<html>
<head>
<script>
function addRow(){
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="purpose_dy[]" id="purpose" size="20" onkeyup="success()"/>';
row.insertCell(1).innerHTML = '<input type="text" name="wafernum_dy[]" id="wafernum" size="20" onkeyup="success()"/>';
row.insertCell(2).innerHTML = '<input type="text" name="cell_dy[]" id="cell" size="20" onkeyup="success()"/>';
row.insertCell(3).innerHTML = '<input type="text" name="qty_dy[]" id="qty" size="20" onkeyup="success()"/>';
row.insertCell(4).innerHTML = '<input type="text" name="remarks_dy[]" id="remarks" size="20" onkeyup="success()"/>';
row.insertCell(5).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)"/>';
}
function success() {
if(document.getElementById("uname").value==="" || document.getElementById("age").value==="" || document.getElementById("purpose").value==="" || document.getElementById("wafernum").value==="" || document.getElementById("cell").value==="" || document.getElementById("qty").value==="" || document.getElementById("remarks").value==="") {
document.getElementById('submit_form').disabled = true;
} else {
document.getElementById('submit_form').disabled = false;
document.getElementById('submit_form').style.backgroundColor="yellow";
}
}
</script>
<style>
</style></head>
<body>
Name: <input type="text" id="uname" />
Age: <input type="text" id="age" />
<input type= "button" id= "add" value="Add" onclick= "Javascript:addRow();" >
<table id= "bod">
<tr>
<th>PURPOSE</th>
<th>WAFERNUM</th>
<th>CELL</th>
<th>QTY</th>
<th>REMARKS</th>
</tr>
</table>
<input type = "submit" name = "submit" id= "submit_form" value = "Submit" onclick="SaveData()" disabled>
</body>
</html>
Alright i fixed your error , you had some issues where you were enbaling the button and disabling , its always better to itrate and check through the loop rather than going and checking if every element is empty , check the bellow answer and the fiddle . let me know if it works . The edited script part is below , replace it with yours it should work .
<script>
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="purpose_dy[]" class = "uname" id="purpose" size="20" onkeyup="success()"/>';
row.insertCell(1).innerHTML = '<input type="text" name="wafernum_dy[]" class = "wafernum" id="wafernum" size="20" onkeyup="success()"/>';
row.insertCell(2).innerHTML = '<input type="text" name="cell_dy[]" class = "cell" id="cell" size="20" onkeyup="success()"/>';
row.insertCell(3).innerHTML = '<input type="text" name="qty_dy[]" class = "qty" id="qty" size="20" onkeyup="success()"/>';
row.insertCell(4).innerHTML = '<input type="text" name="remarks_dy[]" class = "remarks" id="remarks" size="20" onkeyup="success()"/>';
row.insertCell(5).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)"/>';
}
function success() {
// get all the elements present in form
var unameArray = document.getElementsByClassName("uname");
var ageArray = document.getElementsByClassName("age");
var cellArray = document.getElementsByClassName("cell");
var qtyArray = document.getElementsByClassName("qty");
var wafernumArray = document.getElementsByClassName("wafernum");
var purposeArray = document.getElementsByClassName("purpose");
var remarksArray = document.getElementsByClassName("remarks");
// Check for number of tr
var rowCount = document.getElementById("bod").rows.length;
var bt = document.getElementById('submit_form');
var ele = document.getElementsByTagName('input');
for(var i=0;i<ele.length;i++) {
if (ele[i].type == 'text' && ele[i].value == '') {
bt.disabled = true; // Disable the button.
return false;
}
else {
bt.disabled = false; // Enable the button.
}
}
}
</script>
Modify your conditions a little bit. Now it is working as desired
<html>
<head>
<script>
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = '<input type="text" name="purpose_dy[]" class = "uname" id="purpose" size="20" onkeyup="success()"/>';
row.insertCell(1).innerHTML = '<input type="text" name="wafernum_dy[]" class = "wafernum" id="wafernum" size="20" onkeyup="success()"/>';
row.insertCell(2).innerHTML = '<input type="text" name="cell_dy[]" class = "cell" id="cell" size="20" onkeyup="success()"/>';
row.insertCell(3).innerHTML = '<input type="text" name="qty_dy[]" class = "qty" id="qty" size="20" onkeyup="success()"/>';
row.insertCell(4).innerHTML = '<input type="text" name="remarks_dy[]" class = "remarks" id="remarks" size="20" onkeyup="success()"/>';
row.insertCell(5).innerHTML = '<input type="button" value="Delete" onClick="Javacsript:deleteRow(this)"/>';
}
function success() {
// get all the elements present in form
var unameArray = document.getElementsByClassName("uname");
var ageArray = document.getElementsByClassName("age");
var cellArray = document.getElementsByClassName("cell");
var qtyArray = document.getElementsByClassName("qty");
var wafernumArray = document.getElementsByClassName("wafernum");
var purposeArray = document.getElementsByClassName("purpose");
var remarksArray = document.getElementsByClassName("remarks");
// Check for number of tr
var rowCount = document.getElementById("bod").rows.length;
for(var i=0;i<rowCount;i++) {
var uname = unameArray[i];
var age = ageArray[i];
var cell = cellArray[i];
var qty = qtyArray[i];
var wafernum = wafernumArray[i];
var purpose = purposeArray[i];
var remarks = remarksArray[i];
if (uname === "" || age === "" || cell === "" || qty === "" || wafernum === "" || purpose === "" || remarks === "") {
document.getElementById('submit_form').disabled = true;
document.getElementById('submit_form').style.backgroundColor = "initial";
break;
} else {
document.getElementById('submit_form').disabled = false;
document.getElementById('submit_form').style.backgroundColor = "yellow";
}
}
}
</script>
<style>
</style>
</head>
<body>
Name: <input type="text" id="uname" /> Age: <input type="text" id="age" />
<input type="button" id="add" value="Add" onclick="Javascript:addRow();">
<table id="bod">
<tr>
<th>PURPOSE</th>
<th>WAFERNUM</th>
<th>CELL</th>
<th>QTY</th>
<th>REMARKS</th>
</tr>
</table>
<input type="submit" name="submit" id="submit_form" value="Submit" onclick="SaveData()" disabled>
</body>
</html>

Add dynamically rows when user click on button?

Add dynamically rows when user click on button. I made a script but it does not work plz help me out
<script>
var t;
t=2;
function Insert(){
var tab=document.getElementById("mytable");
var row=insertRow(t);
var cell1=insertCell(0);
var cell2=insertCell(1);
var cell3=insertCell(2);
var cell4=insertCell(3);
t=t+1;
cell2.setAttribute('contenteditable','true');
cell3.setAttribute('contenteditable','true');
cell4.setAttribute('contenteditable','true');
}
</script>
Html
<input type="button" onclick="Insert()" name="Insert Row" value="Insert Row" />
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell3 = row.insertCell(0);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="100px" border="1">
<TR>
<TD> <INPUT type="text" /> </TD>
</TR>
</TABLE>
</BODY>
change your script like
<script>
var t;
t=2;
function Insert(){
var tab=document.getElementById("mytable");
var row=tab.insertRow(t);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
var cell4=row.insertCell(3);
t=t+1;
cell2.setAttribute('contenteditable','true');
cell3.setAttribute('contenteditable','true');
cell4.setAttribute('contenteditable','true');
}
</script>

Assign dynamic id for textbox and call it in another function

I have table with 4 td and user can add row by clicking button and inside each td I have textbox and one of them I have button which open popup window. When user click on this button the popup window will appear with checkboxes after user checked checkboxes the value of them will appear in textbox of parent page that is in same td of button clicked. My problem is when I added new row the value of checked checkboxes only appear in first textbox not in new row, for that I want to assign dynamic id for each added row and post value of checked checkboxes to it. I'm only using Javascript, PHP and html.
This is my parent.php code:
<html>
<head>
<script>
function addRow(in_tbl_name)
{
var tbody = document.getElementById(in_tbl_name).getElementsByTagName("TBODY")[0];
// create row
var rrowCount = tbody.rows.length;
var row = document.createElement("TR");
var td1 = document.createElement("TD");
var strHtml1 = "<INPUT TYPE=\"text\" SIZE=\"255\" MAXLENGTH=\"255\" class=\"textborder\">";
td1.innerHTML=strHtml1 ;
var td2 = document.createElement("TD");
var strHtml2 = "<INPUT TYPE='text' name='ch' id='ch' class=\"textbordersmall\">" +"<INPUT TYPE='text' SIZE=\"30\" MAXLENGTH=\"255\" id='clo' name='clo' class=\"textbordersmall\">";
td2.innerHTML=strHtml2;
var td3 = document.createElement("TD");
var strHtml3 ="<textarea value='' overflow-Y='auto' width='20' height='10' name='txtName' readonly='readonly'></textarea>"+"<input type='submit' value='PLO'/>";
td3.innerHTML=strHtml3 ;
var td4= document.createElement("TD");
var strHtml4 = "<INPUT TYPE=\"text\" NAME=\"in_name\" SIZE=\"5\" MAXLENGTH=\"255\" class=\"textbordersmall\">";
td4.innerHTML=strHtml4 ;
// append data to row
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
row.appendChild(td4);
// append row to table
tbody.appendChild(row);
}}
function deleterow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount==1){return false;}
if (rowCount==2&&num==1){num++;}
else{
num--;
table.deleteRow(rowCount -1);
}}
</script>
</head>
<body>
<form action="pop.php" method="POST" name="login" onsubmit="process(); return false;">
<TABLE ID="tbl" width="570" border="1" cellspacing="0" cellpadding="0" align="center" class="st">
<TH WIDTH="400">Content</TH><TH WIDTH="57">CLO</TH><TH WIDTH="57">PLO</TH> <TH WIDTH="56">Week</TH>
<p align="center">
<INPUT TYPE="Button" onClick="addRow('tbl')" VALUE="Add Row">
<INPUT TYPE="Button" onClick="deleterow('tbl')" VALUE="delete Row"> </p>
</TABLE></form>
</body>
</html>
And this my pop.php code:
<html>
<body>
<input type="checkbox" name="c[]" id="ddlNames" value="E1">E1
<br />
<input type="checkbox" name="c[]" id="ddlNames" value="E2">E2
<br />
<input type="checkbox" name="c[]" id="ddlNames" value="E3">E3
<br />
<p align="center"><input type="submit" value="Select" onclick="SetName()" /></p> </form>
<script type="text/javascript">
function SetName() {
var frm = document.forms[0];
var txt = "";
var i;
for (i = 0; i < frm.length; i++) {
if (frm[i].checked) {
txt = txt + frm[i].value + " ";
}
}
for (s=0; s<200; s++){
var txtName = window.opener.document.getElementById('txtName');
txtName.value = txt;
}
window.close();
}
</script>
<body>
</html>

Automatically calculate sum of the dynamic textbox values

I am making an php , mysql website for billing... I want to get the sum of the values in text box.. The rows can be added according to the user requirement... but .. I tried most of things.. but not getting right.... how to get the sum of all the textbox values in the last column rate... I mean without any user input such as button click..... could somebody help me with this code.....
thanks in advance..
code I made for adding rows to table..
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name="s_no[]";
element1.size="25";
element1.value = rowCount;
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name="p_id[]";
element2.size="25";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name="p_name[]";
element3.size="25";
cell3.appendChild(element3);
var cell5 = row.insertCell(3);
var element5 = document.createElement("input");
element5.type = "text";
element5.name="mrp[]";
element5.size="25";
cell5.appendChild(element5);
var cell6 = row.insertCell(4);
var element6 = document.createElement("input");
element6.type = "text";
element6.name = "qty[]";
element6.size="25";
cell6.appendChild(element6);
var cell7 = row.insertCell(5);
var element7 = document.createElement("input");
element7.type = "text";
element7.name = "rate[]";
element7.size="25";
cell7.appendChild(element7);
var cell8 = row.insertCell(6);
var element8 = document.createElement("input");
element8.type = "checkbox";
element8.name = "check";
cell8.appendChild(element8);
}
Html code for table:
<th width="17%"><label>S.No</label></th>
<th width="17%">Product Id</th>
<th width="17%">Product Name</th>
<th width="17%">MRP</th>
<th width="17%">Qty</th>
<th width="18%">Rate</th>
<th width="18%">Check</th>
</tr>
Total
HTML:
<input name="qty[]" type="text" value="0" /><br />
<input name="qty[]" type="text" value="0" /><br />
<input name="qty[]" type="text" value="0" /><br />
<input name="qty[]" type="text" value="0" /><br />
<input name="qty[]" type="text" value="0" /><br />
<input name="sum" type="text" value="0" />
Javascript:
//Get a list of input fields to sum
var elements = document.getElementsByName("qty[]");
var element_array = Array.prototype.slice.call(elements);
//Assign the keyup event handler
for(var i=0; i < element_array.length; i++){
element_array[i].addEventListener("keyup", sum_values);
}
//Function to sum the values and assign it to the last input field
function sum_values(){
var sum = 0;
for(var i=0; i < element_array.length; i++){
sum += parseInt(element_array[i].value, 10);
}
document.getElementsByName("sum")[0].value = sum;
}
Try this:
$('input[name^="rate"]').change(function() {
var sum = 0;
$('input[name^="rate"]').each(function() {
sum = sum + parseInt($(this).val()); // Or parseFloat if you are going to allow floating point numbers.
});
console.log(sum);
//$('#total_input').val(sum); //Your input to show the total
//$('#total_input').html(sum); //If is div, paragraph or another type of container.
});
Is important to make sure the inputs only allow numbers.
HTML
<?php
for($i=1;$1<=5;$i++)
{
?>
<input type="text" id="rate<?php echo $i; ?>" class="rate" name="rate<?php echo $i; ?>">
<?php
}
?><input type="text" name="sum" name"sum">
jQuery
<script type="text/javascript">
$(document).ready(function()
{
for($j=1;$j<=5;$j++)
{
$('#rate'+$j).val('0');
}
});
$sum=0;
$(".rate').keyup(function(){
for($j=1;$j<=5;$j++)
{
$sum=$sum+$('#rate'+$j).val();
alert($sum);
}
$(".sum").html('$sum');
});
</script>
You can iterate on all input elemements using $.each() and get their values.
JavaScript
$(function(){
var inputs = $("input");
inputs.blur(function(){
var total = 0;
$.each(inputs, function(input){
var num = parseInt(inputs[input].value);
total += (!isNaN(num))? num : 0;
});
$("#total").html(total)
HTML
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<p>
Total : <span id="total"></span>
</p>
Working Example http://jsfiddle.net/w0029xuz/

Categories

Resources