Add dynamically rows when user click on button? - javascript

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>

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>

object HTMLInputElement appears instead of checkbox

I'm trying to have a checkbox appear in the Collected column after pressing the Add Item button however, [object HTMLInputElement] appears instead. I've tried appendChild, insertBefore and removing innerHTML but obviously that's made things worse. I've tried searching on Google and Stackoverflow for similar questions for relevant answers but no one's had a similar situation to me.
function addItem() {
var a = String(document.getElementById("it").value);
var b = parseFloat(document.getElementById("iq").value);
if (a.length === 0 || isNaN(b)) {
window.alert("Required field empty, please enter values in both boxes.");
} else {
var table = document.getElementById("list");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cb = document.createElement("INPUT");
cb.setAttribute("type", "checkbox");
cell1.innerHTML = a;
cell2.innerHTML = b;
cell3.innerHTML = cb;
}
}
<table id="list" align="center">
<tr>
<td colspan="3">
<input id="it" name="item" type="text" placeholder="Item" />
<input id="iq" name="quantity" type="text" placeholder="No." />
<br />
<input value="Add Item" type="submit" onclick="addItem()" />
<hr />
</td>
</tr>
<tr>
<td><span>Item</span></td>
<td><span>Quantity</span></td>
<td><span>Collected</span></td>
</tr>
</table>
You need to use appendChild and not overwrite the innerHTML of the cell. You are adding a new element to the DOM. This can be done by writing the HTML into the cell, but you have created the element so just append it..
function addItem() {
var a = String(document.getElementById("it").value);
var b = parseFloat(document.getElementById("iq").value);
if (a.length === 0 || isNaN(b)) {
window.alert("Required field empty, please enter values in both boxes.");
} else {
var table = document.getElementById("list");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cb = document.createElement("INPUT");
cb.setAttribute("type", "checkbox");
cell1.innerHTML = a;
cell2.innerHTML = b;
cell3.appendChild(cb);
}
}
<table id="list" align="center">
<tr>
<td colspan="3">
<input id="it" name="item" type="text" placeholder="Item" />
<input id="iq" name="quantity" type="text" placeholder="No." />
<br />
<input value="Add Item" type="submit" onclick="addItem()" />
<hr />
</td>
</tr>
<tr>
<td><span>Item</span></td>
<td><span>Quantity</span></td>
<td><span>Collected</span></td>
</tr>
</table>

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";
}

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