How-To: Creating Angular/Bootstrap btn-checkboxes in a repeater - javascript

I'm attempting to create a grid (table with ng-repeat) where in each row, there are 4 columns of buttons. Ideally the buttons would be checkboxes, such as the Angular/Bootstrap btn-checkbox, so that they would have an on and off mode, which I would set from my database-derived data in the C# code that would feed the Angular page.
The problem I'm having is that I don't really know how to check the state of those btn-checkbox controls in my controllers.js when the Apply/Save button gets clicked, so I can save the values.

How about something like this?
I'm using eval to create scope variables within $scope.buttons.
http://jsfiddle.net/tekmtn/dnfhnLex/3/
app = angular.module('myApp', ['ui.bootstrap']);
app.controller("myController", function($scope) {
$scope.records = [1,2,3,4];
$scope.buttonSets = [1,2,3,4];
$scope.buttonsPerSet = ["Added", "Changed", "Closed"];
$scope.buttons = {};
$scope.toggleButton = function(recNum, setNum, btnText) {
var field = "$scope.buttons." + "btnRec" + recNum + "_setNum_" + setNum + "_" + btnText;
var value = eval(field);
if(!value) {
eval(field + " = 1;");
} else {
eval(field + " = 0;");
}
}
$scope.isActive = function(recNum, setNum, btnText) {
var field = "$scope.buttons." + "btnRec" + recNum + "_setNum_" + setNum + "_" + btnText;
var value = eval(field);
if(value == 1) {
return true;
} else {
return false;
}
}
$scope.save = function() {
// send $scope.buttons through web service.
}
});
<div ng-app="myApp">
<div ng-controller="myController">
<table class='table table-striped'>
<thead>
<tr>
<th>Record</th>
<th ng-repeat="setNum in buttonSets">
Button Set {{setNum}}
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="recNum in records">
<td>Record {{recNum}}</td>
<td ng-repeat="setNum in buttonSets">
<button ng-repeat="btnText in buttonsPerSet"
class='btn btn-default btn-xs' type='button'
uib-btn-checkbox
btn-checkbox-true="1"
btn-checkbox-false="0"
ng-click="toggleButton(recNum, setNum, btnText);"
ng-class="{'active':isActive(recNum, setNum, btnText)}">
{{btnText}}
</button>
</td>
</tr>
</tbody>
</table>
{{buttons}}
<br /><br />
<button type='button' class='btn btn-default'>Cancel</button>
<button type='button' class='btn btn-default'>Apply</button>
<button type='button' class='btn btn-default'>Save</button>
</div>

Related

Disable and enable Select Value using Java Script

I am using below code.If i click Testing 1 or Testing 2 or selectAll,new rows will be created.I need to disable DatatType and Expected set value column if Execution Type is Get.If I select Set from Execution Type, DataType and Expected set value column should be enabled.How to implmente this? I am using this code in Html.erb file.How to create separate js method?
https://jsfiddle.net/bx5fa2vu/
$("#all").on("click", function() {
if ($(this).is(":checked")) {
let boxes = $("#paramTable input[type='checkbox']").not(this).not(":checked");
boxes.each(function() {
$(this).click();
});
} else {
let boxes = $("#paramTable input[type='checkbox']:checked").not(this);
boxes.each(function() {
$(this).click();
});
}
});
$("#paramTable input[type='checkbox']:not(#all)").on("click", function() {
if ($(this).is(":checked")) {
let name = $(this).parent("td").next("td").next("td").text().trim();
let newname = name.split('.').join('');
let newrow = $("<tr>");
let newcell = $("<td> ");
let newSel=$("<select class='ExeType' name='ExeTypeValue'><option value='getData'>Get</option><option value='SetData'>Set</option></select>")
newcell.append(newSel);
newrow.append(newSel);
let newcell1 = $("<td> ");
let newinput = $("<input type='text' class='parameterName' name='" + newname + "' id='" + newname + "' value='" + name + "'/>");
newcell1.append(newinput);
newrow.append(newcell1);
let newcells = $("<td><select class='parameterDscription' name='parameter_description'><option value=''>Select Data Type</option><option value='OCTET_STRING'>String</option><option value='INTEGER'>Integer</option><option value='INTEGER32'>Unsigned Integer</option><option value='IPADDRESS'>IP Address</option><option value='x'>Hex String</option></select></td><td><input type='text' class='expectedValue' name='expected_value'></td>");
newrow.append(newcells);
$("tbody.parameter_table").append(newrow);
} else {
let name = $(this).parent("td").next("td").next("td").text();
let newname = name.split('.').join('');
console.log("newname: " + newname)
$("#addParamTable").find("#" + newname).closest("tr").remove();
$("#all").prop("checked", false);
}
})
You can do it like this. Note that initially the fields are not disabled because no value is selected at the Execution Type select field. Maybe you want to make this more clear by adding an initial option with the text "Select Type" to the select field like you have it for the select for Data Type.
$("#all").on("click", function() {
if ($(this).is(":checked")) {
let boxes = $("#paramTable input[type='checkbox']").not(this).not(":checked");
boxes.each(function() {
$(this).click();
});
} else {
let boxes = $("#paramTable input[type='checkbox']:checked").not(this);
boxes.each(function() {
$(this).click();
});
}
});
$("#paramTable input[type='checkbox']:not(#all)").on("click", function() {
if ($(this).is(":checked")) {
let name = $(this).parent("td").next("td").next("td").text().trim();
let newname = name.split('.').join('');
let newrow = $("<tr>");
let newcell = $("<td> ");
let newSel = $("<select class='ExeType' name='ExeTypeValue'><option value='getData'>Get</option><option value='SetData'>Set</option></select>")
newcell.append(newSel);
newrow.append(newSel);
let newcell1 = $("<td> ");
let newinput = $("<input type='text' class='parameterName' name='" + newname + "' id='" + newname + "' value='" + name + "'/>");
newcell1.append(newinput);
newrow.append(newcell1);
let newcells = $("<td><select class='parameterDscription' name='parameter_description'><option value=''>Select Data Type</option><option value='OCTET_STRING'>String</option><option value='INTEGER'>Integer</option><option value='INTEGER32'>Unsigned Integer</option><option value='IPADDRESS'>IP Address</option><option value='x'>Hex String</option></select></td><td><input type='text' class='expectedValue' name='expected_value'></td>");
newrow.append(newcells);
$("tbody.parameter_table").append(newrow);
} else {
let name = $(this).parent("td").next("td").next("td").text();
let newname = name.split('.').join('');
console.log("newname: " + newname)
$("#addParamTable").find("#" + newname).closest("tr").remove();
$("#all").prop("checked", false);
}
})
$(document).on("change", ".ExeType", function() {
let type = $(this).val();
if (type === "getData") {
$(this).closest("tr").find(".parameterDscription").attr("disabled", "disabled");
$(this).closest("tr").find(".expectedValue").attr("disabled", "disabled");
} else {
$(this).closest("tr").find(".parameterDscription").removeAttr("disabled");
$(this).closest("tr").find(".expectedValue").removeAttr("disabled");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="paramTable">
<tr>
<td><input type="checkbox" id="all" /></td>
<td>Select all</td>
<td></td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Testing 1</td>
<td>1.2.3.4.5</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Testing 2</td>
<td>.1.3.4.5.8</td>
</tr>
</table>
<div class="tab-content">
<div id="protocol" class="tab-pane fade in active">
<div class="span3 border-0" style="overflow: scroll">
<table id="addParamTable" class="table table-bordered">
<thead>
<tr class="info">
<th>Excution Type</th>
<th>Parameter Name</th>
<th>Data Type</th>
<th>Expected Set Value</th>
</tr>
</thead>
<tbody class="parameter_table">
</tbody>
</table>
</div>
</div>
</div>

my input return me undefined even though the data is catch. using CRUD js

<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries');
this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "popultns" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var pop = el2.value;
if (country2)
{ // Add the new value
loadTableData.push(country2.trim() );
// Reset input value
el.value = '';
//el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
the image is the ui tht im working for the function
I'm supposed to auto-generate the table based on the data available from my main.js script which is in JSon format. There is no problem with the data loading since the data can be display in my html file. However, the problem comes whn my data is returned undefined on my auto generated table whn i click the 'add' button to update the data in the table. Whn i click in the edit button, the data is get correctly. only whn the display, it returns me undefined.
i know how alrdy.
here i attach the code & sample of the data i hv done.
hopefully this would help fresh grad like me who hv trouble in undrsntdng CRUD
<html>
<head>
<meta charset="UTF-8">
<title>Countries CRUD</title>
<style>
input[type='submit'], button, [aria-label]{
cursor: pointer;
}
#spoiler{
display: none;
}
</style>
</head>
<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries' && 'popultns');
//this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "populations" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var popltn = el2.value;
if (country2 && popltn )
{ // Add the new value
//loadTableData.push(country2.trim() );
loadTableData.push({country: country2, population:popltn});
// Reset input value
el.value = '';
el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
this.Edit = function (item)
{ var el3 = document.getElementById('edit-name');
var el4 = document.getElementById('edit-popu');
// Display value in the field
let index = item;
el3.value = loadTableData[index].country;
el4.value = loadTableData[index].population;
// Display fields
document.getElementById('spoiler').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function()
{
// Get value
var country2 = el3.value;
var popltn = el4.value;
//console.log({country2, pop});
if (country2 || pop)
//console.log(country2);
{ // Edit value (strt,del,replace)
console.log(country2,popltn);
console.log(index, 1,({country2,popltn}));
//update array
loadTableData[index].country = el3.value;
loadTableData[index].population = el4.value;
//self.loadTableData.splice(index, 1,({country2,popltn}));
//console.log(index, 1, pop.trim());
//self.loadTableData.splice(index, 1, pop.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item)
{
// Delete the current row
loadTableData.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput()
{ document.getElementById('spoiler').style.display = 'none';}
</script>
</body>
</html>

How can i multiply or add the values of a dynamic javascript input field

The input field are been generated by javascript. I want to pick each value no matter how many input field I generate...so I can use the values for some calculations.
<form action="{{ route('addmorePost') }}" method="POST">
<div class="table-responsive">
<span id="result"></span>
<table class="table table-bordered">
<thead>
<tr>
<th width="55%">Sales Representative</th>
<th width="15%">Target per day</th>
<th width="15%">Monthly day</th>
<th width="10%"> + </th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="target[]" class="form-control target" id="target" oninput="calc()">
</td>
<td><span id="sum1" onchange="add()">0</span> </td>
<td> - </td>
</tr>
</tbody>
<tfoot>
<tr>
<th>
</th>
<th> Total</th>
<th><span id="sumx">0</span> </th>
</tr>
</tfoot>
<script>
function add() {
var ven1 = document.getElementById('sum1').innerHTML;
var valuey = document.getElementById('result1').innerHTML || 0;
console.log(ven1);
console.log(valuey);
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey);
}
</script>
</table>
</button>
</form>
BELOW IS THE JAVASCRIPT FOR GENERATED INPUT FIELDS
<script type="text/javascript">
$(document).ready(function(){
var postURL = "http://localhost/bcwater/public/addmore";
var i=1;
$('.addRow').on('click', function(){
i++;
addRow();
});
function addRow(){
var tr = '<tr class="dynamic-added">'+
'<td>'+
'</td>'+
'<td><input type="text" name="target[]" id="target2" class="form-control" oninput="calc()" /> </td>'+
'<td><span id="result1">0</span> </td>'+
'<td> - </td>'+
'</tr>';
$('tbody').append(tr);
};
$('tbody').on('click','.remove', function(){
$(this).parent().parent().remove();
});
});
THIS IS THE CODEI HAVE TRIED TO GET THE VALUES , MULTIPLY THEM BY 26 AND DISPLAY THE ANSWER ON sum1
<script>
function calc(){
var value1 = document.getElementById('target').value || 0;
document.getElementById('sum1').innerHTML = parseInt(value1 * 26);
var value2 = document.getElementById('target2').value;
document.getElementById('result1').innerHTML = parseInt(value2 * 26);
var ven1 = document.getElementById('sum1').innerHTML;
var valuey = document.getElementById('result1').innerHTML || 0;
console.log(ven1);
console.log(valuey);
document.getElementById("products").disabled = false;
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey);
}
</script>
PLEASE HELP!!!...WHAT AM I DOING WRONG
From your code every time you call addRow() the ID is always target2.
To auto change the ID, have a variable that holds the current ID and concatenate the string, you can make use of the var i.
$(document).ready(function(){
var postURL = "http://localhost/bcwater/public/addmore";
var i=1;
$('.addRow').on('click', function(){
i++;
addRow(i);
});
function addRow(i){
var tr = '<tr class="dynamic-added">'+
'<td>'+
'</td>'+
'<td><input type="text" name="target[]" id="target' + i + '" class="form-control" oninput="calc()" /> </td>'+
'<td><span id="result' + i + '">0</span> </td>'+ //This is modified to attach the current index to result
'<td> - </td>'+
'</tr>';
$('tbody').append(tr);
};
$('tbody').on('click','.remove', function(){
$(this).parent().parent().remove();
});
});
The i variable should always hold the index for the last row added
To multiply the values you have to make use of the same i variable, the function calc() should look like this, i suggest you rename i to something descriptive:
function calc(){
var value1 = document.getElementById('target').value || 0;
document.getElementById('sum1').innerHTML = parseInt(value1 * 26);
for(var j = 1; j <= i; j++) {
var value2 = document.getElementById('target' + j).value;
document.getElementById('result' + j).innerHTML = parseInt(value2 * 26); // This is to target the result span that corresponds to the input value
}
var ven1 = document.getElementById('sum1').innerHTML;
var valuey = document.getElementById('result1').innerHTML || 0;
console.log(ven1);
console.log(valuey);
document.getElementById("products").disabled = false;
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey);
}
Thank u..i was able to do it this way...after i increate the value of the id like this
id="target' + i + '" and also span
so i use the below code to get the values manually...not the best option, but it solved my problem cos i dont need more than three input fields
function calc(){
var value1 = document.getElementById('target').value || 0;
document.getElementById('sum1').innerHTML = parseInt(value1 * 26);
var value2 = document.getElementById('target2').value;
document.getElementById('result2').innerHTML = parseInt(value2 * 26);
document.getElementById("products").disabled = false;
var value2 = document.getElementById('target3').value;
document.getElementById('result3').innerHTML = parseInt(value2 * 26);
var ven1 = document.getElementById('sum1').innerHTML || 0;
var valuey = document.getElementById('result2').innerHTML || 0;
var valuenew = document.getElementById('result3').innerHTML || 0;
document.getElementById('sumx').innerHTML = parseInt(ven1) + parseInt(valuey) + parseInt(valuenew);
}
</script>

How do I make a list of DB data from jsp and print it out?

I am in the beginning stage of web development.
I can get the DBdata but I'm not sure how to print it out as a list.
I'm printing out this table list.
SELECT
seq_no,
type_big_category,
body,
status
FROM DB_TABLE;
And the list output is running in js file.
$(function() {
$.ajax({
url : "/dblistdata",
type : "GET",
dataType : "json",
data: data,
timeout: 10000
}).done(function (result) {
if(result.resultCode == "S000"){
for (var i = 0; i < result.length; i++) {
var tableBody = '<tr>'
+ '<td>' + result.messagelist[i].type_big_category + '</td>'
+ '<td>' + result.messagelist[i].type_mid_category + '</td>'
+ '<td>'
+ '<label class="checkbox" for="checkbox' + i + '">'
+ '<input type="checkbox" name="checkbox" id="checkbox' + i + '" checked="checked" />'
+ '</label>'
+ '</td>'
+ '<td>'
+ '<textarea class="form-control push-text">"' + result.messagelist[i].body + '"</textarea>'
+ '</td>'
+ '<td>'
+ '<button type="button" class="btn btn-primary">save</button>'
+ '<button type="button" class="btn btn-default" id="deletebutton'+ i + '">delete</button>'
+ '</td>'
+ '</tr>';
$('#tbody').append(tableBody);
var btn[i] = document.getElementById('deletebutton[i]');
btn[i].disabled = 'disabled';
}
}else{
alert(result.resultMsg);
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
})
});
And I have to show the list in the jsp file.
<form class="smart-form">
<table class="tb-regist" id="eeMsg">
<thead>
<tr>
<th>Sortation</th>
<th>situation</th>
<th>check</th>
<th colspan="2">message</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</form>
It has to be output in this way. How do you print it out? Please help me a lot.
I see you are using Java so probably you are using servlet-like request processor. So you have at least two approachs to make your view, the third one is just a suggestion that I've found useful :
Add your list as an attribute of the request for your JSP and use JSTL
Get your list with asynchronous javascript request (i.e. fetch or XHR)
Use third-party library (like Boostrap-tables)
Add your list as an attribute of the request for your JSP and use JSTL
Servlet
Add your list to the request attribute.
public void doGet( // or doPost
HttpServletRequest req,
HttpServletResponse res
) throws ServletException, IOException {
List<Object> myList = new ArrayList<>();
req.setAttribute("myList", myList);
}
JSP
Iterate with JSTL through your list and call whatever object attribute you want for each cell of each row of your table.
<form class="smart-form">
<table class="tb-regist" id="eeMsg">
<thead>
<tr>
<th>Sortation</th>
<th>situation</th>
<th>check</th>
<th colspan="2">message</th>
</tr>
</thead>
<tbody>
<c:forEach items="${ myList }" var="object">
<tr>
<td>${ object.seq_no }</td>
<td>${ object.type_big_category }</td>
<td>
<label class="checkbox" for="checkbox01">
<input type="checkbox"
name="checkbox"
id="checkbox01"
checked="checked" />
<i/>
</label>
</td>
<td>
<textarea class="form-control push-text">body</textarea>
</td>
<td>
<button type="button"
class="btn btn-primary">
save
</button>
<button type="button"
class="btn btn-default"
id='deletebutton'>
delete
</button>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</form>
Don't forget JSTL declaration though!
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Get your list with asynchronous javascript request (i.e. fetch or XHR)
Servlet
Add your list to the request attribute but as JSON format, you can use org.json.JSONArray from org.json library.
public void doPost( // or doGet
HttpServletRequest req,
HttpServletResponse res
) throws ServletException, IOException {
List<Object> myList = new ArrayList<>();
JSONArray jsonArray = new JSONArray(myList);
res.setContentType("application/json");
res.getWriter().print(jsonArray);
res.getWriter().flush();
res.getWriter().close();
res.flushBuffer();
}
JSP
Just static HTML, table will be build with javascript.
<form class="smart-form">
<table class="tb-regist" id="eeMsg">
<thead>
<tr>
<th>Sortation</th>
<th>situation</th>
<th>check</th>
<th colspan="2">message</th>
</tr>
</thead>
</table>
</form>
Javascript
Parse your response as JSON and iterate over to build your table with HTMLTableElement.
// XHR post function
var sendXHRPost = void 0;
{
sendXHRPost = function (url, params, callback) {
var http = new XMLHttpRequest();
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if (http.readyState === 4) {
callback(http.status, http.responseText);
}
}
http.send(params);
}
}
// get your table data
var fetchTableData = void 0;
{
fetchTableData = function () {
sendXHRPost(
'myURL',
// maybe you don't pass parameters to fetch your table?
'parameterName=parameterValue',
function (responseStatus, responseText) {
makeTable(responseStatus, JSON.parse(responseText);
}
);
}
}
// formatter for your textarea cell
var textAreaCellFormatter = void 0;
{
textAreaCellFormatter = function (rowId) {
return '<textarea class="form-control push-text">'
+ rowId
+ '</textarea>';
}
}
// formatter for your buttons cell
var buttonsCellFormatter = void 0;
{
buttonsCellFormatter = function (rowId) {
return '<button type="button" '
+ 'class="btn btn-primary">'
+ 'save'
+ '</button>'
+ '<button type="button" '
+ 'class="btn btn-default" '
+ 'id="deletebutton'+rowId+'">'
+ 'delete'
+ '</button>';
}
}
// build your table
var makeTable = void 0;
{
makeTable = function (status, jsonResponse) {
var table = document.getElementById("eeMsg");
// Delete table content in case it was already loaded
for (var i = 1 ; i < table.rows.length ; i++) {
table.deleteRow(i);
}
for (var i = 0 ; i < table.tBodies.length ; i++) {
table.removeChild(table.tBodies[i]);
}
// Create tbody
var tBody = table.createTBody();
// Handle internal server error
if (status != 200) {
var row = tBody.insertRow();
var cell = row.insertCell(0);
cell.colSpan = "4";
cell.innerHTML = "Error while fetching data.";
}
// Handle no data found
else if (jsonResponse.length === 0) {
var row = tBody.insertRow();
var cell = row.insertCell(0);
cell.colSpan = "4";
cell.innerHTML = "No data found.";
}
// All fine, build your table
else {
for(var i = 0 ; i < jsonResponse.length ; i++) {
var row = tBody.insertRow();
row.insertCell(0).innerHTML = jsonResponse[i].seq_no;
row.insertCell(1).innerHTML = jsonResponse[i].type_big_category;
row.insertCell(2).innerHTML = textAreaCellFormatter(i);
row.insertCell(3).innerHTML = buttonsCellFormatter(i);
}
}
}
}
// Execute your function on page loading.
(function () { fetchTableData(); })();
Use third-party library (like Boostrap-tables)
Servlet
Same has above.
JSP
<!-- libs and css -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table#1.15.2/dist/bootstrap-table.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/bootstrap-table#1.15.2/dist/bootstrap-table.min.js"></script>
<!-- your table in your body, not builded yet -->
<table id="eeMsg"
data-toolbar="#toolbar"
data-toggle="table"
data-pagination="true"
data-search="true"
data-url="yourFetchURLWithJSONResponse">
<thead>
<tr>
<th data-field="seq_no">Sortation</th>
<th data-field="type_big_category">situation</th>
<th>check</th>
<th colspan="2">message</th>
</tr>
</thead>
</table>
You can use for loop to fetch the data to the table. Your ajax code should be like the following. After getting all the results it will show in your table.
$(function() {
$.ajax({
url : "/dblistdata",
type : "GET",
dataType : "json",
success : function(result) {
console.log(result);
for (var i = 0; i < result.length; i++) {
var tableBody = "
<tr>
<td>" + result[i].seq_no + "</td>
<td>" + result[i].type_big_category + "</td>
<td>
<label class="checkbox" for="checkbox01">
<input type="checkbox" name="checkbox" id="checkbox01" checked="checked" />
</label>
</td>
<td>
<textarea class="form-control push-text">" + result[i].body + "</textarea>
</td>
<td>
<button type="button" class="btn btn-primary">save</button>
<button type="button" class="btn btn-default" id="deletebutton">dlete</button>
</td>
</tr>
";
$('#tbody').append(tableBody);
}
}
})
});
Your HTML code should be like this,
<form class="smart-form">
<table class="tb-regist" id="eeMsg">
<thead>
<tr>
<th>Sortation</th>
<th>situation</th>
<th>check</th>
<th colspan="2">message</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
</form>
I assume that you are using JQuery. But if not add JQuery.

Error while input datepicker value into a html table

I try to make an input data into a table html. The other input works fine but I got error while I called the textbox that contains a datepicker value into my table. How to fix it? The error say's like this ("Object Html InputELement").
This is the code:­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
// JavaScript Document
function AddData() {
var x = document.getElementById("material").value;
var y = document.getElementById("kapal").value;
var letters = '/^[a-zA-Z]+$/';
if ((parseInt(x) != (x)) && (y == parseInt(y))) {
alert("Wrong Value Entered");
} else {
var rows = "";
var name = "sadcsad";
var gender = $('input[name="gender"]').val();
var tgl = document.getElementById("datepicker").value;
var nopol = document.getElementById("nopol").value;
var netto = document.getElementById("netto").value;
rows += "<tr><td>" + datepicker + "</td><td>" + nopol + "</td><td>" + netto + "</td></tr>";
$(rows).appendTo("#table_bkk tbody");
}
}
function ResetForm() {
document.getElementById("person").reset();
}
<div id="kanan" class="btn btn-default" style="padding-left:20px" >
<table id="table_bkk" cellspacing='0' class="js-serial" border="2">
<thead>
<tr>
<th><center>No.</center></th>
<th><center>Tanggal</center></th>
<th><center>No.Polisi</center></th>
<th><center>Berat Material</center></th>
</tr>
</thead>
<tbody>
</tbody>
<tr>
<td width="auto" style="border-right:hidden" align="right">Total Bongkaran</td>
<td width="auto" style="border-right:hidden" align="left">:</td>
<td width="auto" style="border-right:hidden">
<td width="auto">
<input type="text" id="sts" type="text" name="sensor1" maxlength="10" size=9 disabled="disabled"> </td>
</tr>
</table>
<script>
function incrementValue()
{
var value = parseInt(document.getElementById('no').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('no').value = value;
}
</script>

Categories