call razor function from javascript - html

I'm creating a website with razor with a database but I have a problem changing database elements from within the webpage.
All elements are shown in a table with an update button. If the button is clicked, it sends it's ID to a JavaScript function. In that function an array is created with all the necessary properties. Then I want to pass that array to my razor function, but when calling the function in JavaScript, I get an error (The name 'kamer' does not exist in the current context). Anyone knows a solution?
thanks!
my razor function:
#functions{
public String saveRoom(string[] room){
var db = Database.Open("Studentenkamers");
var sql = "UPDATE Studentkamer SET oppervlakte='" + room[1] + "', locatie='" + room[2] + "', type='" + room[3] + "', vrij='" + room[4] + "' WHERE id='" + room[0] + "'";
db.Query(sql);
return "ok";
}
}
the html and javascript code:
#foreach(var row in db.Query(getKamers))
{
<tr id="#row.id">
<td class="td-id">#row.id</td>
<td class="td-opp"><input type="text" value="#row.oppervlakte" name="oppervlakte" id="td-opp" /></td>
<td class="td-loc">#row.locatie</td>
<td class="td-type"><input type="text" value="#row.type" name="type" id="td-type" /></td>
<td class="td-kamernr">#row.kamernr</td>
<td class="td-vrij"><input type="text" value="#row.vrij" name="vrij" id="td-vrij" /></td>
<td class="td-update"><input type="button" value="opslaan" onclick="updateRoom(this.id)" name="opslaan" id="#row.id" /></td>
</tr>
}
</table>
<script type="text/javascript">
function updateRoom(id) {
var opp = $("#" + id + " .td-opp input").attr("value");
var locatie = $("#" + id + " .td-loc").html();
var type = $("#" + id + " .td-type input").attr("value");
var kamernr = $("#" + id + " .td-kamernr").html();
var vrij = $("#" + id + " .td-vrij input").attr("value");
var kamer = [id, opp, locatie, type, kamernr, vrij];
alert(kamer);
#saveRoom(kamer);
}
</script>

Related

Is there a good package/library to add Pagination/Sorting/Searching to my table? ASP.NET Core

I am new to web development in ASP.NET Core. I have a table with information, I would like to add pagination/sorting/searching to the table. Is there an easy way to add this using some sort of library/package? Thanks
I need pagination, sorting, and searching for my ASP.NET Core table.
I would like to add pagination/sorting/searching to the table. Is
there an easy way to add this using some sort of library/package?
Well, considering all the requirement you can go for jquery data table regardless of simplicity, quick implementation and free subscription. Importantly, its light weight and easy to use.
Here is the compplete example how you can implement that:
Controller:
[HttpGet]
public IActionResult ConAction()
{
var controlleractionlist = _context.Controller.ToList();
return Json(controlleractionlist);
}
Note: I am returning a simple list to demonstrate you , sorting, searching and paging functionality.
View:
<table id="userTable_info" >
<thead>
<tr>
<th>action </th>
<th>controller </th>
<th>returnType</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
//Button Click Functions
function DetailsFunc(data) {
alert("User Id:" + data + " Details!");
}
function EditFunc(data) {
alert("User Id:" + data + " will be Edited!");
}
function DeleteFunc(data) {
alert("User Id:" + data + " will be deleted!");
}
//On Load
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://localhost:5094/Home/ConAction',
dataType: "json",
contentType: "application/json",
success: function (response) {
console.log(response);
var id = 0;
$.each(response, function (index, value) {
id++;
console.log(id);
var tr = "<tr>";
tr += "<td>" + value.action + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.returnType + "</td>";
tr += "<td>" + "<input type='button' id='" + id + "' class='btn btn-info' onclick='DetailsFunc(" + value.id + ")' value='Details'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
}
});
});
</script>
}
Output:
You could refer to official document for more details.

How can I perform a check on all 'th' values using JQUERY?

I have create a function that adds rows based on value of a dropdown list.
The user selects a project, clicks the Add button, and a row with the name of the project and a set of cells are added to the table.
The name of the project is inside a 'th' tag.
I want to add a condition that the add button does not add a row if the project has already been added:
<script>
$(document).ready(function() {
var i = 1
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
/* table.find('th').each(function(){
if (th.value = projval)
alert("project already in");
});*/
$('#addrow').click(function() {
//Add row
var projval = $('#projSel').val();
$('#myTable > tbody > tr > th').each(function(index, th) {
console.log(index);
// if($("th").eq(index).attr('id') = projval) {
// alert("Exist");
// }
});
table.append('<tr><th scope="row" id="' + projval + '">' + projval + '</th>\
<td><input class="form-control" type="text" id="inMon' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inTue' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inWed' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inThu' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inFri' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inSat' + i + '" placeholder="00:00"></td>\
<td><input class="form-control" type="text" id="inSun' + i + '" placeholder="00:00"></td>\
<td><button name="remove" id="' + i + '" class="btn btn-danger btn_remove btn-sm" onclick="deleteRow(this)">X</td></tr>');
i++;
})
});
projVal variable is the value selected from the dropdown list
myTable is the ID of the table.
I cannot figure how to write the if condition so that the index retrieves the value of 'th' ID and compares it to the already exisiting 'th' added by user.
Check with the below code:
$('#addrow').click(function () {
var projval = $('#projSel').val();
var projectAdded = $('tr>th[scope=row][id="' + projval + '"]', table).length > 0;
if (projectAdded) {
alert('project already in');
return false;
}
// ... Add Row Code
i++;
})

How to edit array value using jquery?

I am trying to edit array values using jquery. here is what I did.
From a modal, everytime I click the "Add item" button it will push values to an array and just append the data to a table
var iteminfo = {
"row": 'row' + cnt,
"make": make,
"body": body,
"cabin": cabin,
"horsepower": horsepower,
"wheels": wheels,
"chassis": chassis,
"engine": engine,
"remarks": remarks,
"shipmenttag": shipmenttag
};
trucksarray.push(iteminfo);
//append to table:
$("#truckstable > tbody").prepend(<tr><td>.....</td></tr>);
and my html table looks like this:
now I am able to delete a table row and the corresponding data from the array with this code:
//removing the table row
$("#truckstable").on('click', '.remrow', function () {
var id = $(".remrow").attr("id");
$(this).parent().parent().remove();
removeitem(id)
});
//removing array item
function removeitem(row) {
const itemToRemoveIndex = trucksarray.findIndex(function (item) {
return item.row === row;
});
if (itemToRemoveIndex !== -1) {
trucksarray.splice(itemToRemoveIndex, 1);
}
toastr.warning('Item removed!');
}
Now, my problem is, If I click the edit button a modal should popup and be able to edit the selected item value , the table data and the array values as well? Any idea?
You can give data-* to your edit button i.e : data-id="row1"..etc then on click of this button get the data-id value and use filter to filter the JSON Array already created and get only data where row == data-id.
Now , once you got the array values put this values inside the input-box of modal using .val("yourfromarray"). Then, onclick of save button get the value from input box and loop through your JSON Array and update value of array with new values.Lastly add these updated value inside trs.
Demo Code :
var cnt = 0;
var trucksarray = [];
$('#BtnAddTruck').on('click', function() {
var make = $('#tmake').val();
var body = $('#tbody').val();
var cabin = $('#tcabin').val();
var horsepower = $('#thorsepower').val();
var wheels = $('#twheels').val();
var chassis = $('#tchassis').val();
var engine = $('#tengine').val();
var remarks = $('#tremarks').val();
var shipmenttag = 'Truck';
cnt = cnt + 1;
var iteminfo = {
"row": 'row' + cnt,
"make": make,
"body": body,
"cabin": cabin,
"horsepower": horsepower,
"wheels": wheels,
"chassis": chassis,
"engine": engine,
"remarks": remarks,
"shipmenttag": shipmenttag
};
trucksarray.push(iteminfo);
//added here `id` to tr and `data-id` to edit button
$("#truckstable > tbody").
prepend("<tr id='trow" + cnt + "'>" +
"<td>" + make + " " + body + " " + cabin + " " + horsepower + " " + wheels +
"</td>" +
"<td>" + chassis + "</td>" +
"<td>" + engine + "</td>" +
"<td>" + remarks + "</td>" +
"<td>" +
" <button class='btn-primary edit' data-toggle='modal' data-target='#myModal' data-id='row" + cnt + "'>Edit</button>" +
" <button class='remrow btn-danger' id='row" + cnt +
"'>delete</button>" +
"</td>" +
"</tr>"
);
//clearmodalinput();
$(".empty_k input").val("");
//toastr.info('Item added!');
console.log(trucksarray)
});
var id;//delcare this globally
//on click of edit
$(document).on('click', '.edit', function() {
id = $(this).data('id');//get id
console.log(id)
//filter json array and get value only where match
var trucks = $(trucksarray)
.filter(function(i, n) {
return n.row === id;
});
//put value inside input in modal
$('.make').val(trucks[0].make);
$('.body').val(trucks[0].body);
$('.cabin').val(trucks[0].cabin);
$('.horsepower').val(trucks[0].horsepower);
$('.wheels').val(trucks[0].wheels);
$('.chassis').val(trucks[0].chassis);
$('.engine').val(trucks[0].engine);
$('.remarks').val(trucks[0].remarks);
});
//click on save button
$(".save").click(function() {
//loop through array
$(trucksarray).each(function() {
if (this.row == id) {
//creplace value inside array
this.horsepower = $('.horsepower').val();
this.make = $('.make').val();
this.remarks = $('.remarks').val();
this.engine = $('.engine').val();
this.chassis = $('.chassis').val();
this.cabin = $('.cabin').val();
this.body = $('.body').val();
this.wheels = $('.wheels').val();
return false;//got it stop loop
}
});
replace_values(); //replace table datas
})
function replace_values() {
//get values
var make = $('.make').val();
var body = $('.body').val();
var cabin = $('.cabin').val();
var horsepower = $('.horsepower').val();
var wheels = $('.wheels').val();
var chassis = $('.chassis').val();
var engine = $('.engine').val();
var remarks = $('.remarks').val();
//replace trs values
$("#t" + id).html("<td>" + make + " " + body + " " + cabin + " " + horsepower + " " + wheels +
"</td>" +
"<td>" + chassis + "</td>" +
"<td>" + engine + "</td>" +
"<td>" + remarks + "</td>" +
"<td>" +
" <button class='btn-primary edit' data-toggle='modal' data-target='#myModal' data-id='" + id + "'>Edit</button>" +
" <button class='remrow btn-danger' id='" + id +
"'>delete</button>" +
"</td>")
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="empty_k">
<input type="text" id="tmake">
<input type="text" id="tbody">
<input type="text" id="tcabin">
<input type="text" id="thorsepower">
<input type="text" id="twheels">
<input type="text" id="tchassis">
<input type="text" id="tengine">
<input type="text" id="tremarks">
<button id="BtnAddTruck">Add</button>
</div>
<div class="table-responsive">
<table class="table table-bordered" id="truckstable">
<thead>
<tr>
<th scope="col">Description</th>
<th scope="col">Chassis</th>
<th scope="col">Engine</th>
<th scope="col">Remarks</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Edit..</p>
tmake : <input type="text" class="make"><br/> tbody : <input type="text" class="body"> <br/>tcabin : <input type="text" class="cabin"> <br/>thorsepower :<input type="text" class="horsepower"> <br/>twheels : <input type="text" class="wheels"><br/> tchassis :
<input type="text" class="chassis">
<br/> tengine :<input type="text" class="engine"><br/> tremarks : <input type="text" class="remarks">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default save" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

How can I display a profile stored in a database after a SQL query in a Google Spreadsheet Sidebar?

Basically here is what I'm doing:
Storing a person profile in a MYSQL Database
Creating a google spreadsheet add-on with a sidebar
giving to the user the possibility to search profiles through the DB in the add-on
giving to the user the possibility to display the datas of the profile in the Sidebar in the add-on
So Imagine you want to search John but the input you've entered in the searchbar is the letter J. The result of this query will be Jack , Johnatan, Jules, Joe and John as they all have a J. All this names will appear as link for you to click on in order to have more datas displayed (age, picture, fullname, description...). Only problem is that the only way I've managed to achieve is by making a SQL query after each keyup in my HTML input then create X numbers (in this case 5) of hidden classes with the infos, that I can show by clicking on a created link.
So this can easily work for 5 results, but imagine there's 100 of them and you only want to see one of them. Sounds crazy to create 100 hidden divs with all the infos to finally show only one.
here is an example code
code.gs
function onOpen(e) {
SpreadsheetApp.getUi().createAddonMenu()
.addItem('Start', 'showSidebar')
.addToUi();
}
function onInstall(e) {
onOpen(e);
}
function showSidebar() {
var ui = HtmlService.createHtmlOutputFromFile('UI_HTML');
SpreadsheetApp.getUi().showSidebar(ui);
}
//My function to search for profiles (returns an array with each lines found)
function searchProfile(entry){
var address = 'sql3.freemysqlhosting.net';
var user = 'user';
var userPwd = 'password';
var db = 'sql12345678910';
var instanceUrl = 'jdbc:mysql://' + address;
var dbUrl = instanceUrl + '/' + db;
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.createStatement();
var ret = [];
var res = stmt.executeQuery('SELECT * FROM item WHERE name = "' + entry + '"'
+ ' OR fullname LIKE CONCAT("%", "' + entry + '", "%")'
+ ' OR description LIKE CONCAT("%", "' + entry + '", "%")');
var numCol = res.getMetaData().getColumnCount();
var i = 0;
var j = 0;
while (res.next())
{
j = 0;
if (!ret[i])
ret[i] = [];
while (j < numCol)
{
ret[i][j]= res.getString(j + 1);
j++;
}
i++;
}
return (ret);
}
UI_HTML.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.show {
display: block;
}
.hide {
display: none;
}
</style>
</head>
<body>
<div>
<p>Search Profile</p>
<input type="text" id="searchProfile" onkeyup="searchProfileHTML()" placeholder="Search for ...">
<div id="results" ></div>
</div>
<script>
function searchProfileHTML()
{
var x = document.getElementById("searchProfile").value;
google.script.run
.withSuccessHandler(createLinks)
.searchProfile(x);
function createLinks(result)
{
$('.links').remove();
if (!x)
return (0);
$('#results').append('<ul></ul>');
$('#results ul').addClass('links');
result.forEach(function(el){
//My Link to show/hide my Div
$('.links').append('<li><a id="' + el[0] + '-link" href="#">' + el[0] + '</a><div id="' + el[0] + '" class ="hide" ></div></li>');
//My div with all the infos (hidden by default)
$('#' + el[0]).append(""
+ '<img src="' + el[14] + '" height="100" width="100">'
+ "<div>"
+ "<ul>"
+ "<li>Name: "+ el[0] + "</li>"
+ "<li>Full name: "+ el[1] + "</li>"
+ "<li>Description : "+ el[2] + "</li>"
+ "<li>email: "+ el[3] + "</li>"
+ "</ul>"
+ "</div>");
$('#' + el[0] + '-link').on("click", function(){
$('#' + el[0]).toggleClass("hide show");
})
});
}
}
</script>
Anyone has an idea how I can make this more lite?

Auto select the check box in rows

I am displaying table rows in the form. Each row has 5 columns, one of the columns is an (editable) textbox field.
ajaxLoading(true);
$.post('<%=request.getContextPath()%>'+"/processServlet", postData,
function(data) {
var ctxPath='<%=request.getContextPath()%>';
currentPosition = data.currentPosition;
var items = $("#itemsTable");
items.empty();
if (data.items.length == 0) {
items.append($('<tr><td colspan=5 style="color:red;">No items<td></tr>'));
}
;
for (var i = 0; i < data.items.length; i++) {
editText = "";
items.append($("<tr " + zebra + "><td><a href=\"javascript: deviceView('" + data.items[i].id + "')\">" + data.items[i].num +
"</a></td><td>" + data.items[i].itemType +
"</td><td><input type = 'checkbox' id = 'CheckBoxRow_' />" + data.items[i] +
"</td><td><input type = 'textbox' id = 'TextBoxRow_' value = '" + data.items[i].itemName +"' "/>" +
"</td><td>" + data.items[i].status +
"</td><td>" + data.items[i].date + "</td>" +
"<td>" + data.items[i].firmware + "<td>" +
"Delete" +
"</tr>"));
;
ajaxLoading(false);
}, "json");
How do I auto select the check box when the data is entered or modified in the textbox and save the data in the database?
bind to textbox onchange event and have it set the checkbox to checked=true once returned with a value (and not already checked).
$('#itemsTable input[type="checkbox"]').change(function(e){
var $cb = $(this);
if ($cb.is(':checked')){
$cb.closest('tr').find('input[type="checkbox"][id^=CheckBoxRow_]').prop('checked','true');
}
});
basically. though you really should not use HTML in an append, and should be building the objects with jQuery.