I have the following case that I am having a hard time solving.
In the image what I try to do is look for the documents of the selected process and that they are displayed in the table.
This is done with ajax, jsp and servlet.
For the select dropdown, this is the code where I list the processes through java and jsp classes.
<select class="form-control js-example-basic-single" name="sucursal">
<%
MantenedorProcesosLMD md = new MantenedorProcesosLMD();
List<procesoslmd> ld = md.listar_proc_lista(con);
for (procesoslmd p : ld) {
%>
<option value="<%=p.getLDM_ID()%>">
<%=p.getLDM_NOMBPROCESOS()%>
</option>
<%
}
%>
</select>
This is my code in sql where by means of the IDPROCESOS parameter I look for the documents.
SELECT
D.IDLDMDOCUMENTOS,
LT.NOMBRETIPO,RTRIM(D.LDM_NOMENCLATURA) AS NOMENCLATURA,
RTRIM(D.LDM_NOMBRE_DOCUMENTO) AS TITULO,
D.LDM_FECHA_SUBIDA,D.LMD_RUTA_DOCUMENTO
FROM LDM_DOCUMENTOS_ D
LEFT JOIN LDM_PROCESOS_ LP ON LP.IDLDMPROCESOS = D.IDLDMPROCESOS
LEFT JOIN LDM_TIPO_DOCUMENTO_ LT ON LT.IDTIPODOC = D.IDTIPODOC
WHERE LP.IDLDMPROCESOS = #IDLDMPROCESOS
But so far I can't get to the code to find the documents by clicking the search button, I'm trying to do it with ajax I'm still collecting information.
implement this ajax code where I get the value of my select dropdown the IDPROCESOS and if it brings me the documents so far I can show it in the console, but I want to add it to the table but when I click on the search button
$(document).ready(function () {
$('select[name=procesoldm]').on('change', function () {
$.ajax({
type: 'GET',
url: '../sv_proxdocumento',
data: 'codigoproceso='+$('select[name=procesoldm]').val(),
statusCode: {
404: function () {
alert('PAGINA NO ENCONTRADA');
},
500: function () {
alert('ERROR EN EL SERVIDOR');
}
},
success: function (dados) {
var pegadatos = dados.split(":");
console.log(pegadatos);
for (var i = 0; i < pegadatos.length -1; i++){
var codigodocumento = pegadatos[i].split("-")[0];
var nombretipo = pegadatos[i].split("-")[1];
console.log(nombretipo);
}
}
});
})
});
How do I pass that found data to a table with ajax, thanks for your time.
how it should look in the table when clicking the search button
You can use another for-loop after spliting your values and then on each iteration append td inside some variable using += and then add this generated html inside your table.
Demo Code :
$(document).ready(function() {
/*$('select[name=procesoldm]').on('change', function() {
$.ajax({
//other codes..
success: function(dados) {*/
//var pegadatos = dados.split(":");
//just for demo
var pegadatos = ["1-abc-abd-abdd-2/1/12", "2-abc2-abd2-abdd2-2/22/12", ""]
var html = ""; //declare this
//loop through main array
for (var i = 0; i < pegadatos.length - 1; i++) {
var values = pegadatos[i].split("-") //split values
html += `<tr>`
for (var j = 0; j < values.length; j++) {
html += `<td>${values[j]}</td>` //splited values..
}
html += `<td>--Visitor--</td>`
html += `</tr>`
}
$("table tbody").html(html) //add result inside tbody
/* }
});
})*/
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th>No</th>
<th>DocumentType</th>
<th>DocumentNaming</th>
<th>title</th>
<th>date</th>
<th>visitor</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Related
I have a variable in my jQuery called storedDealer that I want to be filled with the option text when a drop-down item is selected:
var storedDealer = '';
$(document).ready(function () {
let dealerId = #Model.DealerID;
if (0 < dealerId.length) {
$("#DealerID option[value='dealerId'']").attr('selected', 'selected');
$('#dealershipName').val(storedDealer);
}
$('#DealerID').on("change", function () {
storedDealer = this.value;
});
});
function getDealers(el) {
$.get("#Url.Action("GetDealers", "Admin")?region=" + $(el).val(), function (res) {
var markup = "";
for (var i = 0; i < res.length; i++) {
markup += '<option value='+res[i].Value+'>'+res[i].Text+"</option>"
}
$('#DealerID').prop('disabled', false);
$("#DealerID").html(markup).show();
});
}
My HTML has a little bit of C# Razor code that is the only place the DealerID is defined. I have added the <var id="dealershipName"> item:
<tr>
<td align="right">Dealership:</td>
<td>#Html.DropDownListFor(m => m.DealerID, new List<SelectListItem>())</td>
<td><var id="dealershipName" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
I would not have thought the Razor variables would be visible by jQuery, but they somehow seem to work.
But when the search is submitted, the page refreshes. Now the drop-down list is reset and the <var> field is blank.
That <var> field is what I added, and I am trying to get to work.
How can I get the value to stay after the form reloads?
I think you can try to use Session,here is a demo for .net6.Each time the slected value is changed,change storedDealer and the session data.And when you refresh the page,if the session data is not null,storedDealer will be set with the session data:
Program.cs:
builder.Services.AddControllersWithViews();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(1);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
actions:
public IActionResult Test(){
return View();
}
public void SetSession(string storedDealer) {
HttpContext.Session.SetString("storedDealer", storedDealer);
}
Test view:
var storedDealer = "";
$(document).ready(function () {
let dealerId = #Model.DealerID;
if (0 < dealerId.length) {
$("#DealerID option[value='dealerId'']").attr('selected', 'selected');
if(storedDealer==""&&"#(string.IsNullOrEmpty(Context.Session.GetString("storedDealer")))"!=True)
{
storedDealer = "#Context.Session.GetString("storedDealer")";
}
$('#dealershipName').val(storedDealer);
}
$('#DealerID').on("change", function () {
storedDealer = this.value;
$.ajax({
type: "GET",
url: "SetSession",
data: {storedDealer:$("#IdSelectIdEmpleado").val()},
});
});
});
This question already has answers here:
Google script - using template to build table
(1 answer)
Passing variable to HTML output and then into a scriptlet
(1 answer)
Closed 2 years ago.
I have data in a sheet in this format which has to be presented in a tabular form inside an HTML Page
I am using Google App Script for achieving the same. The below code is for trying out this option and if this works, I will fit the code into my original HTML Page.
All other things are working fine except the excel data is not coming into the HTML page. I am able to form the table equal to the length of the data but the information inside it is not coming. I have checked the javascript code independently and the data is being fetched to the code, but it is not appearing in the HTML Code.
I have written the following HTML code
<!DOCTYPE HTML>
<HTML>
<head>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
<body>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<? for (var i=0; i<defintion_s_no.length;i++) {?>
<tr>
<th><?defintion_s_no[i]; ?></th>
<th> 1 </th>
</tr>
<? }?>
</table>
</body>
</html>
and the following javascript code for the same
var url = 'https://docs.google.com/spreadsheets/d/1CGZVG6NGAy325wgCz-dS6ZjJ_it5ShzLshIdD-CCpqs/edit';
function doGet(e){
return definition();
}
function defintion() {
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("Datafeed");
var defintion_s_no = data_till_lastrow_coulmn("Description");
var tmp = HtmlService.createTemplateFromFile('try');
tmp.defintion_s_no = defintion_s_no.map(function(r){ return r[0]; });
return tmp.evaluate().setTitle('Daily Task Updater');
}
function data_till_lastrow_coulmn(key) {
//get the data till the last row of a specified column using the key to find the header of the column
var ss = SpreadsheetApp.openByUrl(url);
var webAppSheet = ss.getSheetByName("Datafeed");
var last_row = webAppSheet.getLastRow();
var header_values = webAppSheet.getRange(1,1,1,15).getValues()[0];
var dropdown_column = 0;
//find the column of the "key" in the header row
for (var i=0; i<15; i++){
if(header_values[i]==key){
dropdown_column = i+1;
}
}
//finding the last row in the column containing key as the header
var workstream_Values = webAppSheet.getRange(2,dropdown_column,last_row,1).getValues();
var dropdown_lastrow = 0;
var blank = false;
for (var i=0;i<last_row;i++){
if(workstream_Values[i+1]==""&& !blank){
dropdown_lastrow = i+1;
blank = true;
break;
}
else if(workstream_Values[i] != ""){
blank = false;
}
}
return webAppSheet.getRange(2,dropdown_column,dropdown_lastrow,1).getValues();
}
I am unable to see the data here
I have learnt a sample code from youtube on putting an array in HTML table dynamically that is sortable. Below is the code.
How do I made each record in display HTML table clickable and call a myFunction()? The myFunction() will then get the value of the Name in the respective row and execute another query.
HTML Part ->
<table class="table table-striped">
<tr class="bg-info">
<th data-column="name" data-order="desc">Name ▲</th>
<th data-column="age" data-order="desc">Age ▲</th>
<th data-column="birthdate" data-order="desc">Birthday ▲</th>
</tr>
<tbody id="myTable">
</tbody>
the javascript part
var myArray = [
{'name':'Michael', 'age':'30', 'birthdate':'11/10/1989'},
{'name':'Mila', 'age':'32', 'birthdate':'10/1/1989'},
{'name':'Paul', 'age':'29', 'birthdate':'10/14/1990'},
{'name':'Dennis', 'age':'25', 'birthdate':'11/29/1993'},
{'name':'Tim', 'age':'27', 'birthdate':'3/12/1991'},
{'name':'Erik', 'age':'24', 'birthdate':'10/31/1995'},
]
$('th').on('click', function(){
var column = $(this).data('column')
var order = $(this).data('order')
var text = $(this).html()
text = text.substring(0, text.length - 1)
if(order == 'desc'){
$(this).data('order', "asc")
myArray = myArray.sort((a,b) => a[column] > b[column] ? 1 : -1)
text += '▼'
}else{
$(this).data('order', "desc")
myArray = myArray.sort((a,b) => a[column] < b[column] ? 1 : -1)
text += '▲'
}
$(this).html(text)
buildTable(myArray)
})
buildTable(myArray)
function buildTable(data){
var table = document.getElementById('myTable')
table.innerHTML = ''
for (var i = 0; i < data.length; i++){
var row = `<tr>
<td>${data[i].name}</td>
<td>${data[i].age}</td>
<td>${data[i].birthdate}</td>
</tr>`
table.innerHTML += row
}
}
My Function Call Js part
function myFunction() { " wanna get the value of the row if link is click" }
You need to add the following after you call the buildTable(myArray) so the <tr> tags can render before you assign them a click event.
$('tr').click(function(){
var name = $(this).children('td').first().html();
yourFunction(name);
});
function yourFunction(name){
//do things with name here
}
Also, this assumes that the first td will always contain the name. A better implementation would be to refactor the buildTable function and give classes to your td
$(document).on("click", "tbody tr", function(){
//if you want name field
$(this).find("td:nth-child(1)").text();
//if you want age field
$(this).find("td:nth-child(2)").text();
});
i done the myFunction in Jquery, use this code inside your script tag
I have a form that when submitted shows a table with different data (ajax request to php file) depending on the user's input. Is there a way for me to dynamically reload the table with new information each time the user submits the form? As of now, the data keeps appending to the table after each submit and keeps adding on to the last submit data. Any suggestions would be greatly appreciated, thanks!
HTML
<form id = "infoForm"
action="file.php" method="post">
<b>Enter info:</b> <input type = "text" name = "info"
id = "infoInput" maxlength = "10" required >
<button type = "submit" id = "submit_form">Submit</button>
</form>
<table id = "infoTable">
<tbody>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</tbody>
</table>
JavaScript
$("#infoForm").submit(function() {
$("#infoTable").fadeIn(400);
//InputData is an array that contains the user input data
$.post( "file.php", InputData,
function( data ){
var names = data.names; //from PHP file
var numbers = data.numbers; //from PHP file
var namesArray = names.split(',');
var numbersArray = numbers.split(',');
for(var i = 0; i < namesArray.length; i++) {
$("#infoTable > tbody").append('<tr><td>'+namesArray[i]+'</td><td>'+numbersArray[i]+'</td></tr>');
}
}, "json");
return false;
});
You need to clean the tbody then append the new records.
Try this:
$("#infoForm").submit(function() {
$("#infoTable").fadeIn(400);
//InputData is an array that contains the user input data
$.post( "file.php", InputData,
function( data ){
var names = data.names; //from PHP file
var numbers = data.numbers; //from PHP file
var namesArray = names.split(',');
var numbersArray = numbers.split(',');
$("#infoTable > tbody").empty(); // clean the tbody before adding new data
for(var i = 0; i < namesArray.length; i++) {
$("#infoTable > tbody").append('<tr><td>'+namesArray[i]+'</td><td>'+numbersArray[i]+'</td></tr>');
}
}, "json");
return false;
});
My MVC Controller passes a Model to view in the following form
public class LibaryModel
{
public int LibaryId { get; set; }
public string[] Books { get; set; }
}
This is my LibraryView.cshtml
#model IEnumerable<LibaryModel>
<table id="myTable" class="table-bordered">
<thead>
<tr>
<th>Libary Id</th>
</tr>
</thead>
<tbody>
#foreach (var library in Model)
{
<tr>
<td>#library.LibaryId</td>
</tr>
}
</tbody>
</table>
Now, On clicking the library id, I need to show another div with the list of books in that library. I am able to get the row number and column number of click event, but I am not able to figure a way to get the list of books in the libary from jQuery. Is there any pattern to solve this?
$("#myTable td").on('click', function () {
var column_num = parseInt($(this).index()) + 1;
var row_num = parseInt($(this).parent().index()) + 1;
});
I would suggest using the LibraryId in a function on a click event in your td.
foreach (var library in Model)
{
<tr>
<td onclick="getHiddens(#library.LibraryId)">#library.LibaryId</td>
</tr>
}
And give your books' hidden inputs a class that contains its library's LibraryId
for (var i = 0; i < library.Books.Length; i++)
{
<input type="hidden" class="book#library.LibraryId" value="#library.Books[i]" />
}
And then sending that LibraryId into a function as an argument that gets all matching inputs by class, and does something with the input's value, like for this example, loading it into a div.
var getHiddens = function (libraryId) {
var books = document.getElementsByClassName("book" + libraryId);
var bookDiv = document.getElementById("bookDiv");
bookDiv.innerHTML = "<ul>";
for (var i = 0; i < books.length; i++) {
bookDiv.innerHTML += "<li>" + books[i].value + "</li>";
}
bookDiv.innerHTML += "</ul>";
}
Please check my code .
#foreach (var library in Model)
{
<tr>
<a href="javascript:void(0)"
onclick="GoToInsured('#library.LibaryId');">
</tr>
}
function GoToInsured(LibaryId)
{
//This LibaryId is current selected row ID.You can open new Diva per
LibaryId. You can get Library details as per LibaryId and you can display
that data on Popup or any place you want.
}
Tell me you have any query regarding my code .
Thanks .