I am stuck in a situation, web site is running in ASP.NET 1.1
I am loading a page with some data. In the page there is a Html Table.
In each row, I am loading status(active/inactive) in one and message in another .
There is a save button when clicked it should save the status and message to database.
Since the data is in Html Table I am loosing the data while button is clicked.
I tried one option of keeping the status and message at page load in a global Javascript variable. But I will loose that also when button is clicked.
JS Code to store the data :
// To store all active or inactive feature values.
var arrType = [];
var interiorValues = [arrType];
var exteriorValues = [];
var mechanicalValues = [];
var standardValues = [];
function StoreChromeVallue()
{
var $jDecode = jQuery.noConflict();
var table = document.getElementById('dlInterior');
for (var i = 1, row; row = table.rows[i]; i++)
{
for (var j = 0, col; col = row.cells[j]; j++)
{
var imagePath = $jDecode(row.cells[0]).find('img:first').attr('src');
if(imagePath == "../icon_active1.gif")
{
arrType.push("active");
}
else if(imagePath == "../icon_deleted1.gif")
{
arrType.push("deleted");
}
else
{
arrType.push("active");
}
var featureValue = $jDecode(row.cells[1]).text();
arrType.push(featureValue);
arrType.push("Interior");
interiorValues.push(arrType);
}
}
alert(interiorValues[5][0]);
}
HTML TABLE WHERE DATA IS STORE
<TABLE id="dlInteriors" Width="300" Runat="server" CellSpacing="0" CellPadding="0">
<TR>
<TD id="interiortd" vAlign="top" width="350" runat="server"></TD>
</TR>
</TABLE>
Rows are dynamically added on page load.
Please guide me how I should go ahead on this.
You cant easily get all the values/strings in your HTML page while postback. You could able to get the form fields like input, select, etc in post back using Request.params[""].
But you could try with hidden variable (here it is your alternative Viewstate for your HTML table string values)
When & What you store / how to store /how to access in post back.
You can try the below steps for above question.
Before submit a form, fire a javascript function 'saveTableValues()'
which loops your HTML table and creates the object (var) for each row.
Prepare a javascript object array (just pushing the item in for each loop)
Convert it into JSON string and assign the whole JSON string
into Hidden Field
Do post back // just return true in JS
In code behind try accessing using Request.Params[""] or
normal way like hdnField.Text if it is server side control
In Code behing use a JavaScript Serializer
or JSON.Net to convert the JSON string into some collection.
Recommending JSON.Net here
This may help you.!
Edit:
As your website is running in 1.1 not sure those serializer dll will help you. So you try in XML format instead of JSON. Not sure JSON serializer dll is exist for 1.1 framework
Create table to run at server like this
<table id="users" runat="server">
and you will be able to access it using HtmlTable class,If required create a DataTable dynamically from the table rows and save that in a session. Have a look at http://msdn.microsoft.com/en-us/li
Use Jquery to get the rows values. Then store the data into hiddenfields. This way:
<script type="text/javascript">
function getTableValues() {
var tds = $('#dlInteriors tr td')
jQuery.each(tds, function () {
var url = $(this).children('img:first').attr('src');
var text = $(this).text();
if (url)
$('#hidValuesStatus').val($('#hidValuesStatus').val() + ',' + url);
if (text)
$('#hidValuesMessages').val($('#hidValuesMessages').val() + ',' + text);
});
}
</script>
Call the javascript function on the event "OnClientClick" of your asp:button
<TABLE id="dlInteriors" Width="300" Runat="server" CellSpacing="0" CellPadding="0">
<TR>
<TD id="interiortd" vAlign="top" width="350" runat="server"><img src="icon_active1.gif" /></TD>
<TD id="TD2" vAlign="top" width="350" runat="server">message1</TD>
</TR>
<TR>
<TD id="TD1" vAlign="top" width="350" runat="server"><img src="icon_deleted1.gif" /></TD>
<TD id="TD3" vAlign="top" width="350" runat="server">message2</TD>
</TR>
</TABLE>
<asp:Button runat="server" ID="btnSubmit" OnClientClick="javascript:getTableValues()" Text="SUBMIT" />
<input type="hidden" id="hidValuesMessages" runat="server" />
<input type="hidden" id="hidValuesStatus" runat="server"/>
And in the code behind get the data from the hidden fields:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then
If Not IsNothing(Request.Form("hidValuesMessages")) Then
Dim str As String = Request("hidValuesMessages")
End If
If Not IsNothing(Request.Form("hidValuesStatus")) Then
Dim str2 As String = Request("hidValuesStatus")
End If
End If
End Sub
Split the string and get the final values.
Hope this helps!
Regards.
Related
Hi I want to access text present in all section of my application. I cannot use id because in one application there are different tables with different id's. I want to access text name whenever I place mouse on that td cell irrespective of table so I can't use id. Please suggest me a way to do this using JQuery. The text which I want to access are from asp.net aspx page.
In jquery, you can apply a hover event to every td which fetches it's text. put the text in a variable, then pass it on to your .aspx handler with ajax. here is a simple example. its a good idea to put this script block in your ready function, or near the end of your document.
jQuery
$('td').hover(function () {
//mouse over
//get the data
var tdText = $(this).text();
console.log(tdText);
//do something with the data
var jqxhr = $.ajax("handler.aspx?text=" + tdText)
.done(function () {
console.log("success");
//do something
})
.fail(function () {
console.log("error");
//do something else
});
},
function () {
//mouse out
console.log("mouse-out");
}
);
I can only help you with determining if the mouse cursor is above any td element. You will need to modify the code to fit your needs to display something useful.
HTML:
<p id="message"> </p>
<table>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
<tr>
<td>Data A</td>
<td>Data B</td>
<td>Data C</td>
</tr>
</table>
JS:
addEventListener("mouseover", function(event) {
if (event.toElement.localName == 'td')
$('#message').html("You are in a table cell");
else
$('#message').html(" ");
}, false);
I also created a fiddle for you to test: http://jsfiddle.net/m3EmK/
I'm trying to create a web page to create small playlists. Once data has been entered into the fields, it needs to be saved to an XML file. Currently the table looks like this:
<%-- song list table --%>
<table runat="server" id="table" class="table">
<%-- info row --%>
<thead>
<tr>
<td>Song Title</td>
<td>Song Artist</td>
<td>Song Album</td>
<td><%-- column for delete button --%></td>
</tr>
</thead>
<%-- input rows --%>
<tbody>
<tr>
<td><input runat="server" placeholder="Title" type="text" /></td>
<td><input runat="server" placeholder="Artist" type="text" /></td>
<td><input runat="server" placeholder="Album" type="text" /></td>
<td>
<a href="#">
<img src="Images/Delete.png" onmouseover="this.src='Images/Delete-Hover.png'" onmouseout="this.src='Images/Delete.png'" alt="Delete" />
</a>
</td>
</tr>
</tbody>
</table>
New rows will be added dynamically with jQuery. When the user clicks save, I need to write the table data into their specific XML file. Currently my backend code looks like this:
//for each row
foreach (HtmlTableRow row in table.Rows)
{
//create row info
textWriter.WriteStartElement("Row");
//for each cell
foreach (HtmlTableCell element in row.Cells)
{
//get inputs
//write current input to xml
}
//close row
textWriter.WriteEndElement();
}
My question is where I go from there with my code to be able to get the values of each input and write them to the XML.
You need to give the element's an ID so you can refer to them by. Also, any dynamically added rows will not be able to be accessed this way; that is because they do not exist in the control tree as a server control, but are a pure client control. You would have to access these using Request.Form collection. You'd have to add them dynamically to the control tree if you want them to persist across postbacks too.
If you are using JQuery, it would be more efficient and easier to grab all the values on the client and send the values to a web service or something like that.
My suggestion would be to re-think how you're gathering the data. I assume that you're going to have this information do an HTTP POST to your server using $.ajax() or something similar - and on the server-side, you're wanting to get all of the instances of the Title, Artist and Album fields, grouped by row.
Instead of posting back the table, which is a set of UI elements that display your data, but do not represent it, consider posting back to the server and having the server expect an IEnumerable of Song objects, which would look something like this:
public class Song {
public String Album { get; set; }
public String Artist { get; set; }
public String Title { get; set; }
}
Now, when you bind the form itself, you can bind something like:
<table>
<thead>
<tr>
<td>Song Title</td>
<td>Song Artist</td>
<td>Song Album</td>
<td><%-- column for delete button --%></td>
</tr>
</thead>
<tbody>
<tr>
<td><input placeholder="Title" type="text" name="Songs[0].Title" /></td>
<td><input placeholder="Title" type="text" name="Songs[0].Artist" /></td>
<td><input placeholder="Title" type="text" name="Songs[0].Album" /></td>
</tr>
</tbody>
</table>
The [0] notation indicates that this element is part of an IEnumerable called Songs, and is at index 0. When your jQuery script then goes and adds new rows, you simply increment the indexes. So - a new row would be something like:
<tr>
<td><input placeholder="Title" type="text" name="Songs[1].Title" /></td>
<td><input placeholder="Title" type="text" name="Songs[1].Artist" /></td>
<td><input placeholder="Title" type="text" name="Songs[1].Album" /></td>
</tr>
The only trick to this is to ensure that you never have gaps in your indexes. I.E. - if you have 5 rows, and you delete the third, you need to re-index rows 4 and 5 (by decrementing the [#] values).
Note: All of the above assumes you are using server-side binding.
If you are already using jQuery, you might also find it simpler to simply parse your table's input elements with jQuery and post things as an object that you have direct control over. This prevents you from having to do any indexing at all. An example would be something like:
$('#submit-button').on('click', function (ev) {
var songs = [];
$('#table > tbody > tr').each(function (index, element) {
var $tr = $(element);
var album = $tr.find('input[placeholder=Album]').val();
var artist = $tr.find('input[placeholder=Artist]').val();
var title = $tr.find('input[placeholder=title]').val();
songs.push({ Album: album, Artist: artist, Title: title });
});
$.ajax({
url: '/my/post/url',
type: 'POST',
data: songs
});
});
On the server-side, you will now receive an HTTP POST to /my/post/url which has a payload containing the song data in the table - without having to worry about funky data-binding syntax or indexing.
Hope this helps.
I am having header in gridview that labels as "xls" and a checkbox, that when selected should select all the checkbox columns in gridview and unchecking the xls column should uncheck all the columns.
I am following two links:
Link-1
Here, the totalChkBoxes variable is coming null (despite my gridview has rows). In fact when debugging the JS, code inside parseInt and below line is coming as ''
Link-2
Here also the GridView2 variable is coming null.
One common change that i am doing in both the JS is replacing the <%=.....%> by <%#....%>
Please guide as to what i am doing wrong. You can also help by giving some suitable link to implement the desired functionality
CODE UPDATED WITH MY WORKING JS
<script type="text/javascript" language="javascript">
function checkAllBoxes() {
var gvControl = document.getElementById("gvSample");
//this is the checkbox in the item template.
var gvChkBoxControl = "chkSelectItem";
//Header Template checkbox.
var mainChkBox = document.getElementById("chkBoxAll");
//Array of Inputs in gridview.
var inputTypes = gvControl.getElementsByTagName("input");
for (var i = 0; i < inputTypes.length; i++) {
//if the input type is a checkbox and the id of it is what we set above
//then check or uncheck according to the main checkbox in the header template
if (inputTypes[i].type == 'checkbox' && inputTypes[i].id.indexOf(gvChkBoxControl, 0) >= 0)
inputTypes[i].checked = mainChkBox.checked;
}
}
GRIDVIEW CODE
<asp:TemplateField>
<HeaderTemplate>
<table style="width: 15px" cellpadding="0" cellspacing="0">
<tr>
<td>
<asp:Label ID="lblXls" runat="server" Text="xls"></asp:Label>
<br />
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" />
</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelectItem" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Thanks!
Try changing your parseInt to something like this to see if it helps at all. I know it's only a small change, but small things tend to break JS code:
var totalChkBoxes = parseInt("<%=gvTest.Rows.Count%>");
Secondly, if you have runat="server" on the checkbox in the header, you may need to change this line if your JSFunction:
var mainChkBox = document.getElementById("<%=chkBoxAll.UniqueID%>");
I want to design a table whose rows are retrieved from another aspx page via xml.
Say I have a page getstudents.aspx which gives all the students in the database in the following format:
<?xml version="1.0" encoding="utf-8"?>
<allstudents>
<student>
<rollno>8001</rollno>
<name>AAAA</name>
</student>
<student>
<rollno>8002</rollno>
<name>BBBB</name>
</student>
</allstudents>
this way I get data from getstudents.aspx.
Now I want to design a page selectstudents.aspx
which outputs following html (a table with a checkbox in each row)
in the following way:
<head>
<script type="text/javascript">
var values[];
function add(x)
{
//adds the value of ticked checkbox in values array and removes it when unticked
}
</script>
</head>
<body>
<table>
<tr>
<td> </td>
<td>Name</td>
<tr>
<td><input type="checkbox" name="cbRoll" value="8001" id="cbRoll8001" /></td>
<td>AAAA</td>
</tr>
<tr>
<td><input type="checkbox" name="cbRoll" value="8002" id="cbRoll8002"/></td>
<td>BBBB</td>
</tr>
</table>
<form id="form1" name="form1">
</form>
</body>
The table with checkboxes is dynamically generated at runtime
with id of checkbox, value of checkbox(8001,8002,etc) and the name (AAAA,BBBB,etc) in the next corrosponding column.
By reading data from xml given by page getstudents.aspx
also
a function (say) addremove(this.id) should be called whenever a checkbox is ticked
or unticked which should add or remove the value of checkbox (8001,8002,etc) to/from a string array named (say) 'values'.
I will then submit to the webpage a string via POST containing "8001;8002;8003 and so on"
depending on which checkboxes are checked
obviously i will make the string from the array 'values'.
I do not want to use ready made usercontrols available in asp.net.
What I want to do is more complicated than this, but this is a simplified version of it.
So for this, what should be structure of aspx page and what should be code behind in C#?
On the selectstudents.aspx page, have a >NET Literal control where you want the table to appear:
<body>
<form id="form1" name="form1">
<asp:Literal runat="server" id="ltrStudents" />
</form>
</body>
Then in the code-behind of that page, get your students XML and create a table from it, something like this:
string xml =
#"<?xml version='1.0' encoding='utf-8'?>
<allstudents>
<student>
<rollno>8001</rollno>
<name>AAAA</name>
</student>
<student>
<rollno>8002</rollno>
<name>BBBB</name>
</student>
</allstudents>";
var studentsXml = XDocument.Parse(xml);
var students = studentsXml.Element("allstudents").Elements("student").ToList();
StringBuilder sb = new StringBuilder(500);
sb.Append("<table>");
foreach (var student in students)
{
string rollNumber = student.Element("rollno") != null ? student.Element("rollno").Value : string.Empty;
string name = student.Element("name") != null ? student.Element("name").Value : string.Empty;
sb.Append("<tr>");
sb.Append("<td> </td>");
sb.Append("<td>Name</td>");
sb.Append("</tr>");
sb.Append("<tr>");
sb.AppendFormat("<td><input type='checkbox' name='cbRoll' value='{0}' id='cbRoll{0}' /></td>", rollNumber);
sb.AppendFormat("<td>{0}</td>", name);
sb.Append("<tr/>");
}
sb.Append("</table>");
ltrStudents.Text = sb.ToString();
Try the above code and see if it helps you. You might need to set the Mode property of the ltrStudents control - check this out for help on that.
As for the JavaScript, my jQuery is really rusty, but in the ASPX you could have:
$(document).ready(
function() {
$("input[type=checkbox]").click(function(){
alert($(this).attr('value')); // Store the rollno using a global variable.
});
});
I'm just using alert() here to prove a point. In your code you need to store the rollno in a variable.
I have been trying to set the value of a hidden input by using Javascript and then access the value from within my C# codebehind. When I run the code that is copied below, the value that is assigned to assignedIDs is "", which I assume is the default value for a hidden input. If I manually set the value in the html tag, then assignedIDs is set to that value.
This behavior suggests to me that the value of the input is being reset (re-rendered?) between the onClientClick and onClick events firing.
I would appreciate any help with the matter. I have spent hours trying to solve what seems like a very simple problem.
html/javascript:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Admin Page - Manage Tasks</title>
<script language="javascript" type="text/javascript">
function PopulateAssignedIDHiddenInput() {
var source = document.getElementById('assignedLinguistListBox');
var s = "";
var count = source.length;
for (var i = count - 1; i >= 0; i--) {
var item = source.options[i];
if (s == "") { s = source.options[i].value; }
else { s = s.concat(",",source.options[i].value); }
}
document.getElementById('assignedIDHiddenInput').Value = s;
// I have confirmed that, at this point, the value of
// the hidden input is set properly
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel id="EditMode" runat="server">
<table style="border: none;">
<tr>
<td>
<asp:Label ID="availableLinguistLabel" runat="server" Text="Available"></asp:Label><br />
<asp:ListBox ID="availableLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
<td>
<input type="button" name="right" value=">>"
onclick="Javascript:MoveItem('availableLinguistListBox', 'assignedLinguistListBox');" /><br /><br />
<input type="button" name="left" value="<<"
onclick="Javascript:MoveItem('assignedLinguistListBox', 'availableLinguistListBox');" />
</td>
<td>
<asp:Label ID="assignedLinguistLabel" runat="server" Text="Assigned To"></asp:Label><br />
<asp:ListBox ID="assignedLinguistListBox" runat="server" Rows="10" SelectionMode="Multiple"></asp:ListBox>
</td>
</tr>
</table>
//-snip-
<asp:Button ID="save_task_changes_button" runat="server" ToolTip="Click to save changes to task"
Text="Save Changes" OnClick="save_task_changes_button_click" OnClientClick="Javascript:PopulateAssignedIDHiddenInput()" />
</asp:Panel>
<!-- Hidden Inputs -->
<!-- Note that I have also tried setting runat="server" with no change -->
<input id="assignedIDHiddenInput" name="assignedIDHiddenInput" type="hidden" />
</div>
</form>
</body>
c#
protected void save_task_changes_button_click(object sender, EventArgs e)
{
string assignedIDs = Request.Form["assignedIDHiddenInput"];
// Here, assignedIDs == ""; also, Request.Params["assignedIDHiddenInput"] == ""
// -snip-
}
In javascript you need the value property to be lowercase, like this:
document.getElementById('assignedIDHiddenInput').value = s;
Then it will be set properly :) You can see an example in action here
Though if you alert the .Value it will show your value, you've actually added a new .Value property, but you haven't set the input's .value property which is what gets posted to the server. The example link above illustrates this both ways.
Also you can make it a bit faster especially if you have lots of options by using an array instead of string concatenation, like this:
var source = document.getElementById('assignedLinguistListBox');
var opts = [];
for (var i = 0; i < source.options.length; i++) {
opts.push(source.options[i].value);
}
var s = opts.join(',');
Edit: The above code is updated, CMS is right that the previous method was browser dependent, the above should now behave consistently. Also, if jQuery is an option, there are shorter ways of getting this info still, like this:
var s = $('#assignedLinguistListBox option').map(function() {
return this.value;
}).get().join(',');
$('#assignedIDHiddenInput').val(s);
You can see a working example of this here
I'm assuming ASP.NET here.
If so, your problem is the id of the control in the HTML generated by ASP.NET is not going to be "assignedIDHiddenInput" that you reference in the script. ASP.NET changes those before rendering the HTML from what you specify in the HTML page declaratively. Do a view source on the page and you will see what I mean.
Here is a way around that:
document.getElementById('<%=assignedIDHiddenInput.ClientID %>').value = s;
Update: As noted in the comments, this is only relevant if the control is set to RunAt=Server.
I think ASP.NET is calling the javascript to execute a postback on that control before your javascript function is called to populate that hidden value.
I think it's possible to disable the default postback and handle it yourself but I'm sure others can advise better.
Stick an alert() into your function there to see if it is really getting called before post-back is triggered.