Inherited an app with a page that has a link that calls the javascript function addValueClick(), when I do this a dialog box pops up, I type in some text, and then the text gets put in the select box. Every time a new option is added to the select it gets about 5 pixels narrower. I can't figure out why this is happening, but it only happens in IE7
Here is the javascript:
function addValueClick()
{
var newValue = prompt("Please enter a new value.","");
if (newValue != null && newValue != "")
{
var lst = document.getElementById("lstValues");
var opt = document.createElement("option");
opt.setAttribute("selected", "true");
opt.appendChild(document.createTextNode(newValue));
lst.appendChild(opt);
updateBtns();
copyValues();
}
}
function copyValues()
{
var frm = document.forms[0];
var lst = frm.elements["lstValues"];
var hid = frm.elements["hidValues"];
var xml = "<root>";
for (var i = 0; i < lst.options.length; i++)
{
xml += "<value seq_num=\"" + (i + 1) + "\">" +
lst.options[i].text + "</value>";
}
xml += "</root>";
hid.value = xml;
}
function updateBtns()
{
var lst = document.getElementById("lstValues");
var iSelected = lst.selectedIndex;
var lnkEdit = document.getElementById("lnkEditValue");
var lnkDelete = document.getElementById("lnkDeleteValue");
var lnkUp = document.getElementById("lnkValueUp");
var lnkDown = document.getElementById("lnkValueDown");
if (iSelected == -1)
{
lnkEdit.style.visibility = "hidden";
lnkDelete.style.visibility = "hidden";
lnkUp.style.visibility = "hidden";
lnkDown.style.visibility = "hidden";
}
else
{
lnkEdit.style.visibility = "visible";
lnkDelete.style.visibility = "visible";
if (iSelected == 0)
lnkUp.style.visibility = "hidden";
else
lnkUp.style.visibility = "visible";
if (iSelected == lst.options.length - 1)
lnkDown.style.visibility = "hidden";
else
lnkDown.style.visibility = "visible";
}
}
EDIT:
The HTML, it's actually ASP.NET. All the listValueChanged() method does is call updateButtons() above.
<tr>
<TD class=body vAlign=top noWrap align=right><b>Values:</TD>
<TD class=body vAlign=top noWrap align=left><asp:ListBox id="lstValues" runat="server" onchange="lstValuesChange();" Rows="9" onselectedindexchanged="lstValues_SelectedIndexChanged"></asp:ListBox></TD>
<TD class=body vAlign=top noWrap align=left>
<TABLE id="Table2" cellSpacing="2" cellPadding="2" border="0">
<TR>
<TD noWrap>
<asp:HyperLink id="lnkAddValue" runat="server" NavigateUrl="javascript:addValueClick();">Add</asp:HyperLink></TD>
</TR>
<TR>
<TD noWrap>
<asp:HyperLink id="lnkEditValue" runat="server" NavigateUrl="javascript:editValueClick();">Edit</asp:HyperLink></TD>
</TR>
<TR>
<TD noWrap>
<asp:HyperLink id="lnkDeleteValue" runat="server" NavigateUrl="javascript:deleteValueClick();">Delete</asp:HyperLink></TD>
</TR>
<TR>
<TD noWrap> </TD>
</TR>
<TR>
<TD noWrap>
<asp:HyperLink id="lnkValueUp" runat="server" NavigateUrl="javascript:valueUpClick();">Up</asp:HyperLink></TD>
</TR>
<TR>
<TD noWrap>
<asp:HyperLink id="lnkValueDown" runat="server" NavigateUrl="javascript:valueDownClick();">Down</asp:HyperLink></TD>
</TR>
</TABLE>
</TD>
</TR>
It may have more to do with the html than the script. What is the select contained in? Based on the JS, I don't think there are any problems here.
I know that adding options via SelectElement.innerHTML = '...'; fails in IE (bug 274).
But I don't know about adding options via .createElement() failing... although I'm not overly surprised.
You can use the JavaScript new Option(); syntax to create them, I'm fairly certain that works without failure.
The issue was where the Option was being added to the Select I changed it to the following and it works perfectly:
function addValueClick()
{
var newValue = prompt("Please enter a new value.","");
if (newValue != null && newValue != "")
{
var lst = document.getElementById("lstValues");
var opt = document.createElement("option");
opt.text = newValue;
opt.value = newValue;
try {
lst.add(opt, null); // real browsers
}
catch (ex) {
lst.add(opt); // IE
}
updateBtns();
copyValues();
}
}
Related
I'm trying to build a sorting function to sort my tables based on which row I click. The problem I am running into is that when I click the row, it returns way too much data, the same data just repeated a couple hundred times. I think it's an issue with the asp:Repeater I use to pull the data, but can't think of a way to fix the issue. If you have any ideas how to fix this, I would appreciate it.If you have a better solution that what I'm trying, let me know, I'm okay with starting over.
The sorting itself doesn't work yet, but I can work on that later. I just need to know how to make it not post the same data hundreds of times. It loads fine the first time, but after a row is clicked it adds too much data.
Here is the code.
<table id="SortedTable" class="table table-hover table-condensed">
<thead>
<tr>
<th id="Ip_prefix">Ip_prefix</th>
<th id="Peer_ip_src">Peer_ip_src</th>
<th id="Comms">Comms</th>
<th id="Event_type">Event_type</th>
<th id="As_path">As_path</th>
<th id="Local_pref">Local_pref</th>
<th id="Created">Created</th>
</tr>
</thead>
<asp:Repeater runat="server" ID="dumpRptr">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<tbody>
<tr>
<td><%#Eval("ip_prefix")%></td>
<td><%#Eval("peer_ip_src")%></td>
<td><%#Eval("comms")%></td>
<td><%#Eval("event_type")%></td>
<td><%#Eval("as_path")%></td>
<td><%#Eval("local_pref")%></td>
<td><%#Eval("Created")%></td>
</tr>
</tbody>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
</table>
<script>
function sortTable(f, n) {
var rows = $('#SortedTable tbody tr').get();
rows.sort(function (a, b) {
var A = $(a).children('td').eq(n).text().toUpperCase();
var B = $(b).children('td').eq(n).text().toUpperCase();
if (A < B) {
return -1 * f;
}
if (A > B) {
return 1 * f;
}
return 0;
});
$.each(rows, function (index, row) {
$('#SortedTable').children('tbody').append(row);
});
}
var f_Ip_prefix = 1;
var f_Peer_ip_src = 1;
//....same all for allnames
$("#Ip_prefix").click(function () {
f_Ip_prefix *= -1;
var n = $(this).prevAll().length;
sortTable(f_Ip_prefix, n);
});
$("#Peer_ip_src").click(function () {
f_Peer_ip_src *= -1;
var n = $(this).prevAll().length;
sortTable(f_Peer_ip_src, n);
});
//same for the rest
</script>
I'm very new to all of this, so if you could explain the logic behind why it does what I don't want it to, I would be grateful. Answers are better of course.
I ended up making it so when the table row is clicked, the SQL code was changed to order them correctly. Everything can be sorted correctly now.
With reference to this link: https://web.archive.org/web/20210301194237/https://www.4guysfromrolla.com/articles/091708-1.aspx
I want to implement grouping headers for the gridview similar to what is shown in the below listview.
HTML Source:
<asp:ListView ID="ProductsGroupedByDataField" runat="server" DataSourceID="odsAllPlannedLeaves"
<LayoutTemplate>
<table cellspacing="0" cellpadding="5" rules="all" border="1" >
<tr style="background-color:#5D7B9D;color:White">
<th>Start Date</th>
<th>End Date</th>
<th>Date Of Applying</th>
</tr>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</table>
</LayoutTemplate>
<ItemTemplate>
<%# AddGroupingRowIfSupplierHasChanged() %>
<tr class='data<%# Container.DataItemIndex % 2 %>'>
<td><%#GetDate(Eval("Emp_StartDate"))%></td>
<td><%#GetDate(Eval("Emp_EndDate"))%></td>
<td><%#GetEntryDate(Eval("Emp_EntryDate"))%></td>
</tr>
</ItemTemplate>
</asp:ListView>
Method:
int LastEmpId = 0;
protected string AddGroupingRowIfSupplierHasChanged()
{
int CurrentEmpId = Convert.ToInt32(Eval("Emp_Id").ToString());
if (LastEmpId != CurrentEmpId)
{
LastEmpId = CurrentEmpId;
string CurrentEmpName = Eval("Emp_Name").ToString();
string CurrentEmailId = Eval("Emp_EmailID").ToString();
return string.Format("<tr style='text-align:left' class='group'><td colspan='3'>Employee Name: " + CurrentEmpName + " | Email Id: " + CurrentEmailId + "</td></tr>");
}
else
return string.Empty;
}
How can I implement this in a gridview ?
I use this little "break" for the Gridview's subheaders:
private string tmpCategoryName = "";
protected void gdvRowDatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
HiddenField hdnTmpSubTitle = (HiddenField)e.Row.FindControl("hdnTmpSubTitle");
if (!(tmpCategoryName == hdnTmpSubTitle.Value)) {
tmpCategoryName = hdnTmpSubTitle.Value;
Table tbl = e.Row.Parent as Table;
if (tbl != null) {
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.ColumnSpan = this.grdViewProjects.Columns.Count;
cell.Width = Unit.Percentage(100);
cell.Style.Add("font-weight", "bold");
cell.Style.Add("background-color", "#c0c0c0");
cell.Style.Add("color", "white");
HtmlGenericControl span = new HtmlGenericControl("span");
span.InnerHtml = tmpCategoryName;
cell.Controls.Add(span);
row.Cells.Add(cell);
tbl.Rows.AddAt(tbl.Rows.Count - 1, row);
}
}
}
}
This code gets the top level "Category" which is within your Gridview and just creates an extra table row, with one single cell, adds the style and then adds the category name. If the category is different from row to row, then change it. Ensure that your datasource is ordered by your "Category" first (or whatever you're using as a subheading).
Also ensure you place a HiddenField with the "Category" into a Template Field in your Gridview.
I have an AutoCompleteExtender on my page which works fine but when I scroll down the page and use it, suggestions show up at wrong (vertical) position.
It happens with Safari & Chrome but not with IE &FF and so I thought it could be webkit's fault.
Heres the code:
<td>
<div style="position: relative;">
<asp:TextBox ID="DepartureAirportTextBox" runat="server" CssClass="DepartureAirport airport-textbox"
onblur="javascript:DepartureLostFocus();" onkeydown="javascript:DepartureChanged(event);"></asp:TextBox>
<asp:Panel ID="DepartureAutocompleteDropDownPanel" runat="server" ScrollBars="Vertical"
CssClass="autocomplete-panel" Style="display: none;" />
<AjaxControlToolkit:AutoCompleteExtender ID="DepartureAirportAutoComplete" runat="server"
TargetControlID="DepartureAirportTextBox" CompletionSetCount="200" ServicePath="../WebServices/SecureService.asmx"
ServiceMethod="ListAirports" MinimumPrefixLength="3" BehaviorID="DepartureAirport"
CompletionListElementID="DepartureAutocompleteDropDownPanel" OnClientItemSelected="SelectDepartureAirport"
OnClientPopulating="ShowDepartureIcon" OnClientPopulated="HideDepartureIcon">
</AjaxControlToolkit:AutoCompleteExtender>
</div>
</td>
I have tried this & this solutions on SO, but none worked.
How to fix it?
Update:
Even the simplest example from Microsoft has this problem. Add some <p> elements before and after the textbox & extender to create scrollable area and test it.
<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>
<AjaxControlToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="txtMovie"
runat="server" UseContextKey="True" MinimumPrefixLength="2" ServiceMethod="GetCompletionList" />
Get code for GetCompletionList from above link. This issue is so easily reproducible.
I found a solution on Asp.net forums.
function resetPosition(object, args) {
var tb = object._element;
var tbposition = findPositionWithScrolling(tb);
var xposition = tbposition[0];
var yposition = tbposition[1] + 20; // 22 textbox height
var ex = object._completionListElement;
if (ex)
$common.setLocation(ex, new Sys.UI.Point(xposition, yposition));
}
function findPositionWithScrolling(oElement) {
if (typeof (oElement.offsetParent) != 'undefined') {
var originalElement = oElement;
for (var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
posX += oElement.offsetLeft;
posY += oElement.offsetTop;
if (oElement != originalElement && oElement != document.body && oElement != document.documentElement) {
posX -= oElement.scrollLeft;
posY -= oElement.scrollTop;
}
}
return [posX, posY];
} else {
return [oElement.x, oElement.y];
}
}
Call resetPosition on Extender's OnClientShown event
Greetings smart people of stackoverflow! I have this ListView with the following itemtemplate
<ItemTemplate>
<tr>
<td><%#Eval("abc_availablearea").ToString()%> </td>
<td><%#Eval("abc_classname").ToString() %> </td>
<td><%#Eval("abc_division").ToString() %> </td>
<td><%#Eval("abc_managername").ToString() %> </td>
</tr>
</ItemTemplate>
Now I am trying to use dynamic field names...so something like
<ItemTemplate>
<tr>
<td><%#Eval(fieldOne).ToString()%> </td>
<td><%#Eval(fieldTwo).ToString() %> </td>
<td><%#Eval(fieldThree).ToString() %> </td>
<td><%#Eval(fieldFour).ToString() %> </td>
</tr>
</ItemTemplate>
But it's not working for me. Anyone have an idea on how to do this? Thank you in advance for your help.
You'll need to create the ItemTemplate dynamically. Creating Web Server Control Templates Programmatically
I wrote a post on it: http://start-coding.blogspot.com/2013/06/dynamic-columns-in-listview.html.
On ItemDataBound event, do something like this:
private void dynamicPopulateRow(HtmlTableRow row, System.Data.DataRowView drv, int iGeneration)
{
if (row != null)
{
// http://www.pcreview.co.uk/forums/do-enumerate-all-columns-dataviewrow-t1244448.html
foreach (DataColumn dc in drv.Row.Table.Columns)
{
string sEmployeeID = drv["LoginID"].ToString();
if (dc.ColumnName.Equals("LoginID"))
{
// http://msdn.microsoft.com/en-US/library/e5daxzcy(v=vs.80).aspx
// Define a new HtmlTableCell control.
HtmlTableCell cell = new HtmlTableCell("td");
// Create the text for the cell.
cell.Controls.Add(new LiteralControl(Convert.ToString(drv[dc.ColumnName])));
cell.ColSpan = dc.ColumnName.Equals("LoginID") ? I_COLSPAN - iGeneration : 1;
// Add the cell to the HtmlTableRow Cells collection.
row.Cells.Add(cell);
}
else if (!(dc.ColumnName.Equals("GENERATION") ||
dc.ColumnName.Equals("hierarchy") ||
dc.ColumnName.Equals("rowNo") ||
dc.ColumnName.Equals("EmployeeID")))
{
// http://msdn.microsoft.com/en-US/library/e5daxzcy(v=vs.80).aspx
// Define a new HtmlTableCell control.
HtmlTableCell cell = new HtmlTableCell("td");
bool bIsNull = drv[dc.ColumnName] is System.DBNull;
Literal ltrl = new Literal();
ltrl.Text += "<input type=\"checkbox\" name=\"" + dc.ColumnName + "\"" +
(bIsNull ? "" : " value=" + drv[dc.ColumnName].ToString()) +
" id=\"" + sEmployeeID + "~" + dc.ColumnName.Replace(" ", "_") + "\"" +//will be retrieved later
" onclick=\"didModify(this)\" " +
(bIsNull ? " disabled" : "") +
(!bIsNull && ((int)drv[dc.ColumnName]) > 0 ? " checked>" : ">");
cell.Controls.Add(ltrl);
// Add the cell to the HtmlTableRow Cells collection.
row.Cells.Add(cell);
}
else
{
//other rows
}
}
}
}
I have a table with rows in, and each row has a few <td> elements. The last element has a checkbox in.
They are in a <div> which is set to runat="server". I have another checkbox on the page called "chkAll" that when clicked, I want to javascript check or uncheck all of the checkboxes in my table.
I'm not very good at Javascript, so I am not sure what to do. I added a javascript onclick method, and put document.getelementbyid and put in the div.clientID, but I wasnt sure what to do from there. Any ideas?
once you have the the <div> element as a reference, use getElementsByTagName() to get the <input> elements, then check the type property, if it's a checkbox then set it's checked property the same as the checked property of the checkbox chkAll. For example
function toggleCheckBoxes(elem) {
var div = document.getElementById('<% = divid.ClientID %>');
var chk = div.getElementsByTagName('input');
var len = chk.length;
for (var i = 0; i < len; i++) {
if (chk[i].type === 'checkbox') {
chk[i].checked = elem.checked;
}
}
}
and then attach this function as a click event handler of the chkAll element
<input type="checkbox" id="chkAll" onclick="toggleCheckBoxes(this)" />
Here's a Working Demo. add /edit to the URL to see the code
Since you are new to javascript I won't recommend using jQuery. Get basic ideas of javascript and then use jQuery.
Try this one
function CheckAll()
{
var tab = document.getElementById ( "tbl1" ); // table with id tbl1
var elems = tab.getElementsByTagName ( "input" );
var len = elems.length;
for ( var i = 0; i < len; i++ )
{
if ( elems[i].type == "checkbox" )
{
elems[i].checked = true;
}
}
}
If you are confident of using jQuery then you can use
$("#tbl1 input[type='checkbox']").attr ( 'checked' , true );
in the onclick function.
Try using jQuery - it makes javascript much easier and less verbose.
I think a solution to your problem can be found here:
http://www.iknowkungfoo.com/blog/index.cfm/2008/7/9/Check-All-Checkboxes-with-JQuery
Try the following:
in aspx:
<asp:CheckBox ID="chkAll" onclick="javascript:CheckUncheckall(this);" Text="Select" runat="server" />
<table id="tbl" runat="server">
<tr>
<td>
<asp:CheckBox ID="CheckBox1" runat="server" Text="A" /></td>
</tr>
<tr>
<td>
<asp:CheckBox ID="CheckBox2" runat="server" Text="B" /></td>
</tr>
<tr>
<td>
<asp:CheckBox ID="CheckBox3" runat="server" Text="C" /></td>
</tr>
<tr>
<td>
<asp:CheckBox ID="CheckBox4" runat="server" Text="D" /></td>
</tr>
<tr>
<td>
<asp:CheckBox ID="CheckBox5" runat="server" Text="E" /></td>
</tr>
</table>
and the javascript below:
<script language="javascript" type="text/javascript">
function CheckUncheckall(chk) {
var chks = document.getElementById("<% = tbl.ClientID %>").getElementsByTagName("input");
for(var i=0; i<chks.length; i++) {
if(chks[i].type == "checkbox") chks[i].checked= chk.checked;
}
}
</script>
I want to javascript check or uncheck
all of the checkboxes in my table
<table id="goofy">...</table>
Click me to check all boxes in table
And JavaScript:
function f() {
var inputs_in_table = document.getElementById("goofy").getElementsByTagName("input");
for(var i=0; i<inputs_in_table.length; i++) {
if(inputs_in_table[i].type == "checkbox") inputs_in_table[i].checked= true;
}
}
i have created a modified version using this script where you can pass table name and checkbox name dynamically.
Click here to get more infomarion
function checkedAll(container,chkID)
{
var tab = document.getElementById ( container ); // get table id which contain check box
var elems = tab.getElementsByTagName ( “input” );
for ( var i = 0; i < elems.length; i++ )
{
if ( elems[i].type == “checkbox” )
{
if ( document.getElementById(chkID).checked ==true)
elems[i].checked = true;
else
elems[i].checked = false;
}
}
}
You could save on looping elements here by using jquery to directly access checkboxes directly and then looping them.
$('input[type=checkbox]').each(function(){
this.checked = true
});
If you wanted to isolate a particular part of the page:
$(mydiv).find('input[type=checkbox]').each(function(){
this.checked = true
});
$('#checkall').click(
function () {
$('#divid').find('input[type=checkbox]').each(function () {
this.checked = $('#checkall').is(':checked')
});
});
In this, all checkboxes checked and unchecked by a single checkbox (checkall - id)