Dynamic HTML Elements using data from a Database - javascript

I am currently trying to create a website that dynamically displays items when a certain Make, Model, Year is chosen using dropdown lists. The item information was retrieved using web crawling which utilized the HtmlAgilityPack.
So I currently have a database table that is full of thousands of items which contain the columns: id, Make, Model, Year, PartCategory, PartUrl, ImageUrl, PartBrand, PartName, PartPrice.
What I'm attempting to do is separate each site into divs so the user can easily tell which site the item they are looking at is from. Example:
<div id="siteOne">
<table>
<tr>
<td>
<img url="ImageUrl">
PartBrand & PartName & PartPrice
</td>
</tr>
<tr>
<td>
<img url="ImageUrl">
PartBrand & PartName & PartPrice
</td>
</tr>
</table>
</div>
<div id="siteTwo">
.............
</div>
<div id=""siteThree>
.............
</div>
I am currently only using three sites total, and I can easily pull the data into a DataTable and then see how many rows were returned, so that number will be how many dynamic instances I need to create. I'm pretty sure Jquery can handle this job, however I cannot find any examples of people using a DataTable's DataRows to control the dynamic part, usually it is with a button event or something of the sort.
I imagine the code will look something like this:
//this foreach statement will be in the last dropdown list's SelectedIndexChanged event
//when the last dropdown is chosen, a datatable will be returned with all the items that match that particular make/model/year
foreach (DataRow tempRow in tempDataTable)
{
//this should pull data from each column one at a time
//column: 0 = id, 1 = Make, 2 = Model, 3 = Year, don't think I'll need these right now
string partCategory = tempRow[4].ToString();
string partUrl = tempRow[5].ToString();
string imageUrl = tempRow[6].ToString();
string partBrand = tempRow[7].ToString();
string partName = tempRow[8].ToString();
string partPrice = tempRow[9].ToString();
//this is where the jquery would generate the dynamic elements in the table.
//three main divs can be hard coded for now, only using 3 sites currently
//this means the <table></table> in each will most likely be hard coded as well
//the <tr></tr>, <td></td>, <img>, and <a></a> will need to be generated dynamically each loop iteration
}
I've been working on this one step for a while so I figured I would post to see if anyone had any tips or similar examples while I continue to try and solve it myself. Anything would be greatly appreciated. Cheers!

I figured it out, and its quite easy.
heres how my function is setup
protected void drpdwnYear_SelectedIndexChanged(object sender, EventArgs e)
{
//get the data for the specific make/model/year from the database
DataTable dt = new DataTable();
string tempYear = drpdwnYear.SelectedItem.ToString();
string tempManufacturer = Globals.myManufacturer;
string tempModel = Globals.myModel;
Globals.myQuery = "SELECT * FROM CrawlerInfo WHERE Model = '" + tempModel + "' AND Year ='" + tempYear + "'";
try
{
using (SqlConnection con = new SqlConnection(Globals.myConStr))
{
using (SqlCommand cmd = new SqlCommand(Globals.myQuery, con))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}
catch (Exception ex)
{
handleTheError(ex);
}
//put the data into HTML elements
try
{
int tempflag = 0;
foreach (DataRow tempRow in dt.Rows)
{
string tempCategory = tempRow[4].ToString();
string tempPartUrl = tempRow[5].ToString();
string tempImageUrl = tempRow[6].ToString();
string tempPartBrand = tempRow[7].ToString();
string tempPartName = tempRow[8].ToString();
string tempPrice = tempRow[9].ToString();
string tempStoreName = tempRow[10].ToString();
Image tpImg = new Image();
tpImg.ID = "id_img_" + tempflag;
tpImg.ImageUrl = tempImageUrl;
Page.Controls.Add(tpImg);
HyperLink hyp = new HyperLink();
hyp.ID = "id_link_" + tempflag;
hyp.NavigateUrl = tempPartUrl;
hyp.Text = tempPartBrand + " " + tempPartName + ": " + tempPrice + "\n\n";
Page.Controls.Add(hyp);
tempflag++;
}
}
catch (Exception ex)
{
handleTheError(ex);
}
}
and here hows it displays currently, I just need to figure out how to put them into <div>s so I can style them.

Related

Button not firing the third time - ASP.NET code behind C#

I have written a code for button click that should retrieve data from the database and display the data row wise as required. It is working Fine for the first two clicks and it is not firing for the third time... I really don't understand why Please any help.
thank you in advance
The button code
protected void NextButton_Click(object sender, EventArgs e)
{
c++; //integer created to iterate through rows of datatable
qno++; //just counts the rows begining from 1 and displays on page
SqlCommand lque = new SqlCommand("select * from questions where course='" + cour + "' and [group]='" + gr + "' and semester='" + sem + "'", con);
IDataReader rque = lque.ExecuteReader();
if (rque.Read())
{
DataTable dt = new DataTable();
dt.Load(rque);
QuestionNo.Text = Convert.ToString(qno);
Question.Text = dt.Rows[c].Field<string>(4);// only displaying the required columns.
RadioButton1.Text = dt.Rows[c].Field<string>(5);
RadioButton2.Text = dt.Rows[c].Field<string>(6);
RadioButton3.Text = dt.Rows[c].Field<string>(7);
RadioButton4.Text = dt.Rows[c].Field<string>(8);
}
}
source code for the button
<asp:Button ID="NextButton" runat="server" Text="Next" Width="111px" OnClick="NextButton_Click" />
i also checked the data is loaded without any errors into the datatable by passing the datatable as a source to the gridview, it shows all the rows in gridview but in the labels the first 2 rows only displaying. I also chekced the counting varible is only increasing 2 times.enter image description here
a few rows from the table that i am retrieving
Your variables(c for example) will be reset to 0 on every request(button-click). Http is stateless. So you need to persist this value somewhere else(i.e. Session, ViewState, Hiddenfield, etc).
For example with Session, which you should only use if this site has not too much traffic:
private int CurrentRowIndex
{
get
{
if (Session["CurrentRowIndex"] == null)
Session["CurrentRowIndex"] = 0;
return (int)Session["CurrentRowIndex"];
}
set => Session["CurrentRowIndex"] = value;
}
protected void NextButton_Click(object sender, EventArgs e)
{
int currentRowIndex = ++CurrentRowIndex;
// maybe you need this also for your other variables
// ...
}
You should also not read all rows if you only want one, you should modify your sql query. If you use MS SQL-Server you could use ROW_NUMBER function to select only the required row from DB.

Need help to add javascript array contents to an existing piece of HTML code

My front-end skills are fairly limited. I have a trained language model which generates 'tweets'.
I have this javascript function which currently displays the tweets as a paragraph.
function addResponse(msg) {
document.getElementById("results").textContent = ""
var para = document.createElement("div");
var s = "<div class='center' id='gpt2'> <b> Here what our BOT has to say... </b> </br></br>"
i = 1
for (var key in msg){
var value = msg[key];
console.log(value);
s = s + i + ") " + " <b>" + value + "</b> </br></br>"
i = i + 1
}
para.innerHTML = s + "</div>";
document.getElementById('append').appendChild(para);
}
Instead of displaying in a paragraph, I want to display as a proper tweet.
Here is a tailwind CSS implementation to create the UI of the tweet: https://codepen.io/webcrunchblog/pen/xedQVv
Currently this displays a fixed string "Starhopper". What I want to do is, loop through my array object 'msg' and display all the tweets with the proper UI .
Currently the addResponse() is called as part of ajax callback for successful response. From there how can I include the tailwind CSS code so that I can display every array element in its own tweet UI?
Hope the question is clear.
EDIT: Created this codepen if anyone wants to try it out: https://codepen.io/nikhilno1/pen/RwPBWvb
In the output, there is a tweet and three sentences. I want 3 tweets to be created for each of the sentence.
I've updated a bit of your code here: https://codepen.io/rxna/pen/OJVwMOm
The idea is to:
Clone the tweet element, have added a custom class for that:
var articleNode = document.querySelector(".tweet-body");
var clone = articleNode.cloneNode(true);
Update the text within each element:
var title = clone.querySelector(".tweet-text");
title.innerText = value;
And lastly append within the DOM:
document.getElementById("append").appendChild(clone);
It's not perfect but hopefully you'd get the idea.

Modify innerHTML for table row in javascript in ie8?

I am trying to add create an editable table in HTML. So, I need to add rows, when user clicks on a button. Here is the code I am using.
//remove all old rows.
while (summaryTableElement.firstChild) {
summaryTableElement.removeChild(summaryTableElement.firstChild);
}
//add a new text area in the summary field.
summaryTableElement.innerHTML = "<textarea id='summaryTextBox' value='' onblur='saveSummary()'> </textarea> ";
This code works fine on Chrome and Mozilla. But, IE doesn't allow editing innerHTML. This HTML will be displayed inside a VB form, so I have "browser" and "webbrowser" controls available. Both of those controls use IE engine, so this code does not work there.
I have tried using firstchild.innerHTML instead so that I am not editing table row directly, and even that gave me same error.
I tried using WebKitBrowser. But, that causes an exception on load. Apparently that control uses some old method, and the method is changed. So, that control is out of question too.
Now, I am confused as to how to solve this problem?
Edit:
I found the issue with WebKitBrowser. It was specific to x86, while my project was targeting both x64 and x86. Switching it to x86 for both, worked. Although, webkit browser do not take return key values. So, I have a new problem. Pressing enter does not create a new line in table cell, and instead passes the event to vb form.
Edit:
Okay, so I tried working further with WebKitBrowser. But, that control gives me accessviolatedexception. So, I am thinking about going back to using the default browser control, for now.
As for default control, I checked further. Apparently, code works fine in IE9 and above. But, vb.net control uses some weird JS engine. So, I am receiving error only in vb control.
Here is the complete code for reference:
var summaryChanges = "";
var isSummaryClickable = true;
//creates a textbox for editing purpose and include the original summary data.
function modifySummary(id) {
var summaryTableElement; //to get the table cells so that we can access the value
var originalSummary = ""; //to hold the original summary while we create a text box
var loopCounter = 0;
if (isSummaryClickable == true) {
isSummaryClickable = false; //saves event spilling when clicked on the newly created textbox
//get the summary table id saved.
summaryTableElement = document.getElementById (id).childNodes.item(0);
//add existing data to a string to save it for later.
for (loopCounter = 0; loopCounter < summaryTableElement.childNodes.length; loopCounter++) {
originalSummary = originalSummary + summaryTableElement.childNodes.item(loopCounter).childNodes.item(0).innerHTML + "\n";
}
//remove all old rows.
while (summaryTableElement.firstChild) {
summaryTableElement.removeChild(summaryTableElement.firstChild);
}
//add a new text area in the summary field.
summaryTableElement.innerHTML = "<tr><td><textarea id='summaryTextBox' value='' onblur='saveSummary()'> </textarea></td></tr> ";
//set the width of the textbox to allow easy modification
document.getElementById("summaryTextBox").style.width = '600px';
//add original summary text to the text area and set focus
document.getElementById("summaryTextBox").value = originalSummary;
document.getElementById("summaryTextBox").focus();
}
}
// saves the updated summary data back to HTML
function saveSummary()
{
var newHTML = "";
var changesSummary;
var changesSubString = new Array();
var index = 0;
var elementToUpdate;
//get the summary table id saved.
elementToUpdate = document.getElementById("SummaryData"); //.childNodes.item(0);
//get changes from the textbox
changesSummary = document.getElementById("summaryTextBox").value;
//generate string array for separate lines from summaryChanges
changesSubString = changesSummary.split("\n");
//generate new HTML string for the summary fields
//alert(changesSubString.length);
for (index = 0; index < changesSubString.length; index++) {
newHTML = newHTML + "<tr><td class='Text' style='padding-left: 4px;padding-bottom: 4px;' id='SummaryLine" + index + "'</td>" + changesSubString[index] + "</tr>"
}
//update the HTML to the element
elementToUpdate.innerHTML = newHTML;
//allow clicking on summary table
isSummaryClickable = true;
}
function doNothing(id) {
//empty function for future use
return;
}
//this function is called from vb.net script to read the js variable.
//do not change the function definition (name or parameters or return type)
//any change will cause error in vb.net script
function jsInvokedFunction() {
var updatedHTML; // to be used by vb.net invoked function to get updated body
var testVariable = "test";
updatedHTML = document.body.innerHTML.toString();
return updatedHTML.toString();
}
I receive an error at the start of the line summaryTableElement.innerHTML = " ";
It is possible I am missing some other error, but I couldn't find any.

How to get client id for grid view from inside a view to use in javascript

I have a grid view that I want to use with JavaScript to calculate values entered in the textboxes.
I was adding onkeyup to the textboxes in the onrowcreated function and it was working fine.
Then I put the gridview in a multiview, and it stopped working.
This is my JavaScript function:
function margin1(rowIndex, price, gridId) {
var grid = document.getElementById(gridId);
var volumeQuota = grid.rows[rowIndex].cells[2].innerText;
alert(volumeQuota);
var coef = grid.rows[rowIndex].cells[5].childNodes.item(1).value;
alert(coef);
var prevSites = grid.rows[rowIndex].cells[4].innerText;;
grid.rows[rowIndex].cells[6].childNodes.item(1).value = parseFloat(coef) * (parseFloat(volumeQuota) - parseFloat(prevSites));
grid.rows[rowIndex].cells[7].childNodes.item(1).value = price;
}
and in the code behind this is how im adding it.
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox t1 = (TextBox)e.Row.FindControl("p98Margin1");
t1.Attributes.Add("onkeyup",
string.Format("javascript:margin1('{0}', {1}, {2})", e.Row.RowIndex + 2, a98.Text , GridView1.ClientID));
when I alert Gridview1.clientId in the JavaScript function I'm getting [objectHTMLTableElement]
use this
t1.Attributes.Add("onkeyup",
string.Format("javascript:margin1('{0}', '{1}', '{2})'", e.Row.RowIndex + 2, a98.Text , GridView1.ClientID));
I think this should work.
I think the value should go in single quotes ' mark.
Like you said you put your grid in a multiview and everything stopped working,which means your gridview has been buried and you need to drill down a bit further to expose it.
Do this
GridView myGridView=(GridView)(MultiView1.FindControl("GridView1"));
Now you have located it gracefully reference its ID
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox t1 = (TextBox)e.Row.FindControl("p98Margin1");
t1.Attributes.Add("onkeyup",
string.Format("javascript:margin1('{0}', {1}, {2})", e.Row.RowIndex + 2, a98.Text ,myGridView.ClientID));
}
Hope this helps.

Is there a limit of the size of data using replaceWIth in jQuery?

I am using the replaceWith() function in jQuery to update my web page. I receive the data from a C# web service program that extracts data from a database to build my HTML code. It works fine except when I replace large amounts of data. In the example that's not working, I replace code in my web page with 39000 bytes of data. After that, none of my links work when clicking on a span to calls a JavaScript function. Is there a limit on the size of data used in the replaceWith() function? The html code I am replacing looks like this:
<td align=left valign=top>
<div id="showitems" class="showitems" style="display:inline; float:left"></div>
</td>
The javascript code looks like this:
function ShowDinerItems() {
var gps = document.getElementById("selectdiner").value;
var pos = gps.indexOf(";");
var len = gps.length;
var latitude = document.getElementById("Hiddenlat").value;
var longitude = document.getElementById("Hiddenlng").value;
var dinerkey = gps.substring(0, pos);
PageMethods.CallShowDinerItems(dinerkey, latitude,longitude, OnShowDinerComplete, OnShowDinerError, dinerkey);
}
function OnShowDinerComplete(result) {
var htmlcode = result[0];
if (result == 'none') {
document.getElementById("Message").value = "Search returned no items";
}
else {
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
var locations = result[1].split(";");
var lat = locations[0];
var lng = locations[1];
markDiner(lat, lng, "", 'map_canvas');
}
}
The reason I am using jquery to build my webpage is to avoid page reloads. I could easily program the webdata content in my C# program which may be more efficient but page reloads are to be avoided as dictated by the people who own the website. I am will try the recommendations given.
Note: I used the following code to make it work.
$('.showitems').html(result[0]);
Using .text will not work as it displays raw data and not html data. Thanks to those who contributed.
To be honest I think you're going about this the wrong way here.
It seems to me that you're using ReplaceWith to completely overwrite the matched tag when you could just as simply change its properties with jQuery.
For example:
var htmlcode = result[0];
htmlcode = "<div id=\"showitems\" class=\"showitems\" style=\"display:inline\">" + htmlcode + "</div>";
$('.showitems').replaceWith(htmlcode); // size of htmlcode is 39849 bytes
Could easily be changed to this:
$('.showitems').css('float','none').text(result[0]);
Just how many showItems are there going to be by the way, and how do you know how it compares to how many results you get back from the C# call ?
Edit 2: Sorry, didn't realise that the CSS display attribute wasn't actually changing.

Categories

Resources