I'm creating a dynamic menu that fetches dishes from a database and displays them to the user so he can add them to his order. Whenever I retrieve a row from the database I send it to my menuItems class so the columns can be read and the display format is created and inserted into a cell:
foreach (DataRow dr in drc){
//extract the dish data from the row into a cell
TableCell c1 = menuItem.makeItemCell(dr);
//display it
tr.Controls.Add(c1);
table1.Controls.Add(tr);
}
c1 will be a cell that has the dish information along with a quantity dropdownlist and an "add to order" button:
public static TableCell makeItemCell(DataRow dr)
{
TableCell tc = new TableCell();
Image img = new Image();
img.ImageUrl = (string)dr["img"];
tc.Controls.Add(img);
//rest of information adding is omitted for brevity
String myLiteral = "<p>" + "Name: " + (string)dr["NameofDish"] + "</br>";
tc.Controls.Add(new LiteralControl(myLiteral));
//add quantity label and dropdownlist populated with possible quantity values
Label lb = new Label();
lb.Text = "Quantity: ";
DropDownList ddl = new DropDownList();
for (int i = 0; i < 13; i++)
{
String t = i.ToString();
ddl.Items.Add(new ListItem(t, t));
}
//create the add to order button
Button btn = new Button();
btn.Text = "Add to order";
tc.Controls.Add(lb);
tc.Controls.Add(ddl);
tc.Controls.Add(btn);
return tc;
}
My problem is with handling the button click event. All my tries to bind it with an event handler (on the menuItems class or the codebehind itself) have failed. I could only manage to update the postbackURL of the button when it's created in the cell like this
btn.PostBackUrl = "./menu.aspx?dish=" + (string)dr["ID"] + "&quantity=" + ddl.SelectedValue;
But the .selectedvalue value is rendered when the cell is created hence is always 0
My question is this: how can I handle the button click event in a way that I can get hold of the dishID and the selected value.
((((I would prefer an event handling solution rather than querystrings if possible))))
Thank you!
EDIT:
My whole problem is that the cell and its components are created in the external class and sent back to my code. How do I access the dropdownlist variable from my codebehind if I don't have the element id or anything
Related
I have created a dynamic table in html click here to view image the rows are created dynamically in javascript please refer the image click here to view image the data for table is fetched from firebase.
The problem I am facing is that the rows are getting added at the end of the table repeatedly resulting in duplicate rows please refer the image click here to view image how do I remove old rows and add new updated rows using javascript.
I have updated the snapshot.forEach loop with comments.
snapshot.forEach(function (data) {
var val = data.val();
var trow = document.createElement('tr');
var tdata = document.createElement('td');
var tdata1 = document.createElement('td');
tdata.innerHTML = val.Name;
tdata1.innerHTML = val.Votes;
trow.appendChild(tdata);
trow.appendChild(tdata1);
// set the Name as data-id attribute
// which can be used to query the existing row
tdata.setAttribute('data-id', val.Name);
// append the trow to tbdy
// only if there's no row with data-id value of val.Name
// otherwise update the vote column of the existing row
var existingRow = tbdy.querySelector('[data-id="' + val.Name + '"]');
if (!existingRow) {
tbdy.appendChild(trow);
} else {
existingRow.querySelectorAll("td")[1].innerHTML = val.Votes;
}
});
I am quite new to javascript and for some time now i cant figure a solution to a problem that i have on my own. The web application i am building is using javavascript and Firebase. I am creating a table that pulls some data from mysql and display them as a table in my website. The table consists of three columns ID,NAME, AND SURNAME.Along with that i am also creating a new column called Recipient that consists of buttons. The table looks like this:
I give a different value to each of the buttons, the value of each button is the number of the ID that is in the same row as the current button. For example the first button has a value = 2, the 3rd a value = 123. Al the buttons have an id = contact
The source code of the table is
$con = mysql_connect("localhost","root",'');
if(!$con){
die("Cannot Connect" . mysql_error());
}
mysql_select_db("client_app",$con);
$get_user_clients = "SELECT `ID`,`Name`,`SurName`,`storagefolder` FROM `clients` ";
$clients = mysql_query($get_user_clients,$con);
echo "<table class=table table-condensed>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>SurName</th>
<th>Recipient</th>
</tr>
</thead>";
while($record = mysql_fetch_array($clients)){
echo "<action=usersfiles.php method=post>";
echo "<tr>";
echo "<td>".$record['ID']." </td>";
echo "<td>".$record['Name']." </td>";
echo "<td>".$record['SurName']." </td>";
echo "<td>"."<button value=".$record['ID']." id=contact>Folder Data</button>"." </td>";
echo "</tr>";
echo "</form>";
}
echo "</table>";
When i click on a button from the table the application get the value of the corresponding button and store it in a variable, then it sends the variable to a function that will drug all the files from firebase database that are store in the folder with the same name as the variable, And then it will display them.
My firebase Database
So for example when I click on the button of the first column I will get the files that are stored in the folder with name 2 form firebase.database. The result of after I click the first button will be this:
My source code works fines as it gets the files from the corresponding folders from firebase.database. The problem that i have is when i dont refresh the page and i click a button again then the outpout will be the result of the previous button click plus the new one. For example if i dont refresh my page and i click the second button to get the files from the file from database with the name = 3 the outpout will be :
The outpout is a merging of all the results that i have oupouted so far. If i refresh my page and click on the second button now i will get the result i want which it is:
How can i edit my source code so the tables wont merge?
My source code is the follwing:
Source code of saving the value after button is clicked and passsing it to function:
var contactName; //prepare var to save contact name/ PLACE outside document ready
$(function() {
// contact form animations
$('button[id="contact"]').click(function() {
contactName = $(this).val(); //set var contactName to value of the pressed button
store(contactName);
$('#contactForm').fadeToggle();
})
$(document).mouseup(function (e) {
var container = $("#contactForm");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.fadeOut();
}
});
});
Source code of function receiving the value and displays the corresponding file from firebase database:
function store(value){
var tblUsers = document.getElementById('tbl_users_list');
var databaseRef = firebase.database().ref().child(`files/${value}/`);
var rowIndex = 1;
databaseRef.once('value',function(snapshot){
snapshot.forEach(function(childsnapshot) {
var childKey = childsnapshot.key;
var childData = childsnapshot.val();
//var urls = childData.url;
var row = tblUsers.insertRow(rowIndex);
var cellId = row.insertCell(0);
var cellName = row.insertCell(1);
var button = row.insertCell(2);
var itd = document.createElement('input');
itd.setAttribute("type","button");
itd.setAttribute("value","View");
itd.onclick=function () {
window.open(childData.url);
};
cellId.appendChild(document.createTextNode(childData.filename));
cellName.appendChild(document.createTextNode(childData.created));
button.appendChild(itd);
rowIndex = rowIndex+1;
//document.write(username);
})
});
}
Thanks in Regards
You only append data to the existing table, without ever removing existing rows in the table:
var row = tblUsers.insertRow(rowIndex);
You should make sure to remove all existing rows before adding the new one(s):
for (var i = tblUsers.rows.length; i >= 0; i--) {
tblUsers.deleteRow(i - 1);
}
I have a Dynamic asp Gridview with all columns as template feild TextBox. The columns of the Gridview are also dynamic and column count may vary everytime.
Please find code below
public void FillPoDetails()
{
DataTable dt = new DataTable();
dt = pmdata.createdatatable(int.Parse(Session["OurStyleid"].ToString()), int.Parse(Session["PoPackid"].ToString()));
GenerateTable(dt.Columns.Count, dt.Rows.Count,dt);
foreach (DataColumn col in dt.Columns)
{
//Declare the bound field and allocate memory for the bound field.
TemplateField bfield = new TemplateField();
//Initalize the DataField value.
bfield.HeaderTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Header, col.ColumnName);
//Initialize the HeaderText field value.
bfield.ItemTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Item, col.ColumnName);
//Add the newly created bound field to the GridView.
GrdDynamic.Columns.Add(bfield);
}
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
}
public GridViewTemplate(ListItemType type, string colname)
{
//Stores the template type.
_templateType = type;
//Stores the column name.
_columnName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_templateType)
{
case ListItemType.Header:
//Creates a new label control and add it to the container.
Label lbl = new Label();
//Allocates the new label object.
lbl.Text = _columnName;
lbl.CssClass = "Headerclass";
//Assigns the name of the column in the lable.
container.Controls.Add(lbl);
//Adds the newly created label control to the container.
break;
case ListItemType.Item:
//Creates a new text box control and add it to the container.
TextBox tb1 = new TextBox();
//Allocates the new text box object.
tb1.DataBinding += new EventHandler(tb1_DataBinding);
//Attaches the data binding event.
tb1.Columns =6;
//Creates a column with size 4.
// tb1.Width = System.Web.UI.WebControls.Unit.Percentage(100);
tb1.Width = 100;
tb1.Wrap = true;
tb1.ID = "txt_" + _columnName;
if(_columnName== "ColorTotal")
{
tb1.CssClass = "ColorTotal";
}
else if (_columnName == "Color")
{
tb1.CssClass = "Color";
}
else
{
tb1.CssClass = "txtCalQty";
tb1.Attributes.Add("onkeypress", "return isNumberKey(event,this)");
tb1.Attributes.Add("onkeyup", "sumofQty(this)");
}
container.Controls.Add(tb1);
//Adds the newly created textbox to the container.
break;
}
}
And inorder to get the row total I had added a Javascript function on keydown event and its working clearly
//calculate the sum of qty on keypress
function sumofQty(objText) {
var cell = objText.parentNode;
var row = cell.parentNode;
var sum = 0;
var textboxs = row.getElementsByClassName("txtCalQty");
for (var i = 0; i < textboxs.length; i++)
{
sum += parseFloat(textboxs[i].value);
}
var textboxtotalqtys = row.getElementsByClassName("ColorTotal");
textboxtotalqtys[0].value = sum.toString();
}
And the result is Like below
can anyone please help me in finding out the sum of each columns(all same cssclass).and display it in the Sizetotal row because I am not able to loop through columns
I would give every textbox a row id and a column id through html5 data attributes. and in javascript (jQuery) filter the textboxes through column id.
example:
..
var sum = 0;
$( "input[data-column-id='" + selectedColumnId + "']" ).each(function( index )
{
sum += parseFloat($( this ).val() );
});
..
By the way, use jQuery. its amazing.
Not sure about your requirement but this may help you, After binding data to grid, once again loop through the column list
GrdDynamic.DataSource = dt;
GrdDynamic.DataBind();
int rowIndex=2;
GrdDynamic.FooterRow.Cells[1].Text = "Total";
GrdDynamic.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
foreach (DataColumn col in dt.Columns)
{
decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>(col.Caption));
GrdDynamic.FooterRow.Cells[rowIndex++].Text = total.ToString("N2");
}
There is a very simple way.
Add Footer and Label to each Column, Then do calculations from database side best is use LINQ and Group by, find footer Label Controls for each column and Bind values to those Footer's Label Control, in this way your UI will have less load.
See here for code:
.ASPX Page in Grid:
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Literal ID="ltrlTotal" Text='<%#Eval("Total") %>' runat="server"> </asp:Literal> // For Sub Total
</ItemTemplate>
<FooterTemplate>
<strong><asp:Literal ID="ltrlGrandTotal" runat="server"> // This is Grand Total
</asp:Literal></strong>
</FooterTemplate>
</asp:TemplateField>
C# Code:
var searchResult = soService.SearchResult(companyId);
var grandTotal = searchResult.Select(so => so.Total).Sum();
searchResult.All(aa => aa.GrandTotal == grandTotal);
gridSo.DataSource = searchResult;
gridSo.DataBind();
if (searchResult.Count > 0)
{
Literal ltrlGrandTotal = gridSo.FooterRow.FindControl("ltrlGrandTotal") as Literal;
if (ltrlGrandTotal != null)
ltrlGrandTotal.Text = string.Format("Grand Total : $ {0}", grandTotal);
}
Hi this is a second part to an early question. I need to add rows to a form consisting of a selection box. Each row of the form is a type of "Room" in a house and the user has to be able to add as many rooms as needed. I have it all working however if you fill in the 2nd room and then add a 3rd room it resets the selection box to its default for the 2nd room. I can see why it is doing this i just cant think of how to change the function so it keeps your previous selections intact. Note: i have the 1st row for the 1st room written in the HTML then this function(below) is called from a button click and adds the extra rooms.
function add_room() {
var room_count = 0;
write = document.getElementById('new_room')
var roomSelect = '<select name="level[]" id="levels"' + room_count + '/> ';
roomSelect += '<option>Basement</option>';
roomSelect += '<option>Lower Level</option>';
roomSelect += '<option>Main Floor</option>';
roomSelect += '<option>2nd Floor</option>';
roomSelect += '<option>3rd Floor</option></select>';
write.innerHTML += roomSelect;
room_count++;
}
Thanks for any help you can offer!
This is because of the magic of .innerHTML +=.
As you might have guessed, It's actually identical to div.innerHTML = div.innerHTML + moreHTML - So the browser resets the HTML of the div. Including any selection, obviously.
I'd recommend you used div.appendChild. It doesn't change previously loaded HTML, and so won't change the user's selection.
function add_room() {
var room_count = 0;
write = document.getElementById('new_room');
var roomSelect = document.createElement('select'); // create select node
roomSelect.setAttribute("name", "level[]");
roomSelect.setAttribute("id", "levels" + room_count);
roomSelect.innerHTML = '<option>Basement</option>'+ //set the innerHTML (the options)
'<option>Lower Level</option>'+
'<option>Main Floor</option>'+
'<option>2nd Floor</option>'+
'<option>3rd Floor</option>'
write.appendChild(roomSelect); //append the child
room_count++;
}
i'm looking for somone that can help me on this problem:
i've a Telerik RadGrid in edit-mode, after pressing radgrid's update button i do some checks into a javascript file; i want to check the value in some cells that are in edit mode but i don't know how to see the value.
I try to explain better with an example: i have some columns editable and some read-only, for the read-only columns i can view the value but for the editable columns i view all the html of the cell and i don't know how to get only the value, here is the code
function calculate(dgRDO) {
var grid = $find(dgRDO).get_masterTableView();
var righe = grid.get_editItems();
for (var i = 0; i < righe.length; i++) {
var row = righe[i];
//i can view this value, CODART column is ReadOnly
var codart = grid.getCellByColumnUniqueName(row, "CODART").innerHTML;
//i cannot view only the value but i view the entire html of the cell, PREZZO column is editable
var prezzo = grid.getCellByColumnUniqueName(row, "PREZZO").innerHTML;
}
Thanks for any suggestion
RESPONSE FROM TELERIK (IT WORKS)
In order to easily access RadGrid cells client-side you could use the ClientDataKeyNames property. It should contain the DataField names of the columns that will be accessed on the client. Illustration on extracting key values client-side is available in this article.
A sample function for accessing a column that is added to the ClientDataKeyNames collection would look similar to this:
function command(sender, eventArgs) {
var grid = $find("<%= RadGrid1.ClientID %>");
var masterTableView = grid.get_masterTableView();
var editItem = masterTableView.get_editItems()[0];
var cellValue = editItem.getDataKeyValue("Quantity");
}
Try this
var prezzo = grid.getCellByColumnUniqueName(row, "PREZZO").val();