Clone a table row and remove values in JavaScript - javascript

I have a set of text inputs fields which I want to be cloned when the user clicks the "add" button. My problem is that the fields are being cloned with the input from the user. Using Javascript, how do I reset the value of the text input fields so they may be cloned without cloning the user input text.
This is my code...
<table width="766" border="0" cellspacing="0" cellpadding="0" id="albumTable">
<tr id="clone">
<td width="230"><input type="text" name="dj_1" /></td>
<td width="230"><input type="text" name="affiliations_1" /></td>
<td width="230"><input type="text" name="rating_1" /></td>
<td width="230"><input type="text" name="comments_1" /><input type="hidden" name="count" value="1" class="count"/></td>
<td width="286" style="position:absolute; top:110px; left: 670px;"><input name="button" type="button" id="Add" value="ADD ROW" onclick="addRow(this.parentNode.parentNode)"></td>
</tr>
</table>
<script type="text/javascript">
function addRow(r){
var root = r.parentNode;
var allRows = root.getElementsByTagName('tr');
var cRow = allRows[0].cloneNode(true)
var cInp = cRow.getElementsByTagName('input');
var countRow = cRow.getElementsByClassName('count');
for(var i=0;i<cInp.length;i++){
cInp[i].setAttribute('name',cInp[i].getAttribute('name').replace(/\d/g,(allRows.length+1)))
}
for(var j=0;j<countRow.length;j++){
countRow[j].setAttribute('value',countRow[j].getAttribute('value').replace(/\d/g,(allRows.length+1)))
}
root.appendChild(cRow);
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>

Something like this:
var cln = document.getElementByID("clone");
var clns = cln.getElementsByTagName("td");
for(var i = 0; i <clns.length; i++)
{
clns[i].innerHTML = "";
}

In the first for loop, just add this:
cInp[i].value='';

Related

I have a table in jsp which have 5 rows and 3 colums and i wanted to print it in servlet how can i do this?

<script>
function addRow() {
var medicinename = document.getElementById("medicinename");
var time = document.getElementById("time");
var duration = document.getElementById("duration");
var when = document.getElementById("when");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= medicinename.value;
row.insertCell(2).innerHTML= time.value;
row.insertCell(3).innerHTML= duration.value;
row.insertCell(4).innerHTML= when.value;
document.getElementById('medicinename').value='';
document.getElementById('time').value='';
document.getElementById('duration').value='';
document.getElementById('when').value='';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<3; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<4; j++){
var td = document.createElement('TD');
td.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
</script>
<table>
<tr>
<td>Medicine Name:</td>
<td><input type="text" id="medicinename"></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" id="time">
</tr>
<tr>
<td>Duration:</td>
<td><input type="text" id="duration">
</tr>
<tr>
<td>When?</td>
<td><input type="text" id="when">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<div id="mydata">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Medicine Name</b></td>
<td><b>Medicine Time&nbsp</b></td>
<td><b>Medicine Duration</b></td>
<td><b>Medicine When?</b></td>
</tr>
</table>
here is JAVASCRIPT through which i add element in JSP table
here is my 4 field and table which display data inside JSP
hello = request.getParameter("");//what should i take here
System.out.println(hello);
You need to collect your table data in JavaScript by the use a form or Ajax to send this data to your servlet. You can't get the table data from request parameters in servlet unless you send it.
An example of form
<form action="login" method="post">
<input type="text" name="uname" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit" class="button" >Login</button>
</form>
This form pass uname and password to login Servlet.
You can pass each data in table like this way...!
In servlet side you can use this code for fetch data
String uname = request.getParameter("uname");
String password = request.getParameter("password");
just try out..!
Since, you were using jQuery and Servlet but you edited your question and removed the code. But here is some code example using jQuery.
Sample Table :
<table id='table_id'>
<th>Column1</th><th>Column2</th>
<tr>
<td>1</td><td>2</td>
</tr>
<tr>
<td>3</td><td>4</td>
</tr>
</table>
First you need to iterate through your table in javascript, create a JSON object with table data. Probably like this (see the table structure given here)
<script type="text/javascript" >
function collectData(){
var tableData = [];
$('#table_id tr').each(function(){
var $this = $(this);
var tds = $this.find('td');
var i = 0;
//if we have data in that row
if(tds.length){
var rowData = {
column1:tds[0].innerHTML,
column2:tds[1].innerHTML,
}
tableData.push(rowData);
}
});
console.log(tableData);
// Send it via AJAX
$.ajax({
url: '/yourServletName', // Change name to your servlet
type: 'POST',
dataType: 'json',
data: {objarray: JSON.stringify(tableData)},
success: function(result) {
alert('SUCCESS');
}
});
}
JSON will be like :
{
[{'column1':1,'column2':2}, {'column1':3,'column2':4}]
}
Now in your servlet code access this data using
String tableArray = request.getParameter("objarray").
But you need to convert the JSON to Java Pojo Object. Create a class similar to your table and parse the JSON using any library like jackson or gson
public class TableData{
private String column1;
private String column2;
public String getColumn1(){
return column1;
}
public void setColumn1(String column1){
this.column1 = column1;
}
public String getColumn2(){
return column2;
}
public void setColumn2(String column2){
this.column2 = column2;
}
}
GSON tutorial is given here
As explained in another answer, either use input elements in form or use JSON object as given in another answer here.
Form input method
HTML or JSP
<table>
<tr>
<td>Medicine Name:</td>
<td><input type="text" id="medicinename"></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" id="time">
</tr>
<tr>
<td>Duration:</td>
<td><input type="text" id="duration">
</tr>
<tr>
<td>When?</td>
<td><input type="text" id="when">
<input type="button" id="add" value="Add" onclick="Javascript:addRow()"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
<div id="mydata">
<form action="yourServletName" method="post">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Medicine Name</b></td>
<td><b>Medicine Time&nbsp</b></td>
<td><b>Medicine Duration</b></td>
<td><b>Medicine When?</b></td>
</tr>
</table>
<button type="submit" class="button" >Submit</button>
<!-- Update the rowCount on Submitting the button -->
<input type="hidden" id="rowCount" value="" />
</form>
</div>
JS File to add input in table, you can :
function addRow() {
var medicinename = document.getElementById("medicinename");
var time = document.getElementById("time");
var duration = document.getElementById("duration");
var when = document.getElementById("when");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= '<input type="text" name="'+'rowMedicine'+rowCount+'" value="'+medicinename.value+'" readonly />';
row.insertCell(2).innerHTML= '<input type="text" name="'+'rowTime'+rowCount+'" value="'+time.value+'" readonly />';
row.insertCell(3).innerHTML= '<input type="text" name="'+'rowDuration'+rowCount+'" value="'+duration.value+'" readonly />';
row.insertCell(4).innerHTML= '<input type="text" name="'+'rowWhen'+rowCount+'" value="'+when.value+'" readonly />';
document.getElementById('medicinename').value='';
document.getElementById('time').value='';
document.getElementById('duration').value='';
document.getElementById('when').value='';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<3; i++){
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<4; j++){
var td = document.createElement('TD');
td.width='75';
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
In your servlet, use the request.getParameter to access values.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Now, you can get the parameter from input elements using name
String rowMedicine = request.getParameter("rowMedicine1");
//Similarly get the values of all parameters using names
//get the row count
//iterate through it and save it in your database
}

Issue replacing input value in array

I did an example about replacing the input value when the row is deleted but is not working (this is not a static example).
<script src="./edit_files/prototype.js" type="text/javascript"></script>
<script src="./edit_files/application.js" type="text/javascript"></script>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="cristianoronaldo#realmadrid.com"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
<div class="contact">
<table border="0">
<tr>
<td><select class="position_id" id="obj_client_contact_attributes__position_id" name="obj_client[contact_attributes][][position_id]"><option value="1" selected="selected">INTELIGENT</option><option value="2">OTHER</option></select></td>
<td><input class="should_change_value" id="obj_client_contact_attributes__phone_mail" name="obj_client[contact_attributes][][phone_mail]" type="text" value="ONLY THE INPUT WILL BE test#hotmail.com IF I CLICK ON DELETE"/></td>
<td>
DELETE
<input id="obj_client_contact_attributes__id" name="obj_client[contact_attributes][][id]" type="hidden" value="16594"/>
<input class="should_destroy" id="obj_client_contact_attributes__should_destroy" name="obj_client[contact_attributes][][should_destroy]" type="hidden"/>
</td>
</tr>
</table>
</div>
Here is the application.js file:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
I tried this code but only works if I remove the first row.
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
$('should_change_value').update("test#hotmail.com");
if (should_destroy) {
$(element).next('.should_destroy').value = 1;
}
$(element).up('.contact').hide();
}
Here is the live example in jsfiddle
Here is the example download on Github but is not replacing the input value correctly
Ok I got it, you want to change the input value when the row is deleted, so do this:
function mark_for_destroy_contact(element,should_destroy,should_change_value) {
var element_text = $(element).up('.contact').down('.position_id',0);
element_text.className = 'position_id';
element_text.value = '';
var element_text2 = $(element).up('.contact').down('.should_change_value',0);
element_text2.className = 'should_change_value';
element_text2.value = 'test#hotmail.com';
if (should_destroy) { $(element).next('.should_destroy').value = 1;}
$(element).up('.contact').hide();
}

How to get values of dynamically created input fields (Json)

input fields are created via jquery depend on user input
If user type Quantity : 5 then i m created 5 input fields
for example if user give Quantity = 3 then this is how the html created dynamically using Jquery
<tr id = "tr_1">
<td><input type="text" name="cont_no1" id="cont_no1" /><td>
<td><input type="text" name="cont_size1" id="cont_size1" /><td>
<td><input type="text" name="cont_type1" id="cont_type1" /><td>
</tr>
<tr id = "tr_2">
<td><input type="text" name="cont_no2" id="cont_no1" /><td>
<td><input type="text" name="cont_size2" id="cont_size2" /><td>
<td><input type="text" name="cont_type2" id="cont_type2" /><td>
</tr>
<tr id = "tr_3">
<td><input type="text" name="cont_no3" id="cont_no3" /><td>
<td><input type="text" name="cont_size3" id="cont_size3" /><td>
<td><input type="text" name="cont_type3" id="cont_type3" /><td>
</tr>
now i need to store all this input fields values in json.
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
i tried like this but its not working the please someone help me. ThankYou
for your refrence here is full code, var auto_tr value is aligned here(with enter) for your purpose .
$(document).ready(function(){
$( "#cont_qty" ).change(function()
{
var itemCount = 0;
$("#munna").empty();
var cont_qty = this.value;
for(var i=0 ; cont_qty>i; i++)
{
itemCount++;
// dynamically create rows in the table
var auto_tr = '<tr id="tr'+itemCount+'">
<td>
<input class="input-medium" type="text" id="cont_no'+itemCount+'" name="cont_no'+itemCount+'" value="">
</td>
<td>
<select class="input-mini" name="cont_size'+itemCount+'" id="cont_size'+itemCount+'">
<option>20</option>
<option>40</option>
<option>45</option>
</select>
</td>
<td>
<select class="input-mini" name="cont_type'+itemCount+'" id="cont_type'+itemCount+'">
<option>DV</option>
<option>HD</option>
<option>HC</option>
<option>OT</option>
<option>FR</option>
<option>HT</option>
<option>RF</option>
</select>
</td>
<td>
<select class="input-medium" name="cont_tonnage'+itemCount+'" id="cont_tonnage'+itemCount+'">
<option>24000 Kgs</option>
<option>27000 Kgs</option>
<option>30480 Kgs</option>
<option>Super Heavy Duty</option>
</select>
</td>
<td>
<input class="input-medium" type="text" id="cont_tare'+itemCount+'" name="cont_tare'+itemCount+'" value="">
</td>
<td>
<input class="input-medium" name="cont_netweight'+itemCount+'" id="cont_netweight'+itemCount+'" type="text" value="">
</td>
<td>
<input class="input-mini" name="yom'+itemCount+'" id="yom'+itemCount+'" type="text" value=""></td>
<td>
<select class="input-medium" name="cont_condition'+itemCount+'" id="cont_condition'+itemCount+'">
<option>IICL</option>
<option>ASIS</option>
<option>CARGO WORTHY</option>
</select>
</td>
</tr>';
$("#munna").append(auto_tr);
}
});
$("#getButtonValue").click(function ()
{
var jsonObj= jsonObj || [];
for(var i=1; i<cont_qty.value; i++)
{
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
alert(jsonObj[0].cont_no[1]);
});
});
did small loop mistake :)
for(var i=1; i<=cont_qty.value; i++)
{
alert(cont_qty.value);
item = {};
item ["cont_no"] = $('#cont_no'+i).val();
item ["cont_size"] = $('#cont_size'+i).val();
item ["cont_type"] = $('#cont_type'+i).val();
jsonObj.push(item);
}
in previous one i<cont_qty.value this one used now just changed as i<=cont_qty.value
so the loop ran 3 times when qty is 4. now just added <=
ThankYou for your answers friends
Make sure you call your function after you created the html via jquery.
createHtml(); // function to create the html
storeValuesToArray(); // Your function to store data to array
Also make sure you properly close your tags <tr></tr>. And put <tr> inside a <table> tag.
And make sure your cont_qty is set to a value
After you created the html and added all the fields necessary, you can catch all elements by using a selector like:
var jsonObj= jsonObj || [];
$('[name^="cont_no"]').each(function(){
var i = this.name.split('cont_no')[1];
var item = {};
item['cont_no'] = $(this).val();
item['cont_size'] = $('[name="cont_size'+i+'"]').val();
item['cont_type'] = $('[name="cont_type'+i+'"]').val();
jsonObj.push(item);
});

Search table contents using javascript

I am currently working on javascript. In this code I have a table and a textbox. When I enter data in the textbox it should show the particular value that I typed but it doesn't search any data from the table. How do I search data in the table?
Here's a jsfiddle http://jsfiddle.net/SuRWn/
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th> </th>
<th> </th>
<th><center> <b>COURSE CODE</b></center></th>
<th><center>COURSE NAME</center></th>
</tr>
</thead>
<tbody>
<tr id="rowUpdate" class="TableHeaderFooter">
<td >
<center> <input type="text" name="input" value="course" ></center>
<center> <input type="text" name="input" value="course1" ></center>
<center> <input type="text" name="input" value="course2" ></center>
</td>
<td>
<center> <input type="text" name="input" value="subject" ></center>
<center> <input type="text" name="input" value="subject1" ></center>
<center> <input type="text" name="input" value="subject2" ></center>
</td>
</tr>
</tbody>
</table >
<form action="#" method="get" onSubmit="return false;">
<label for="q">Search Here:</label><input type="text" size="30" name="q" id="q" value="" onKeyUp="doSearch();" />
</form>
Javascript:
<script type="text/javascript">
//<!--
function doSearch() {
var q = document.getElementById("q");
var v = q.value.toLowerCase();
var rows = document.getElementsByTagName("tr");
var on = 0;
for ( var i = 0; i < rows.length; i++ ) {
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
if ( fullname ) {
if ( v.length == 0 || (v.length < 3 && fullname.indexOf(v) == 0) || (v.length >= 3 && fullname.indexOf(v) > -1 ) ) {
rows[i].style.display = "";
on++;
} else {
rows[i].style.display = "none";
}
}
}
}
//-->
</script>
checking with chrome console, it seems that innerHtml for the 'fullname' is returning an error:
var fullname = rows[i].getElementsByTagName("td");
fullname = fullname[0].innerHTML.toLowerCase();
That's because the first tr tag you have is in the thead and it doesn't have any td at all. Changing the start of your loop to 1 will fix that:
for ( var i = 1; i < rows.length; i++ ) { //... and so on
yuvi is correct in his answer. I've incorporated this in a fiddle - http://jsfiddle.net/dBs7d/8/ - that also contains the following changes:
Inputs with course and subject grouped into individual rows.
td tags align underneath th tags.
Code refactored to improve readability.
Instead of checking the html of the td tags I've changed it to check the value attribute of the input tags. This means you can change the value of the input and still search.
I also changed the style alteration to use backgroundColor. This can easily be reverted to display.
See this link.
HTML:
<table name="tablecheck" class="Data" id="results" >
<thead>
<tr>
<th>Course</th>
<th>Subject</th>
<th>COURSE CODE</th>
<th>COURSE NAME</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" value="course" /></td>
<td><input type="text" value="subject" /></td>
</tr>
<tr>
<td><input type="text" value="course1" /></td>
<td><input type="text" value="subject1" /></td>
</tr>
<tr>
<td><input type="text" value="course2" /></td>
<td><input type="text" value="subject2" /></td>
</tr>
</tbody>
</table>
Search here (with jQuery):<input type="text" size="30" value="" onKeyUp="doSearchJQ(this);" /><br />
Search here:<input type="text" size="30" value="" onKeyUp="doSearch(this);" />
Javascript:
function doSearchJQ(input) {
var value = $(input).val();
if (value.length > 0) {
$("#results tbody tr").css("display", "none");
$('#results input[value^="' + value + '"]').parent().parent().css("display", "table-row");
} else {
$("#results tbody tr").css("display", "table-row");
}
}
function doSearch(input){
var value = input.value;
var table = document.getElementById('results');
var tbody = table.querySelector("tbody");
var rows = tbody.querySelectorAll("tr");
var visible, row, tds, j, td, input;
for (var i = 0; i < rows.length; i++) {
visible = false;
row = rows[i];
tds = row.querySelectorAll("td");
for (j = 0; j < tds.length; j++) {
td = tds[j];
input = td.querySelector("input");
console.log(input.value.indexOf(value));
if (input.value.indexOf(value) > -1) {
visible = true;
break;
}
}
if (visible) {
row.style.display = "table-row";
} else {
row.style.display = "none";
}
}
}
With jquery it's more compact function. But you can use clear javascript doSearch.
Why don't you use JQuery DataTables? The plugin has a really nice table view as well as automatically enabled search textbox, and should fit in easily with your JavaScript/PHP solution.
See example table below:
The plugin is well-documented, and widely used. It should be very easy to drop in into an existing application, and style it accordingly.
Hope this helps!

add image input with jquery with limit to four

I have this code that a user can upload pictures. It works just fine, but the user can submit unlimited pictures, and I want to put a limit to four.
when the user reaches four input fields then they won't be allowed to add any input.
<script type="text/javascript">
function addItems()
{
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2)
table1.deleteRow(lastRow-1);
}
</script>
<form method="post" action="" enctype="multipart/form-data">
<table align="center" border="0" id="tab1">
<tr>
<td width="218" align="center">
<input type="file" name="image[]" /></td>
<td width="54" align="center">
<img src="Button-Add-icon.png" alt="Add" style="cursor:pointer"
onclick="addItems()" /></td>
<td>
<img src="Button-Delete-icon.png" alt="Remove" style="cursor:pointer"
onclick="remItems()" /></td>
</tr>
</table>
<table align="center" border="0" id="tab2">
<tr><td align="center">
<input type="submit" value="Upload" name="upload" /></td></tr>
</table>
</form>
Thanks
Add a global counter.. and check on your addItems function.. something like:
var totalItems = 0;
function addItems()
{
if(totalItems < 4) {
var table1 = document.getElementById('tab1');
var newrow = document.createElement("tr");
var newcol = document.createElement("td");
var input = document.createElement("input");
input.type="file";
input.name="image[]";
newcol.appendChild(input);
newrow.appendChild(newcol);
table1.appendChild(newrow);
totalItems++; //increment the global counter...
} else {
//Display your message here.. with an alert or something...
}
}
function remItems()
{
var table1 = document.getElementById('tab1');
var lastRow = table1.rows.length;
if(lastRow>=2) {
table1.deleteRow(lastRow-1);
totalItems--;
}
}

Categories

Resources