Blog Archives

lastChild is null in FireFox works in IE invalid nodeType javascript c# asp .net

This issue alluded me at first as it works in IE but not in FF. See code below.

//pass in table, last cell number and style to apply to it. call this on hover and blur for cell highlight effects. alternatively you can determine last cell number as well and this function could be rewritten to work solely for the purpose of modifying specific cells rather than last cell
function ChangeTableCellStyle(tableid,cellnumber,mystyle) {
if (document.getElementById)
{
var selectedElement = document.getElementById(tableid);
selectedElement.className = style;
//change style on end cell by drilling into table. this will become deprecated by css3.
if (selectedElement.tagName.toLowerCase()=="table")
{

var tbody = selectedElement.lastChild;
if (tbody!=null)
{
var tr = tbody.lastChild;
if (tbody !=null)
{
var tr = tbody.lastChild; //BUGGED IN FF!

//nodetype should be 1 for element type. in FF it is 3. see reference link at bottom for list of types.
if (tr.nodeType!=1) {
tr.tbody.getElementsByTagName("td");
tr[cellnumber].className+= ' ' + mystyle;
} else {
tr.lastChild.className+=' ' + mystyle;
}

}
}

}
}

}

//example usage
ChangeTableCellStyle("table1",3,"cellend"); //will append the class cellend to the last cell in table1 if table1 only has 4 cells per row

In you’re interested in reviewing other approaches to styling your table cells, see my similar article here.

Advertisements

change last row cell style in css and javascript cross browser compatibility issues

There are various approaches to achieve this functionality with equally different levels of compatibility across browsers. Here are some of the ways.

Javascript Approach (most compatible. you may recognize this code from another one of my articles.):

function ChangeTableCellStyle(tableid,cellnumber,mystyle) {
if (document.getElementById)
{
var selectedElement = document.getElementById(tableid);
selectedElement.className = style;
//change style on end cell by drilling into table. this will eventually become completely replaced by css3
if (selectedElement.tagName.toLowerCase()=="table")
{
var tbody = selectedElement.lastChild;
if (tbody!=null)
{
if (tr.nodeType!=1) {
tr.tbody.getElementsByTagName("td");
tr[cellnumber].className+= ' ' + mystyle;
} } } } }

HTML col tags and hardcoded inline style overrides (easy, but messy IMO. also definitely not a good approach for styling lots of similar looking pages)

<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>

<td style="background-color: #000000">First TD of first TR</td>
[... etc ...]
<tr style="background-color: #6374AB;"> // second TR

CSS3 last child (super clean and awesome but unfortunately not well supported by browsers)

p:last-child {
  ⋮ declarations
}

jQuery Approach (this also has good compatibility and much cleaner than your own JS function, but requires an external jquery library reference which may be overkill unless you’re already using it):

$(document).ready(function() {
    $('table.class tr:last-child').addClass('ClassName'); //can also speciy firstchild etc
});

Some of the snippets above are quoted snippets directly from references below. See the reference links for more information on a specific approach.

As the above examples have illustrated there are many ways to achieve what you need each varying depending on your implementation. Hope this article helped! Enjoy.

References
CSS fixed table approachhttp://stackoverflow.com/questions/359821/styling-the-last-td-in-a-table-with-css
HTML col tags approach, http://www.quirksmode.org/css/columns.html
css3 approach, http://reference.sitepoint.com/css/pseudoclass-lastchild
jQuery approach, http://stackoverflow.com/questions/5850835/jquery-selector-to-last-row-first-column

Serialize C# object to JSON JavaScriptSerializer .Net

//declare data you want to send as an object type
public class MyType {
//may simply contain properties mapping to your database rows or be more complex objects
//use [Serializable] attributes to mark props or methods as non-serialized
}
public void Page_Load(object sender, EventArgs e) {
MyType o1 = new MyType {p1="",p2=""};


Response.Write(JSONSerialize(o1));

Response.Write("<br /><br />");

MyType o2 = new MyType {p1="",p2=""};
List<MyType> olist = new List<MyType> {o1, o2};

Response.Write(JSONSerialize(olist));
}

public string JSONSerialize(MyType o) {
System.Web.Script.Serialization.JavaScriptSerializer sz = 
         new System.Web.Script.Serialization.JavaScriptSerializer();
return sz.Serialize(o);
}

//additional signature to handle lists of object
public string JSONSerialize(List<MyType> o) {
System.Web.Script.Serialization.JavaScriptSerializer sz = 
         new System.Web.Script.Serialization.JavaScriptSerializer();
return sz.Serialize(o);
}

References
MS Blogs, http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx
JSON.org, http://www.json.org/js.html
C# Cross-Site Page Access, http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method
PHP Cross-Site Page Access, http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/
JS Eval string to JSON Object, http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/

asp .net c# luhn algorithm validation mod10 with realtime clientside Javascript

Read the rest of this entry

Simple Javascript CountDown timer and Page Redirect in HTML

<html>
<title>SiteName (test)</title>
<head>
<script type="text/javascript">
var ss = 10;
function countdown() {
ss = ss-1;
if (ss<0) {
window.location="http://www.sitename.com";
}
else {
document.getElementById("countdown").innerHTML=ss;
window.setTimeout("countdown()", 1000);
}
}
</script>
</head>
<body onload="countdown()">
<center>
<table width="100%" height="600px" style="text-align:center;">
<tr><td valign="center"><h3>Redirecting to <a href="http://www.sitename.com">www.sitename.com</a> (<span id="countdown" style="color:green;">10</span>)</h3></td></tr>
</table>
</center>
</body>
</html>

Get Current URL in Javascript

JS (JQuery):

$(document).ready(function() {
    $(location).attr('href');
});

JS (standard):

function CurrentURL() {
    var currenturl = window.location.pathname;
return currenturl;
}

JQuery Grid Themes

Useful links to JQuery grids utilizing (mostly) standard UI themes and/or very little code.

Google!
http://jquery-ui.googlecode.com/svn/branches/labs/grid/tests/static/grid/default.html

Datatables.Net:
http://www.datatables.net/styling/themes/smoothness

Ke-Cai:
http://www.ke-cai.net/2010/01/theme-your-table-with-jquery-ui.html

Trirand:
http://www.trirand.com/blog/jqgrid/jqgrid.html

Stackoverflow:
http://stackoverflow.com/questions/2613632/jquery-ui-themes-and-html-tables

JQuery and Partial Postbacks

I recently came across an issue where JQuery bindings no longer functioned after a partial postback and stumbled upon some code that was helpful in most cases.

Javascript (JQuery):

Sys.Application.add_load(startJQuery); 

startJQuery() { 
//do JQ here
}

And alternatively..

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(){});

This code will not always work however, as was the case in my particular scenario, so I resolved using an alternate method.

RegisterStartupScript is great functionality, and can be useful for loading javascript dynamically on an as-needed basis.

The example below, based on prior code selects the correct JS file to use, then loads it using the registerstartupscript function. This is all within a code block which calls an update panel

C#:


int scriptnumber = 1;
string FilePath = String.Format("~/Scripts/Script_{0}.js",scriptnumber.ToString());
System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(FilePath));
            jqueryfileoutput = sr.ReadToEnd();

            upnlBodyContent.Update();

            ScriptManager.RegisterStartupScript(this, this.GetType(), "scriptname",
                "<script type=\"text/javascript\">" + jqueryfileoutput.ToString().Trim() + "</script>", false);

JQuery and Frames

Although there is definitely some room for debate in the web development and design community on where the usage of frames is necessary, there are some situations where they cannot be avoided.

Manipulation of data within these frames can be confusing, and dumping frames to page content using ajax or server side code is not always possible. This is especially true if these pages contain their own sub-site navigation.

In these scenarios, JQuery helps us simplify content management within frames using a combination of the “.contents()” method and “find” functionality to locate and update elements.

If “videoframe” is the id of the iframe, the example below changes the background color of a body inside the frame to a specific color.

JS (JQuery):


$('#videoframe').contents().find("body").css("background-color", "#FFFFFF");

References:
JQuery API, http://api.jquery.com/contents

JQuery AJAX Reference

Keep in mind when using code below if requesting a page that requires login/restricted access, users login session is not carried over.

Snippet below is sample code usage illustrating two different methods of achieving similar result. See references for more info and full specifications.

Javscript (JQuery):

$.ajax({
                            url: 'http://www.websitename.com/',
                            dataType: "text",
                            type: "POST",
                            data: { city: "NewYork"},
                            error: function(err) {
                                alert("Error:" + err.toString());
                            },
                            success: function(data) {
                                //$("#JQuery_modal_p").html(data);
                                alert(data);
                            }

                        });

Javscript (JQuery):

$.ajax({
                            url: 'http://www.websitename.com/' + data1+ data2,
                            dataType: "text",
                            type: "GET",
                            data: {},
                            error: function(err) {
                                alert("Error:" + err.toString());
                            },
                            success: function(data) {
                                //$("#JQuery_modal_p").html(data);
                                alert(data);
                            }

                        });

References:
JQuery Ajax, http://api.jquery.com/jQuery.ajax/