Accessing objects/rows created in ASP.NET from Javascript - javascript

I create a table dynamically and add rows, labels etc to it.
I want to be able to access those rows to make either visible or hidden AND access labels to change content on the fly. So far the table and all info is created with no problem. I spent days trying to access the data from JS, but I keep getting NULL etc on objects using ALERT to test it. Here's a snippet example of my code...
ASP.NET (C#) code
mTable = new HtmlTable();
mTable.ID = "mTable";
aCell = new HtmlTableCell();
aLabel = new Label();
aLabel.ID = "aLabel";
aLabel.Text = "TEST";
aCell.Controls.Add(aLabel);
aRow = new HtmlTableRow();
aRow.ID = "r" + x;
aRow.Cells.Add(aCell);
mTable.Controls.Add(aRow);
Ive put the following code in a SCRIPT FILE etc and ive tried many styles.
alert(document.getElementById('<%=aLabel.ClientID%>'));

If you are using plain vanilla javascript, please look at the code sample here: How do I iterate through table rows and cells in javascript?
The code sample in the above link gets the table by id, which in your case is 'mTable' (from your c# code)
var table = document.getElementById('mTable');
// will return you a reference to the table object on the page
You also have to place the code to call your javascript function that accesses data on the 'mTable' on the document load event

Related

Issue with ng-html-compile displaying UI-Grid twice while rendering saved HTML from SQL Server Database

1)I am saving entire DIV - TestDIV from a HTML page in AngularJS to SQLServer database.
2)TestDIV has many DIVs nested inside it, including UI-Grids.
3)I save the HTML as a VARCHAR(MAX) column in SQL Server. I am able to save and retrieve the HTML correctly.
4)On page - Test.HTML - I have a another DIV - with ID = TestDIVDisplayed
5)I am assigning saved HTML to TestDIVDisplayed using ng-html-compile. Basically setting ng-html-compile to HTMLBindValue
6)This seems to work, with an issue esp. with UI-Grid. The UI-Grid is displayed twice, instead of once. Something similar to the following -
7)The assignment is done the following way in JavaScript code -
var toChg = 'TestDIVDisplayed';
var btn = document.querySelector('#' + toChg);
btn.setAttribute("ng-html-compile", "HTMLBindValue");
var el = $(btn);
$compile(el)($scope);
$scope.mySidenav = entity.DivSavedInSQLServerDatabase; //Getting the entity.DivSavedInSQLServerDatabase from a WebAPI service call.

Jquery <<S.fn.init [selector]>> in Java Script Vanilla

For this project, I want to change the logic written in jquery with that in js vanilla.
My code looks like this
Based on the information from the input using the event keydown,
I call a function through which I do a search in api.
var selectedUsers = [] //empty array
$('#userSearchTextbox').keydown((event)=>{
var textBox = $(event.target);
var value = textBox.val();
//Function which search in api
searchUsers(value);
});
//Search in array function
function searchUsers(searchTerm){
$.get("/api/users",{search:searchTerm},results =>{
outputSelectableUsers(results,$('.resultsContainer'));
});
}
After I call another function outputSelectableUsers
which will call 2 functions one that displays the data in HTML and one that creates an array of values.
function outputSelectableUsers(results,container){
results.forEach(results => {
//Call function which will render the html
var html =createUserHtml(results,false);
/*
Here is the problem, as seen using jquery element variable selects html variable which render function
*/
var element = $(html);
/*
with jquery, I managed to select the variable and assign it a click event that when I click it calls the function that adapts the array with data
from each API call
*/
element.click(()=>userSelected(results))
//append content to the html selector
container.append(element);
});
}
//Function which will update the array
function userSelected(user){
selectedUsers.push(user);
}
This is what the visible result looks like
And when I click on one of the cards, the area adapts to the user's values.
values ​​that I take from the array and enter them in the database.
I managed to convert everything to js using fetch instead of ajax jquery and changed the selectors and events with vanilla js code.
But the problem is I couldn't find a way to change this piece of code.
var html =createUserHtml(results,false);
var element = $(html);
console.log(element)
element.click(()=>userSelected(results))
container.append(element);
at consol.log (element) I observed asata in the console.
The question is could I choose the element with js vanilla and get the same result as in the jquery version. To use Js Vanilla code instead of
var element = $(html);
element.click(()=>userSelected(results))
let users_id = results._id;
let html = createUserHtml(results,users_id ,false);
container.insertAdjacentHTML('beforeend',html);
//Identify each element by a unique selector
document.querySelector(`[data-selectorTab ="${results._id}"]`).addEventListener('click',()=>{
userSelected(res)
})
I solve this by adding a data attribute to dinamically generated elements,using this data atribute I can make a individual selector for each user.

oData binding to table generates repeated lines in table output

I have an OData connection using which I read an entityset with conditions that returns me data in the following structure. The data being in the root node itself rather than in an object array-
oData Structure
I am then setting this data to a JSON Model and binding this model to my oTable.
The code in controller looks something like below-
//Get data for the table
var oTabData = sap.ui.getCore().byId("MyTable");
var sServiceUrl = "http://example.com/sap/opu/odata/SAP/ZXX_SRV";
var oModel2 = new sap.ui.model.odata.ODataModel(sServiceUrl,true);
var oJsonModel = new sap.ui.model.json.JSONModel();
oModel2.read("/MyEntitySet(Myvar1='000001',Myvar2='abc')?
$format=json",null,null,true,function(oData,response){
oJsonModel.setData(oData);
});
oTabData.setModel(oJsonModel);
The view contains the table and the binding is as below. Have ignored rest of table declaration code to keep it short. Table declared as oTable with id MyTable and with all the right columns-
//Template to map the data to the respective column
var template = new sap.m.ColumnListItem({
id:"table_template",
type: "Navigation",
visible: true,
cells:[
new sap.m.Label({
text: "{/Myvar1}"
}),
new sap.m.Label({
text: "{/Myvar2}"
}),
new sap.m.Label({
text: "{/Myvar3}"
}),
new sap.m.Label({
text: "{/Myvar4}"
})
]
});
var oFilters = null;
oTable.bindItems("/",template,null,oFilters);
The issues are-
As I have made a service call with conditions the oData output
received does not output an array of data like it does when we make
a call without conditions
(oModel2.read("/MyEntitySet?$format=json",null,null,true,function(oData,response)).
In the latter case the output comes under results array for which
the binding assignment is /results and that works right as expected.
In current case (service call with conditions), as the columns in
output are available right in the root level, have used binding /
and in template as well using / in front of every element (e.g.
{/Myvar1} as seen above). But using this technique it also creates 3
default blank lines in table initially. When the above controller
code is executed, it fills the table 3 x 4 times i.e. 12 rows for a
single row output.
Due to organization restrictions I cannot put the original code here. But this is how the scenario is. Any help would be appreciated.
Thanks.
PS: Haven't used any loop that would generate the repeated lines.
You can bind your table directly to the ODataModel:
Steps:
Before doing binding, you need to create a template for the table rows, in sap.m.Table it is ColumnListItem control, I would suggest to carry it out to the XML fragment. Try to use XML for markup as much as possible, becasue it much clearer and maintainablier than js coding;
All the controls in "cells" should be bound to the rows' properties using relative paths.
Tell the View about your model by calling "oView.setModel(MODEL_INSTANCE)", by this line you set the default model to the view. From now on all the controls inside are able to see it. The model is default because the name of it was not specified.
oTable.bindItems("/MyEntitySet", { template: oColumnListItem, filters: aFilters}); - this will automatically trigger an OData call to grab all needed data. The table will be updated automatically. You should see the rows.

Save dynamic data created using createElement(Javascript) to database

I am new to this forum as well as webpage designing. I am trying to design a profile management tool using JSP in which there are dynamically added(through javascript createElement) input fields to which names are assigned. I am able to save only one record to database and others are ignored.
My question is how to save all the data that is dynamically added?
Please help me on this.
Javascript code:Using the below function, I am able to get Javascript array
function addedu()
{
$(document).ready(function(){
$(".ed").each(function(input){
var value = $(this).val();
var id = $(this).attr('id');
t= id+' : '+ value;
arr.push(t);
});
});
var newinput1 = document.createElement("input");
newinput1.name="i1"
newinput1.className="ed"
newinput1.id="Education"
newinput1.innerHTML = "";
document.getElementById('edu').appendChild(newinput1);
}
JSP code:
String edu1=request.getParameter("i1");
Statement st1=con.createStatement();
String sql1="insert into education values('"+pno+"','"+edu1+"');
st1.executeUpdate(sql1);
On the client side you can use jQuery to dynamically add rows and read necessary values. To access the rows of the table you can use jQuery selectors. Then save the data in the JavaScript array, convert it to JSON and send it to the server side.
Here is an example (with using PHP, but in this case it doesn't matter):
Store HTML Table Values in a Javascript Array and Send to a PHP Script Using jQuery and Ajax
On the server side you'll need to make a lot of inserts via plain JDBC, use BATCH insert instead of hitting database once for each insert statement.
Here is an example:
Java: Insert multiple rows into MySQL with PreparedStatement
If you'll decide to use Spring, here is an example:
How to Insert multiple rows from web form into database using java spring framework

Databinding to Windows 8 ListView

I'm having massive problems with databinding to a ListView in a Windows 8 app using Javascript.
Inside the "activated" event on default.js I have written some code to get some data from a web service and push it into an array. This bit works OK and the array is populated.
The problem I have is that the app won't recognise the data. I have this code in a page called inspections.html:
data-win-options="{itemTemplate: select('#imageTextListCollectionTemplate'),
itemDataSource: dataList.dataSource,
layout: {type: WinJS.UI.ListLayout}}
and then in the "activated" event I declare:
var dataList = new Array();
and push the data from the web service into this array. But at runtime I get an error that says something along the lines of "can't find dataSource on undefined dataList".
I've done some of the examples on the MS website and in one of them it creates a dummy dataset and references it from a namespace. I kinda think that what I'm missing here is a namespace too but I don't know what the namespace for default.js is. Or maybe I'm wrong and it's something totally different.
Please help - this is so fundamental (and should be easy) but I can't get my head around it.
Do you want to create datalist in HTML or javascript?
It seems you want to create it from JavaScript. Assuming that you have already pushed your data into array from your webservice, you only need to call:
var dataList = new WinJS.Binding.List(array);
now accessing dataList.dataSource is perfectly valid.
Also, to create the datalist you don't always need an array. You could probably start with an empty list and then keep inserting data directly into the data list from web services, like:
var dataList = new WinJS.Binding.List([]);
dataList.push(value1);
dataList.push(value2);
...
Hope it helps. Let me know if you have any more questions.
If you are getting troubled by assigning datasource in HTML side
Prefer js side like
var list = new WinJS.Binding.List(array here);
listView.itemDataSource = list.dataSource;
by using this you can easily go through the data which you are binding to ListView.

Categories

Resources