How to add to arraylist in javascript - javascript

I am using javascript for my server side validation.I need to add all data from a table which is dynamically generated while clicking an add button.
Clicking ADD button section is working fine.Also i added date picker to 2nd and 3rd columns.its working fine.The code is given below.....
function addRow(tableId) { //Add new row to given table having id tableId
var table = document.getElementById(tableId);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = '<input type="text" id="code'+ rowCount +'" name="code" maxlength="16"/>';
cell2.innerHTML = '<input type="text" id="datepicker2'+ rowCount +'" class="datepicker" name="validFrom" maxlength="50" >';
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
cell3.innerHTML = '<input type="text" id="datepicker3'+ rowCount +'" class="datepicker" name="validFrom" maxlength="50" >';
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
cell4.innerHTML = '<input type="button" id="del'+ rowCount +'" name="del" />';
Html code
<div class="systemsettings">
<h3><spring:message code="systemSetting.ratePeriods.label"/></h3>
</div>
<div class="systemset" >
<!-- table table-hover table-striped table-bordered table-highlight-head-->
<table id="systemsettingstid" class="table-bordered table-striped">
<thead class="tax_thead" id="tdDetailList">
<tr >
<!-- <th>Applicable From</th> -->
<th width="200" id="code" title="Code" >Code</th>
<th width="200" id="from" title="from ">from</th>
<th width="200" id="to" title="to">to</th>
<th width="50" id="del" title="del">del</th>
<!-- <th width="45" ><div class="add_new">
</div></th> -->
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div>
<tr>
<button type="button" onClick="javascript:addRow('systemsettingstid');">Add</button>
</tr>
</div>
DELETE BUTTON:
I have a delete button also appended inside the html code.
While clicking it the corresponding row should be deleted(fixed automatically while clicking add button on every row).
MY PROBLEM:
Adding and delete does not affect back end it just need to alter in an arraylist.
During final form submission the arraylist needs to go to backend(built in spring mvc).
1) Can we create an arraylist in javascript?
2) If we can how to add the text boxes and date picker details into arraylist?.
4) How to pass that arraylist in to my spring mvc controller?
NB:I am new to javascript.Any help will be highly appreciable.

<script>
var tdDetailList = [];
function init() {
var tdDetailTable = document.getElementById("tdDetailTable");
for (var i = 0, row; row = tdDetailTable.rows[i]; i++) {
var tdDetail = {code : row.cells[0].innerHTML, datepicker2 : row.cells[1].innerHTML, datepicker3 : row.cells[2].innerHTML};
tdDetailList.push(tdDetail);
}
alert(getDetailTableJson());
}
function deleteRow(index){
tdDetailList.splice(index, 1);
var tdDetailTable = document.getElementById("tdDetailTable");
tdDetailTable.deleteRow(index);
alert(getDetailTableJson());
}
function getDetailTableJson(){
return JSON.stringify(tdDetailList);
}
</script>
<body onload="init();">
<table id="tdDetailTable">
<tr><td>1</td><td>2</td><td>3</td><td>del</td></tr>
<tr><td>4</td><td>5</td><td>6</td><td>del</td></tr>
</table>
</body>
Can we create an arraylist in javascript?
Yes. In my example var tdDetailList = []; is array (list).
You can add elements to it:
tdDetailList.push(tdDetail);
and remove element in index: tdDetailList.splice(index, 1);
If we can how to add the text boxes and date picker details into arraylist?.
You can create object like:
var tdDetail = {code : row.cells[0].innerHTML, datepicker2 : row.cells[1].innerHTML, datepicker3 : row.cells[2].innerHTML};
with fields of your table and add the object to your list.
How to pass that arraylist in to my spring mvc controller?
Convert the list to json
JSON.stringify(tdDetailList);
In my example: "[{"code":"1","datepicker2":"2","datepicker3":"3"},{"code":"4","datepicker2":"5","datepicker3":"6"}]"
and send.

If you want to add and delete using JAVA SCRIPT then it will very complex and lengthy.
But using JQUERY it will work fine and easily you can handle ADD, DELETE actions also
use JQUERY and in this append and remove methods are there you can use it and insert a row in table and delete a row in table
May be you new in jQUERY but once you get it, its amazing than JAVA SCRIPT
Hope you getting let me know if you have any confusion. ['}

Related

Creating a timetable using JavaScript

I am trying to create a web page where user can create his own schedule. User can enter the values of lines and columns in some input to build a table in which the user will write his schedule. I use this javascript code:
var p = document.getElementById('paragraph');
var table = document.createElement('table');
var tbody = document.createElement('tbody');
table.appendChild(tbody);
for (let i = 0; i < lines; i++){
let tr = document.createElement('tr');
for (let j = 0; j < columns; j++){
let td = document.createElement('td');
}
tbody.appendChild(tr);
}
p.appendChild(table);
However, when I'am trying to add information to table cells, I can't write values to each of them. I've used .innerHTML but it doesn't work the way it needs to. The information will be written only to the beginning of the table.
Should I give id to each td and then address to them by id when I need to write the information? Or there is another way to write values to table cells?
I think you need something like this to insert the data.
We have insertRow(), which is pre-defined function which i used in this answer to insert new row and then inserted columns in it with insertCell function.
<!DOCTYPE html>
<html>
<body>
<div class="inputs">
<input type="text" id="input1" placeholder="Enter first col data" >
<input type="text" id="input2" placeholder="Enter second col data" >
</div>
<br> <br> <br>
<table id="myTable">
<thead style="background-color: beige;">
<tr>
<td>default head row cell 1</td>
<td>default head row cell 2</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button type="button" onclick="myFunction()">add data to body row</button>
<script>
function myFunction() {
var table = document.querySelector("#myTable tbody");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
const val1 = document.getElementById('input1').value;
const val2 = document.getElementById('input2').value;
cell1.innerHTML = val1;
cell2.innerHTML = val2;
}
</script>
</body>
</html>
I think that you need to refer to your button in the js file and write a function that will be executed on the "onclick" event
In this function, you are accessing the table variable. By using the built in javaScript function «insertRow()» you are adding rows to your table. Then you should add cells to this row in which information that users entered will be stored. This you can also do by using build in function «insertCell()»
Next, you access the fields in which the user has entered data
Retrieve values ​​using the «value» built-in function
Using the built-in «innerHTML» function, draw cells with the information that you received in the previous step
You can look at the written code below for better assimilation of information
<!DOCTYPE html>
<html>
<body>
<div class="inputs" >
<input type="text" id="firstColumn" placeholder="Enter data here" >
<input type="text" id="SecondColumn" placeholder="Enter data here" >
</div>
<table id="Table">
<thead>
<tr>
<td style="background-color: pink;">Name of first column</td>
<hr>
<td style="background-color: purple;">Name of second column</td>
</tr>
</thead>
<tbody></tbody>
</table>
<br>
<button style="background-color: yellow;" type="button" id = "btn">Add</button>
<script>
const button = document.querySelector('#btn');
btn.onclick = function() {
var table = document.querySelector("#Table tbody");
var row = table.insertRow();
var Fcell = row.insertCell(0);
var Scell = row.insertCell(1);
const Fdata = document.getElementById('firstColumn').value;
const Sdata = document.getElementById('SecondColumn').value;
Fcell.innerHTML = Fdata;
Scell.innerHTML = Sdata;
}
</script>
</body>
</html>

delete function delets the last record from table. js jquery.updated

I have a dynamic table which gets values from db. I have a button which onclcik runs the query to delete the record from database. Currently instead of deleteing record(which was clicked ) its deleting the last record available. I am updating from here I figure out the issue when I provide ID to the post somehow the LAST ID is being sent to the query, is there anyway I can delete the ID which was selected.please look at the code for more info
//this is how im creating dynamic table
//just for the test
function() {
});
});
<table>
<thead>
<tr>
<td>
</td>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
<button type="button" id="chochk" style="display:none" class="sukuti">delete</button>
.
Perhaps you may be better listening directly on the change event of the checkbox and then get the value of the event.target afterwards? There is something wrong with the way you are getting the variable ad in your code i suspect, but without seeing how that is derived it's hard to see why.
The example below shows a simple way to get the value of a checkbox, hopefully this might lead you to the correct answer.
$('.test').on('change', function(e) {
alert(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Value of 1: <input type="checkbox" class="test" value="1" /><br />
Value of 2: <input type="checkbox" class="test" value="2" />
Instead of a checkbox, use a radio button, so the user can only select one at a time. Then in the handler for the delete button, get the value of the checked button and send that to the server.
//this is how im creating dynamic table
//just for the test
function() {
var table = document.getElementById('tablebody');
for (var i = 0; i < (test.length); i = i + 2) { //test is an array of values from db
var row = table.insertRow(-1);
var cell3 = row.insertCell(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
cell1.innerHTML = //some html span
cell2.innerHTML = //some html span
//this is the checkbox which onclick shows the button
cell3.innerHTML = '<input type="radio" name="checkbox" class="your" value="ID of current row">';
}
///this is how i am displaying a button on click and also delete function
$(document).on('click', ".your", function() {
$('#chochk').show();
});
$(".sukuti").click(function() {
var ad = $(".your:checked").val();
$.post("test.jsp", {
id: ad //ad is the ID which will delete the specifIC ID being clicked
}, function(data) { //sending a query to delete from db working good
});
});
<table>
<thead>
<tr>
<td>
</td>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
<button type="button" id="chochk" style="display:none" class="sukuti">delete</button>

Update a HTML table record via jQuery

I have created a form with only three inputs, a HTML table and a submit button
<div class="form-group">
<input type="text" id="inputText1" required>
<input type="text" id="inputText2" required>
<input type="text" id="inputText3" required>
</div>
<button type="button" class="btn btn-default" id="submit">Submit</button>
</form>
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed" id="myTable" style="width:90%; margin:0 auto;">
<thead>
<tr>
<th>ID</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
that works this way:
every time the user clicks the submit button the HTML table adds to its rows the value of the inputs via jQuery + two linkbuttons and the variable cont specified as a number in a hidden element in order to easily locate the row when it comes to update it.
$(document).ready(function () {
var cont=0;
$("#submit").click(function(e) {
e.preventDefault();
cont++;
var id = $("#inputText1").val().toLowerCase();
var lastname = $("#inputText2").val();
var name = $("#inputText3").val();
if (checkId(lastname)) {
return alert('El ID ya ha sido especificado');
}
$('#myTable tbody').append('<tr><td for="id">' + id + '</td><td for="lastname">' + lastname + '</td><td>' + name + '</td><td id="cont" style="visibility:hidden">' + cont + '</td><td>Modificar Eliminar</td></tr>');
$("#inputText1").val('');
$("#inputText2").val('');
$("#inputText3").val('');
$('#inputText1').focus();
});
});
the submit button works OK the problem is when I want to modify a row, what I do now is to populate the inputs with the values of the row selected in order to let the user to modify its content but I cannot retrieve the value of the variable cont that represents an specific and different number for each row and besides of that I don't know how to update the table's row once the user decide to update the record, could you please help me, this is the jQuery code I had for the moment
$(document).ready(function () {
$("#myTable").on('click', '#select', function (e) {
e.preventDefault();
var currentRow = $(this).closest("tr");
//var contador= currentRow.$("#cont").val();
//alert(contador);
//doesn't retrieve neither show anything
var col1 = currentRow.find("td:eq(0)").text();
var col2 = currentRow.find("td:eq(1)").text();
var col3 = currentRow.find("td:eq(2)").text();
$("#inputText1").val(col1);
$("#inputText2").val(col2);
$("#inputText3").val(col3);
});
});
and also would like to dd that when the user add the info from the inputs to the table, theres a gap where the hidden field is
how could I solve this?

escape parameters on onclick event doesnt work

I'm atm working on getting a dynamic table into an html page with a button on every table row's first column to display a description of an item(it's an itemlist).
however when setting the innerhtml with an onclick event i am not able to fire an alert .When i want to call another JS function to call the alert and trying to pass an argument in my onclick function it wont do nothing, when trying to escape the quotes nothing works.
Javascript
function showAuctionList(auctionList){
var table = document.getElementById("myTableData");
for(var i = 0 ; i< auctionList.length ; i++){
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var description = auctionList[i].itemDesc;
row.insertCell(0).innerHTML= '<input type="button" value = "Show Description" onclick="showDescription( description)">';
row.insertCell(1).innerHTML= auctionList[i].auctionId;
row.insertCell(2).innerHTML= auctionList[i].sellId;
row.insertCell(3).innerHTML= auctionList[i].startDate;
row.insertCell(4).innerHTML= auctionList[i].endDate;
row.insertCell(5).innerHTML= auctionList[i].buyNow;
row.insertCell(6).innerHTML= auctionList[i].minBid;
row.insertCell(7).innerHTML= auctionList[i].actualBid;
row.insertCell(8).innerHTML= auctionList[i].itemCat;
row.insertCell(9).innerHTML= auctionList[i].itemName;
row.insertCell(10).innerHTML= auctionList[i].itemDesc;
}
}
function showDescription(desc){
alert(desc);
}
HTML
<div id="search" style="display:none">
<button id="searchButton" onclick="
google.script.run.withSuccessHandler(showAuctionList).getAuctionList()"> Search </button> <br>
<div id="mydata">
<table id="myTableData" border="1" cellpadding="2">
<tr>
<td> </td>
<td><b>Auction ID</b></td>
<td><b>Seller ID</b></td>
<td><b>Start Date</b></td>
<td><b>End Date</b></td>
<td><b>Buy now option</b></td>
<td><b>Min Bid</b></td>
<td><b>Actual Bid</b></td>
<td><b>Category</b></td>
<td><b>Item Name</b></td>
<td><b>Description</b></td>
</tr>
</table>
<br/>
</div>
gs function call:
function doget(e){
...
return HtmlService.createTemplateFromFile('Main').evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
can this be escaped that description works as an parameter or whats the workaround about the issue?The rest works perfectly fine though
Try this. As description seems to be a string value you need to surround it with qoutes.
row.insertCell(0).innerHTML = '<input type="button" value = "ShowDescription" onclick="showDescription(\'' + description + '\');">';
You need not escape if use this code:
row.insertCell(0).innerHTML= '<input type="button" value = "Show
Description" onclick="showDescription(this.getAttribute(\'description\'))">';
row.cells[0].firstChild.setAttribute('description', description);

Create div within a cell in Javascript

I am having troubles creating a div after creating a cell dynamically using Javascript. My goal is to be able to add the exact same original table row and its contents below. Below is the HTML code:
<table width="100%" id="processTable">
<tr>
<td id="ProcessDetails"><div id="description">Replace with description.</div>
<div id="QuestionToAnswer"><b>Replace with a question answerable by YES or NO</b></div>
</td>
<td id="AvailableAnswersColumn">
<p id="option1">YES</p>
<p id="option2">NO: Proceed to next question</p>
</td>
</tr>
<!--Insert new table row if needed-->
</table>
<div id="footer">
<input type="button" value="Insert Table Row" id="CreateRow" class="CreateRow" onclick="insertRow()" />
</div>
Here is the Javascript
<script>
function insertRow() {
var table = document.getElementById("processTable");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = //within this cell should be created the div ids "description" + "QuestionToAnswer";
cell2.innerHTML = //within this cell should be created the paragraph with ids "option1" + "option2";;
cell1.setAttribute("id", "ProcessDetails", 0);
cell2.setAttribute("id", "AvailableAnswersColumn", 1);
}
</script>
Please help.
document.createElement will be your friend here.
var div = document.createElement("div");
div.innerHTML = "Replace with description.";
cell1.appendChild(div);
With document.createElement(<tagname>) you can create any html element you want with JavaScript code. You can append it to the cell by using appendChild. Since div in my example is an object and a reference to a DOM node after it gets appended you can set event handlers to it etc.

Categories

Resources