How to use (assign & manipulate) Razor variables in Javascript - javascript

I am trying to create a simple counter for a dynamic table I am creating. Essentially, every time I add a row to the table I want the counter to increase by 1. I'm trying to avoid adding some arbitrary property to the model if I can avoid it but I am really scratching my head at how to get this to work.
My table starts with 2 rows and is model-bound to a list. The intent here is to allow every new row after that to be given a new index so it can be submitted with the form and create the list as I go (one submit action further down in the view, the addRow() function is called with a button that does not submit the form)
Essentially here's what I have in my view
#model AddUsers
#{
ViewData["Title"] = "Add Users";
var Counter = 2;
}
#section Scripts{
<script>
function addCount() {
var count = #Counter;
console.log('count: ' + count + 'counter: ' + '#Counter');
count = count + 1;
#Counter = count;
console.log('count: ' + count + 'counter: ' + '#Counter');
}
</script>
<script>
function addRow() {
var counter = #Counter;
var table = document.getElementById("AddUsersTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = '<input type="text" asp-for="Users[' + counter + '].FirstName"/><br /><span asp-validation-for="Users[' + counter + '].FirstName class="text-danger"></span>';
var cell2 = row.insertCell(1);
cell2.innerHTML = '<input type="text" />';
var cell3 = row.insertCell(2);
cell3.innerHTML = '<input type="text" />';
var cell4 = row.insertCell(3);
cell4.innerHTML = '<input type="text" />';
addCount();
}
</script>
}
When I debug this and view the log and elements in the browser, I see the following.
I am clearly missing something crucial as none of this is working as expected.
What should have been a simple counter is turning out to be a bigger headache than I anticipated. I tried some of the answers and comments from here as well as my own tinkering to no avail.

It seems you want to add the count to number the name.
Change like below:
#model AddUsers
<button onclick="addRow()">Add Row</button>
<table id="AddUsersTable">
<tr>
<th>UserName</th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
<tr>
<td>Candy</td>
<td>aaa1</td>
<td>bbb1</td>
<td>ccc1</td>
</tr>
</table>
#section Scripts{
<script>
var counter = 2;//it must define outside the function
function addRow() {
var table = document.getElementById("AddUsersTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = '<input type="text" asp-for="Users[' + counter + '].FirstName"/><br /><span asp-validation-for="Users[' + counter + '].FirstName class="text-danger"></span>';
var cell2 = row.insertCell(1);
cell2.innerHTML = '<input type="text" />';
var cell3 = row.insertCell(2);
cell3.innerHTML = '<input type="text" />';
var cell4 = row.insertCell(3);
cell4.innerHTML = '<input type="text" />';
counter++;
}
</script>
}
Result:
UPDATE:
1.Model:
public class AddUsers
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Age { get; set; }
}
2.Index.cshtml:
I suggest that you could add _ValidationScriptsPartial,it exists in your template by default and it contains jquery-validate and jquery-validation-unobtrusive.This makes you can validate on client side instead of validating ModelState on server side.
#model IEnumerable<AddUsers>
#{
ViewData["Title"] = "Index";
}
<button onclick="ShowPartial()">Add Row</button>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Age)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Age)
</td>
</tr>
}
</tbody>
</table>
<div id="CreateUserPartial" hidden>
#await Html.PartialAsync("PartialView", new AddUsers())
</div>
#section Scripts
{
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script>
function ShowPartial() {
$('#CreateUserPartial').removeAttr('hidden');
}
</script>
}
3.Partial View(Located at Views/Shared/PartialView.cshtml):
#model AddUsers
<form asp-action="Create">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Age" class="control-label"></label>
<input asp-for="Age" class="form-control" />
<span asp-validation-for="Age" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
4.Controller:
public class AddUsersController : Controller
{
private readonly YourContext _context;
public AddUsersController(YourContext context)
{
_context = context;
}
// GET: AddUsers
public async Task<IActionResult> Index()
{
return View(await _context.Users.ToListAsync());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Age")] AddUsers addUsers)
{
if (ModelState.IsValid)
{
_context.Add(addUsers);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(addUsers);
}
}
Result:

Related

Adding Table Row Using Ajax

I'm creating a function that adds rows to the table one by one when I press the Add Row button.
When data is inserted, i want to insert one row into the database per row
I think I need to add a table row using Ajax,
but I don't know how to use Ajax so please give me some advice.
And I wonder if it is okay to use the saveAll method provided by JPA Repository when inserting data.
registerForm.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>registerForm</title>
<style>
textarea
{
min-height: 5rem;
overflow-y: hidden;
resize: none;
width : 500px;
}
body
{
counter-reset: section;
}
h4::before
{
counter-increment: section;
content: counter(section);
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function resize(obj) {
obj.style.height = '1px';
obj.style.height = (12 + obj.scrollHeight) + 'px';
}
function addRow() {
var selected = $(".project").find("select[name='project.projectCode']").val();
$.ajax({
type: "POST",
url: "/testCase/addRowAjax",
success: function() {
var table = document.getElementById("table");
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = "<h4></h4>";
cell2.innerHTML = "<input type='text' name='testCaseList[0].testCaseName' id='testCaseName'>";
cell3.innerHTML = "<textarea name='testCaseList[0].testProcedure' id='testProcedure' onkeydown='resize(this)' onkeyup='resize(this)'></textarea>";
cell4.innerHTML = "<input type='text' name='testCaseList[0].expect' id='expect'>";
cell5.innerHTML = "<input type='hidden' name='project.projectCode' value='selected'>";
}
})
}
</script>
</head>
<body>
<form th:action="#{/testCase/register}" method="post">
<input type="hidden" name="testCaseCode" value="${testCaseCode}">
<table class="project">
<tr>
<th>Project</th>
</tr>
<tr>
<td>
<select name="project.projectCode" id="projectCode">
<option value="">=== ===</option>
<option th:each="val : ${projectList}" th:value="${val?.projectCode}" th:utext="${val?.projectName}"></option>
</select>
</td>
</tr>
</table>
<table id="table">
<tr>
<td>num</td>
<td>name</td>
<td>testProcedure</td>
<td>expect</td>
</tr>
<tr>
</tr>
</table>
<br>
<button type="button" onclick="addRow()">addRow</button>
<input type="submit" value="submit">
</form>
</body>
</html>
Controller
#RequestMapping("/testCase/register")
public String register(List<TestCase> testCaseList)
{
testCaseService.register(testCaseList);
return "redirect:/testCase/projectList";
}
#RequestMapping("/testCase/addRowAjax")
#ResponseBody
public void addRowAjax()
{
}
ServiceImpl
#Override
#Transactional
public void register(List<TestCase> testCaseList)
{
testCaseRepository.saveAll(testCaseList);
}
Service
void register(List<TestCase> testCaseList);

Make a table row editable on click with Javascript

I want to make the row of my list editable after clicking on edit button. I set editablecontent= true for every row I want to change and added focus with onclick event but this works only for the first item. Could you suggest other ways of making the content of every row editable? I started recently to learn javascript so vanilla javascript would be better. Thanks!
Storedcontact = []
// Represent a contact
function convertToEntry(name, surname, phone, email) {
var obj = {
name: name,
surname: surname,
phone: phone,
email: email
};
return obj;
}
// add contacts
var form = document.getElementById("btn-submit");
form.addEventListener("click", function(ev) {
ev.preventDefault();
var name = document.getElementById("name").value;
var surname = document.getElementById("surname").value;
var number = document.getElementById("phone").value;
var mail = document.getElementById("email").value;
var duplicateFlag = false;
var entry = convertToEntry(name, surname, number, mail);
for (var i = 0; i < Storedcontact.length; i++) {
let entry = Storedcontact[i];
// this is duplicate
if (entry.name === name) {
alert("Duplicate") ;
duplicateFlag = true;
} else {
duplicateFlag = false;
}
}
// store and update ui onlz if name is not duplicate
if (duplicateFlag === false) {
Storedcontact.push(entry);
updateUI();
}
});
// showing contacts
function updateUI() {
var tbody = document.getElementById('entry-table');
// clearing the table
tbody.innerHTML = '';
var newHtml = '';
// looping the stored contacts
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable">${entry.name}</td>
<td contenteditable="true" id="editable">${entry.surname}</td>
<td contenteditable="true" id="editable">${entry.phone}</td>
<td contenteditable="true" id="editable">${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow();">Edit</button></td>
`;
tbody.appendChild(row);
function clearFields() {
document.getElementById("name").value = "";
document.getElementById("surname").value = "";
document.getElementById("phone").value = "";
document.getElementById("email").value = "";
}
clearFields();
}
}
function checkDuplicate (name) {
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
if (entry.name === name) {
alert("Duplicate")
} else {
}
}
}
function editHtmlTableRow (){
document.getElementById("editable").focus();
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<link rel="stylesheet" href="bootstrap.min (3).css">
<title>MyAddressBook</title>
</head>
<body>
<div class="container mt-4">
<h1 class="display-4 text-center">
My<span class="text-primary">Address</span>Book</h1>
<form id="address-form">
<div class="form-group"></div>
<label for="Name">Name</label>
<input type="text" id="name" class="form-control">
<div class="form-group"></div>
<label for="Surname">Surname</label>
<input type="text" id="surname" class="form-control">
<div class="form-group"></div>
<label for="Number">Number</label>
<input type="text" id="phone" class="form-control">
<div class="form-group"></div>
<label for="mail">E-mail</label>
<input type="text" id="email" class="form-control">
</div>
<br>
</br>
<input type="submit" value="Add contact" id="btn-submit" class="btn btn-primary btn-block container mt-4">
</form>
<table class="table table-striped">
<thread>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Number</th>
<th>E-mail</th>
<th></th>
</tr>
</thread>
<tbody id="entry-table"></tbody>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
Assign a unique identifier such as your for loop counter to the Rows
for (var i = 0; i < Storedcontact.length; i++) {
var entry = Storedcontact[i];
// printing loop results
//console.log(JSON.stringify(entry));
// creating rows with entry
var row = document.createElement("tr");
row.innerHTML = `
<td contenteditable="true" id="editable"+i>${entry.name}</td>
<td contenteditable="true" id="editable"+i>${entry.surname}</td>
<td contenteditable="true" id="editable"+i>${entry.phone}</td>
<td contenteditable="true" id="editable"+i>${entry.email}</td>
<td><button class="btn btn-danger btn-sm delete" onClick="document.getElementById('entry-table').deleteRow(${i});">Delete</button></td>
<td><button class="btn btn-danger btn-sm edit" onClick="editHtmlTableRow(${i});">Edit</button></td>
`;
tbody.appendChild(row);
}
and in your function
function editHtmlTableRow (i){
document.getElementById("editable"+i).focus();
}

Adding buttons to each row of a table to remove said row

just looking for a simple solution on solving this, Consider the the following code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript - Add HTML Table Row </title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<form>
<script>
function addRow()
{
// get input values
var name = document.getElementById('name').value;
var currentAge =
document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var Delete = document.getElementById('Delete').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length/2+1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = Delete;
function myFunction(){
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + " tr
elements in the table.";
}
</script>
</form>
</head>
<style>
table, th {
border: 1px solid black;
}
tbody td{
padding: 30px;
}
tbody tr:nth-child(odd){
background-color: #F4BC01;
color: #ABC412;
}
$("")
</style>
<body>
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete Entry
<button id="Delete" onclick="remove_update(event)">delete</button> //this button right here but in each row and not here. should remove said row
</th>
</tr>
</table>
</body>
</html>
What im trying to do is within cel 5 (delete entry) is to add a delete button to each row that is entered into the table that will remove that row but don't know how to go about this. Ideally would like to do this without the use of JQuery if possible, since i've not touched upon it as of yet.
You can use the rowIndex property to delete the row.
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
const index = table.rows.length;
var newRow = table.insertRow(index);
newRow.setAttribute('data-index', index);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.textContent = name;
cel2.textContent = currentAge;
cel3.textContent = Birthday;
cel4.textContent = carType;
cel5.innerHTML = '<button onclick="removeRow(this)" type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
function removeRow(evt) {
const deleteIndex = evt.parentElement.parentElement.rowIndex;
document.getElementById("table").deleteRow(deleteIndex);
}
table,
th {
border: 1px solid black;
}
tbody td {
padding: 30px;
}
tbody tr:nth-child(odd) {
background-color: #F4BC01;
color: #ABC412;
}
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id ="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/>
Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/>
Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Delete</th>
</tr>
</table>
</body>
</html>
What you should be doing is that you set the innerHTML of cel5 to a button, e.g.:
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
Then, you can simply add a click event listener on the table, and check if a click event has emitted from the button element. If it matches, you then delete the closest <tr> element:
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
See proof-of-concept example below:
function addRow() {
// get input values
var name = document.getElementById('name').value;
var currentAge = document.getElementById('currentAge').value;
var Birthday = document.getElementById('Birthday').value;
var carType = document.getElementById('carType').value;
var table = document.getElementsByTagName('table')[0];
var newRow = table.insertRow(table.rows.length / 2 + 1);
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
var cel4 = newRow.insertCell(3);
var cel5 = newRow.insertCell(4);
cel1.innerHTML = name;
cel2.innerHTML = currentAge;
cel3.innerHTML = Birthday;
cel4.innerHTML = carType;
cel5.innerHTML = '<button type="button" class="delete-button">Delete</button>';
}
function myFunction() {
var x = document.getElementById("table").rows.length;
document.getElementById("demo").innerHTML = "Found " + x + "tr elements in the table.";
}
document.getElementById('table').addEventListener('click', function(e) {
// Check if click event came from delete button
if (!e.target.classList.contains('delete-button'))
return;
e.target.closest('tr').remove();
});
<h2>Basic HTML table</h2> <button onclick="myFunction()">Press me for
elements amount</button>
<p id="demo"></p>
Name: <input type="text" name="name" id="name" /><br/><br/> Age: <input type="text" name="currentAge" id="currentAge" /><br/><br/> Date of Birth <input type="date" name="Birthday" id="Birthday" /><br/>
<button onclick="addRow();">Display</button><br/><br/>
<p>Eye Colour:</p>
<select id="carType">
<option value="ferrari" id="ferrari">Ferrari</option>
<option value="lamborghini" id="lamborghini">Lamborghini</option>
<option value="porsche" id="porsche">Porsche</option>
<option value="bugatti" id="bugatti">Bugatti</option>
<option value="pagani" id="pagani">Pagani</option>
</select>
<table border="1" id="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Birthday</th>
<th>CarType</th>
<th>Actions</th>
</tr>
</table>
In the head, add a function that understands rows and cells. Call some delete on a parent of a cell (Delete the <tr> in which the <td> is located at). then on the body add to each dynamic button an onClick event and set that function you created earlier ON.
You can use a script like this:
function deleteRow() {
var tableData = event.target.parentNode;
var tableRow = tableData.parentNode;
tableRow.parentNode.removeChild(tableRow);
}
In the button you create (dynamically or fixedly) you should add an onClick event. For example:
<tr>
<td>John Doe</td>
<td>$10,000</td>
<td><input type="submit" value="Delete" id="Delete" onclick="deleteRow()"></td>
</tr>

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
}

Uncaught SyntaxError: Unexpected string in my Javascript code

I keep getting this error in my code and I don't understand why. See line 29 of my Javascript.
HTML
<link href="Styles12.css"; type="text/css" rel="stylesheet">
<link rel="stylesheet" href="Styles12.css"/>
<script src="registration.js"></script>
<body onload="studentAttendance()">
<head>
<style>
table, td, th {
border: 1px solid black;
}
th {
background-color: beige;
color:black;
}
</style>
</head>
<h3 style= "font-size:25px; font-family:Impact"> ADD A STUDENT</h3>
Firstname:
Lastname:
Student number:
<button onclick = "save()"><p>+ADD TO ATTENDANCE</a></p> </button>
<h2 style="font-size: 25px;font-family: Impact">Online attendance</h2>
<table id= "attendanceTable">
<table border="10px">
<thead>
<tr>
<th> Student Name </th>
<th> Student Number </th>
<th> A </th>
<th> Points </th>
<th style="font-size:10px;font-align: left"><em><button> Edit:Add student(+)</a></button></em></th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td><form action="demo_form.asp" method="get"></form></td>
<td></td>
<td> <input type="button" value="save"></input>
<button>reset</button></td>
</tr>
<tbody>
<tr>
<td></td>
<td></td>
<td><form action="demo_form.asp" method="get"></form></td>
<td></td>
</tr>
<tbody>
<tr>
<td></td>
<td></td>
<td><form action="demo_form.asp" method="get"></form></td>
<td></td>
</tr>
</tbody>
</table>
<form>
</form>
<button type="button" onlick="alert('Attendence submitted')"> <strong>SUBMIT</strong></button>
<p id="demo"></p>
</body>
JAVASCRIPT
var studentNo = [];
var index = 0;
var studentInfo = [];
var newObj = [];
function save() { //this function takes values from the text box and stores them as an object studentInfo[index] = { studentNumber: document.getElementById("studentNo").value, firstname: document.getElementById("firstname").value, lastname: document.getElementById("lastname").value, }; index++;
localStorage.setItem("studentRecord", JSON.stringify(studentInfo));
}
function studentAttendance() {
newObj = JSON.parse(localStorage.getItem("studentRecord"));
var table, row, cell1, cell2, cell3;
table = document.getElementById("onlineAttendance");
studentInfo = JSON.parse(localStorage.getItem("studentRecord"));
for (var index = 0; index < studentInfo.length; index++) {
row = table.insertRow(index + 1);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell1.innerHTML = studentInfo[index].studentNumber;
cell2.innerHTML = studentInfo[index].firstName + " " +
studentInfo[index].lastName;
cell3.innerHTML = studentInfo[index].
'<input type="checkbox" name="student attendance" value="absent" id="checkboxab"</input>';
}
function save() {
if (document.getElementById('checkboxab').checked) {
alert("checked");
} else {
alert("You didnt check it")
studentInfo.points++
}
}
}
. use in php to concat string
+ use in javascript to concat string
try like this
cell3.innerHTML =studentInfo[index]+
'<input type="checkbox" name="student attendance" value="absent" id="checkboxab"</input>';
I think that you are confusing PHP string concatenating with Javascript string concatenating:
PHP
$variable = $other_variable . '<span>hello world</span>'
Javascript
var variable = other_variable + '<span>hello world</span>'
I get it?
The dot is a syntax error. You should use a +.
cell3.innerHTML = studentInfo[index].
'<input type="checkbox" name="student attendance" value="absent" id="checkboxab"</input>';
If you don't have another way to validate your JS, put it into a jsfiddle and press JSHint.
http://jsfiddle.net/mgb8x7pd/

Categories

Resources