Passing hidden value using jQuery in MVC - javascript

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 .

Related

Show data in ajax table, jsp and servlets

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>

How to include a clickable link or button for each record? HTML + Array + Tables

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 &#9650</th>
<th data-column="age" data-order="desc">Age &#9650</th>
<th data-column="birthdate" data-order="desc">Birthday &#9650</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 += '&#9660'
}else{
$(this).data('order', "desc")
myArray = myArray.sort((a,b) => a[column] < b[column] ? 1 : -1)
text += '&#9650'
}
$(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

Populate bootstrap table with JQuery and JSON

I'm trying to populate my bootstrap table (in Database.Master) with data (in DatabaseUI.aspx.cs).
How do I dynamically add rows to the table with Jquery?
Do I have to convert my string to JSON?
I think I have to add another JQuery script in the masterpagefile to append data to the table
$(function() {
$.each(response, function(i, item) {
var $tr = $('<tr>').append(
$('<td>').text(item.UID)
.appendTo('#lblDatabase');
});});
but I'm not sure how to pass to get response in the script to read the string in DatabaseUI.
In Database.Master
<form id="form1" runat="server">
<table class="table" id="lblDatabase">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Pid</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<asp:Label ID="lblDatabaseValues" runat="server"></asp:Label>
</td>
</tr>
</tbody>
</table>
</form>
Code that gets data from API in DatabaseUI
protected async void GetRequest(string url)
{
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
Label lblDatabaseValues = (Label)Master.FindControl("lblDatabaseValues");
//lblDatabaseValues.Text = "Values:";
//lblDatabaseValues.Text = "";
string myContent = await content.ReadAsStringAsync();
string[] values = myContent.Split(';');
for (int i = 0; i < values.Length; i++)
{
lblDatabaseValues.Text = lblDatabaseValues.Text + Environment.NewLine + values[i];
}
lblDatabaseValues.Text = lblDatabaseValues.Text.ToString().Replace(Environment.NewLine, "<br />");
}
//response.IsSuccessStatusCode
//response.StatusCode
}
}
}
Basically the question is not much clear. If you are asking about how to loop over the received response from backend and append it to your table then here is the code for you.
<table id="tdUIDs">
</table>
var rows = "";
$.each(response,function(i,item){
rows += "<tr><td>" + item.UID + "</td></tr>"; //your rows get printed here
});
$("#tdUIDs").append(rows);
I hope this is what you are asking for as am not clear with your question.

MVC razor display element that can be edited by javascript

I'm working with a table that I would like to have display text but also have that text updated by javascript.
I can create a readonly textbox and have javascript edit that, but I would rather just have some text on the screen. Here is a sample that has a DisplayFor which displays text and a readonly textbox which shows the same text.
#for (var i = 0; i < Model.ProjectSubmissions.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(modelItem => Model.ProjectSubmissions[i].ChapterNumber)
</td>
<td>
#Html.TextBox("recordsToSort[" + i + "].ChapterNumber", Model.ProjectSubmissions[i].ChapterNumber, new { #id = "recordsToSort[" + i + "].ChapterNumber", #class = "SortOrder", #readonly = "readonly" })
</td>
</tr>
}
My javacript can edit the textbox like this:
$(".sortable-table tr").each(function (index, element) {
var hiddenInput = $(element).find(".SortOrder").first();
hiddenInput.val(index);
});
Can I write javascript that will update the DisplayFor? Or should I use a different element than DisplayFor that javascript can update?
UPDATE:
I'd like to end up with something like this (I would like to keep the hidden .SortOrder element.):
#for (var i = 0; i < Model.ProjectSubmissions.Count; i++)
{
<tr>
<td>
<span id="#Html.Id("recordstosort[" + i + "].ChapterNumber")" class="SortOrderDisplay">#Model.ProjectSubmissions[i].ChapterNumber</span>
#Html.Hidden("recordsToSort[" + i + "].ChapterNumber", Model.ProjectSubmissions[i].ChapterNumber, new { #id = "recordsToSort[" + i + "].ChapterNumber", #class = "SortOrder" })
</td>
</tr>
}
And javascript like this:
$(".sortable-table tr").each(function (index, element) {
var hiddenInput = $(element).find(".SortOrder").first();
hiddenInput.val(index);
var displayInput = $(element).find(".SortOrderDisplay").first();
if (displayInput !== 'undefined') {
displayInput.text = index;
}
});
But this isn't working.
You can use jQuery text instead of val.
#for (var i = 0; i < Model.ProjectSubmissions.Count; i++)
{
<tr>
<td class="SortOrder">
#Html.DisplayFor(modelItem => Model.ProjectSubmissions[i].ChapterNumber)
</td>
</tr>
}
Then the javascript would be
$(".sortable-table tr").each(function (index, element) {
var hiddenInput = $(element).find(".SortOrder").first();
hiddenInput.text(index);
});
Javascript can be used to update any element you like. The easiest way would probably be to create a span with an id property and then use document.getElementById.innerText to set the text.
You can easily replace the #Html.DisplayFor with a <span id="#Html.IdFor(m => m.ProjectSubmissions[i].ChapterNumber)"></span>.
This only an example, and there are several ways to go about changing text client-side.

Get a particular cell value from HTML table using JavaScript

I want to get each cell value from an HTML table using JavaScript when pressing submit button.
How to get HTML table cell values?
To get the text from this cell-
<table>
<tr id="somerow">
<td>some text</td>
</tr>
</table>
You can use this -
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
if (modify == oCells[0].firstChild.data) {
document.getElementById("Error").innerHTML = " * duplicate value";
return false;
break;
}
}
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
You can also use the DOM way to obtain the cell value:
Cells[0].firstChild.data
Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP.
Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title.
courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only:
Course1
Course2
Course3
......
Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
<td class="virtualTd" onclick="putThis(this)">my td value </td>
function putThis(control) {
alert(control.innerText);
}
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Make a javascript function
function addSampleTextInInputBox(message) {
//set value in input box
document.getElementById('textInput').value = message + "";
//or show an alert
//window.alert(message);
}
Then simply call in your table row button click
<td class="center">
<a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
<span class="fa fa-plus"></span>
</a>
</td>

Categories

Resources