jQuery Dynamically Create Table

by aherrick 24. June 2010 10:47

Use jQuery objects to build up your table instead of using string concatenation.  How many time have you seen code similar to the following to build up a table?

        $(function () {

            var content = '';
            content += '<div id="tableWrap">';
            content += '<table id="basicTable">';

            for (var i = 0; i < 200; i++) {


                content += '<tr>';
                content += '<td>';
                content += i;
                content += '</td>';
                content += '<td>';
                content += 200 - i;
                content += '</td>';
                content += '</tr>';
            }

            content += '</table>';
            content += '</div>';

            $('body').append(content);
        });

Let's use jQuery's built in ability to build up the objects and take a look at how we could write this differently below.

        $(function () {

            var $wrap = $('<div>').attr('id', 'tableWrap');

            var $tbl = $('<table>').attr('id', 'basicTable');

            for (var i = 0; i < 200; i++) {

                $tbl.append(
                            $('<tr>')
                                    .append($('<td>').text(i),
                                            $('<td>').text(200 - i))
                           );
            }

            $wrap.append($tbl);
            $('body').append($wrap);
        });

View the live code here!

Tags:

Javascript Regular Expression Allow Alphanumeric KeyUp

by aherrick 22. January 2010 04:13

Working on an application I needed to write a script to only allow Alphanumeric characters (Letters and Numbers only) for dynamic XML generation.  We wanted the solution to be smart enough that when the user is typing in a textbox, any character other than Alphanumeric is automatically removed while they are typing into the input.  Using a combination of jQuery and regular Javascript the solution becomes simple. 

Take a look at the Javascript used below.

    <script type="text/javascript">

        $(function() {

            $('#basicInput').keyup(function() {

                // cache input and value
                var input = $('#basicInput');
                var value = $('#value');

                // only allow letters, numbers, don't allow spaces
                var tempVal = input.val().match(/[A-Za-z0-9]+/g);
                tempVal = tempVal == null ? "" : tempVal.join("");

                // display formatted input
                input.val(tempVal);
                value.html(tempVal);
            });
        });
        
    </script>

First we attach a jQuery keyup event to the text input. We then get the value of the input and run it through a basic regular expression to get the match. We then update the input with the array of matched values.

Great! Check out the example page to see it in action!

Tags:

Hard Drive No Sleep v1.0

by aherrick 29. November 2009 07:13

I wrote this little Windows Forms application a while back as an answer to a small issue I was having with my external hard drives.  I wanted to prevent them from spinning down and entering a sleep mode after a certain period of time.  This application simply attempts to write a text file to the root of each configured drive in order to keep activity on the drive and prevent it from spinning down.  I wanted to learn how to do some of the different configurations but mainly wanted to write a working Windows application.  Tested in Windows Server 2003/2008, Windows XP, and Windows Vista.

hdns

It is fully customizable to allow for multiple hard drives, and has different configuration settings such as how often (in minutes) to write a file, minimize to tray on start, monitor automatically on start, and run on Windows start up.  Once a configuration is saved, settings are saved even if the application is restarted.  I wanted to take a look at some of these basic configurations that can be reused across other applications that I build.

hdns-config

Below is an EXE of the application and the full source in case you are interested in checking it out!

HardDriveNoSleepV1.0-EXE.zip (91.46 kb)
HardDriveNoSleepV1.0-SRC.zip (422.66 kb)

Tags: ,

JavaScript Determine Valid Integer

by aherrick 13. October 2009 05:02

I need a simple function to determine if a value was a valid integer.  Meaning that the value is a whole number (positive or negative) and doesn’t contain decimals. 

Below is what I came up with.

// check valid integer
function IsValidInt(s) {

    var valid = false;
    if (s != null && s != "" && !isNaN(s)) {
        valid = parseInt(s, 10) == s;
    }
    return valid;
}

Breaking it down we assume that the value is invalid.  We verify the value is not null, not an empty string, and use JavaScript’s built in NaN() (Not a Number) function to determine if it is a valid number.

Then use other JavaScript built in function, parseInt() and compare it to the original passed in value.  parseInt() will evaluate the value and return an Integer.  By comparing the returned integer and our passed in value, we can determine if the passed in value is valid.

I came up with this basic test suite function to show it validating.

function TestIsValidInt(){
    var results = ''
    results += (IsValidInt('-1')?"Pass":"Fail") + ": IsValidInt('-1') => true\n";
    results += (IsValidInt('-1.5')?"Pass":"Fail") + ": IsValidInt('-1.5') => false\n";
    results += (IsValidInt('0')?"Pass":"Fail") + ": IsValidInt('0') => true\n";
    results += (IsValidInt('asdf')?"Pass":"Fail") + ": IsValidInt('asdf') => false\n";

    alert(results);
}

Check out the example page to see it in action!

Enjoy!

Tags:

Check It Out http://www.theholidaycountdown.com Is Live!

by aherrick 8. August 2009 02:44

This past week I took live the project I have been working on over the past month, The Holiday Countdown.  The premise is simple, I wanted to create a basic, clean site where you can easily find out how many days until an upcoming holiday. 

From the technology side of things, the site is built completely on the ASP.NET MVC 1.0 framework with a LINQ to SQL backend.  Custom Javascript code is used for the countdown timers. I would call this version 1.0, in the future I may end up making it more dynamic by allowing users to add their own Holiday Countdowns and add favorite Holidays to their account homepage. 

It was a fun little side project to work on so check it out today to find out how long until your next favorite Holiday!

http://www.theholidaycountdown.com

image

Tags:

Validate Username Using jQuery AJAX, JSON, and ASP.NET Web Method

by aherrick 11. February 2009 08:59

As of late, I have been working on using AJAX in my code to call ASP.NET Web Methods and Web Services.  There are a couple of different ways to accomplish this, including using the ASP.NET Script Manager, (see here) however there is a lot of overhead with instancing the Script Manager that is not always necessary.

The method below using the jQuery.AJAX call which even includes built in error checking functionality.  In this example, I am going to call a Web Method in the code behind that will validate the username text field input and return a boolean regarding if the username is valid. 

In a normal production environment, in your Web Method you would want to hit a database to validate the input, however for this demo I am going to simulate that.  If the username entered equals “testuser”, the method will return false, otherwise return true resulting in a valid username.

First we are going to add our html to the page:

<div>
    Username:
    <input id="tbUsername" type="text" />
    <span id="valid"></span>
</div>
<!-- preload -->
<div style="display: none">
    <img src="images/available.gif" alt="available" />
    <img src="images/taken.gif" alt="taken" />
    <img src="images/waiting.gif" alt="waiting" />
</div>

Here I am creating a simple html textbox and span tag.  We will use the Javascript code to change the html of the span tag.  It is a place holder for now.  Also I add an image preload div using CSS so the necessary images are loaded at runtime.  display: none ensures the images will not be visible on the screen.  This ensures a smooth effect when hiding/showing the images dynamically.

Next we are going to create our simple Web Method in the code behind.

using System.Web.Services;
[WebMethod]
public static bool IsUserAvailable(string username)
{
    // simulating db call here
    if ((!username.Contains(" ") || !username.Contains("")) && username != "testuser")
        return true;
    else
        return false;
}
 
All we are doing is creating a simple method to return if the user is valid. 

Now lets take a look at the Javascript required to make this all happen.

<script type="text/javascript" src="scripts/jquery-1.2.6.min.js"></script>
 
<script type="text/javascript">
    $(document).ready(function() {
        $("#tbUsername").blur(function(event) {
            $.ajax({
                type: "POST",
                url: "Default.aspx/IsUserAvailable",
                data: "{'username': '" + $('#tbUsername').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    $('#valid').html("<img src='images/waiting.gif' alt='Checking username!'>");                       
                    var delay = function() {
                        AjaxSucceeded(msg);
                    };
 
                    setTimeout(delay, 2000);
                },
                error: AjaxFailed
            });
        });
    });
    function AjaxSucceeded(result) {
        if (result.d == true)
            $('#valid').html("<img src='images/available.gif' alt='Username available!'>");
        else
            $('#valid').html("<img src='images/taken.gif' alt='Username taken!'>");
    }
    function AjaxFailed(result) {
        alert(result.status + ' ' + result.statusText);
    }    
</script>

Here is where the magic happens.  Using jQuery we are getting a reference to tbUsername and adding blur event.  Adding the event through jQuery leads to better cross browser compatibility. 

Using jQuery.ajax we define our variables:

  1. type: “POST” – this ensures we are posting to the server
  2. url: “Default.aspx/IsUserAvailable” – sets the page and method we are calling
  3. contentType: “application/json; charset=utf-8”
  4. dataType: “json” – using JSON as the data type, this could be XML, etc.
  5. success: – here we are creating a function to determine what to do with the Response from the server i fit was successful
  6. error: – allows us to define an error method if something goes wrong.

Here is what our POST/RESPONSE looks like in debug mode with Firebug

POST:

usernamePost

You can see what we are sending, username defines the argument name and test is the value entered into the textbox.

RESPONSE:

usernameResponce

After successfully validating the username in the Web Method, it sends back a true.  For more information on what the d value is, give this blog post esconia a read.

Finally if the response was true, we set the html of the span to the success image, otherwise set it to taken!

I hope this code is a jump-off point to get you started with jQuery AJAX, JSON, and ASP.NET and gives you a glimpse at how powerful it can really be!  Posted below is the code in its entirely, please test it out and let me know what you think!

jQueryAJAXValidateUsernameWebMethod.zip (39.30 kb)

Tags:

ASP.NET 2.0 SubSonic Project Template With SQL Server 2005 Northwind DB

by aherrick 29. December 2008 01:39

I created this template mostly for myself so that when I am creating web demos/test projects I have a wired up SubSonic project ready to go.  Hopefully it will be useful for someone interested in getting started with SubSonic.  Setup is currently running SubSonic 2.0.3.  I have found this to be the most stable version to date.  I will be putting up a version 2.1 (and hopefully 3.0) template soon.

Rob Conery, SubSonic creator, has some great videos on getting started as well.  Check it out at http://subsonicproject.com

This solution is completely wired using ASP.NET 2.0 and SQL Server 2005.  I broke the solution up to into two projects (DAL and WEB).  This way seems to work well and allows for abstraction.  In order to run, make sure you are running the Northwind database (just run ins). 

Good luck and let me know if you have problems running the solution.

SubSonicSMall

SubSonicNorthwindDBTemplate.zip (869.28 kb)
InstallNorthwind.zip (274.19 kb)

Tags:

ASP.NET Programmatically Control MasterPage and CSS

by aherrick 22. December 2008 07:14

Working on a project I need the ability to programmatically change the web application's associated master page (and associated CSS).  Most of the pages in the application were content pages (derived from the content page) however some were just static pages.  Since there was no MasterPage assoicated with these static pages, dynamically assigning the CSS was the next best option.

I created a BasePage for ALL pages in the application to derive from. 

For the ContentPages (pages that point to a MasterPage) I created a method in the BasePage to assign the necessary master page.  This method is called in the Page_PreInit method of the content page.  See below.

        protected void Page_PreInit(object sender, EventArgs e)
        {
            // set master page
            this.SetMasterPage();
        }

SetMasterPage is a simple method to dynmically change the MasterPage...

        public void SetMasterPage()
        {
            // change master page

            // will return random number between 1-3...      
            int masterPage = RandomNumber(1, 4);

            string fullMaster = ResolveUrl(string.Format("~/Site{0}.master", masterPage));
            this.MasterPageFile = fullMaster;
        }

Dynamically set the CSS on the static pages in a similar matter.  In the code behind of the specific page, , call SetCSS in the Page_Init method.  Dynamically setting the CSS is very easy too...

        public void SetCSS()
        {
            // set CSS

            // ALL CSS has to be set programatically... 
            HtmlLink css = new HtmlLink();
            int cssNum = RandomNumber(1, 3);

            css.Href = ResolveUrl(string.Format("~/StyleSheet{0}.css", cssNum));
            css.Attributes["rel"] = "stylesheet";
            css.Attributes["type"] = "text/css";
            css.Attributes["media"] = "all";
            Page.Header.Controls.Add(css);
        }

Really that's all there is to it.  This code can be tweaked to suit your needs.  This gives a lot more flexibility than simply dynamically changing your CSS file.

Attached is the code

ControlMasterPagesProgramatically.zip (34.59 kb)

Tags:

C# Directory List Application

by aherrick 9. December 2008 11:11

I am releasing this application I created to help me organize my music collection.  It takes multiple paths and combines ever directory under each path into a single txt/csv file sorted alphabetically.  I had a little fun with some of the validation and colors to make it work a little more smoothly. 

dl

Usage:

  1. Select paths using Add
  2. Select output format (txt or csv)
  3. List is generated to same directory .exe is located

Attached is the .exe and full source code.  It is free for distribution and please feel free to tweak to your needs!

If I tweak this in the future I will post the updated code, consider this V1.0

Enjoy!

DirectoryListV1.0-FullSRC.zip (73.37 kb)
DirectoryListV1.0EXE.zip (12.18 kb)

Tags: ,

ASP.NET Control HTML Elements/Tags Programmatically

by aherrick 3. December 2008 06:34

I was working on a project and was looking for more control over the elements I was creating in the HTML.  More specifically, I had a MasterPage setup and I wanted all pages to have the same background image throughout the site.

Simple.  Add a runat=server to your markup.  See below. 

<div id="bgimg" runat="server">
</div>

You now have control of this element from the code-behind.

To add a background image to the div, you could do something like this:

bgimg.Style[HtmlTextWriterStyle.BackgroundImage] = ResolveUrl("~/images/bodyback.jpg");

The only thing to realize is what your generated markup is.  Asp.Net will auto-generate this tag to prevent naming collisions.  Just look out for it if you are trying to style the element with CSS or call it using javascript.

<div id="ctl00_bgimg" style="background-image:url(/HRR/images/bodyback.jpg);">
</div>

Enjoy!

Tags: ,



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen
Tweaked by ajondeck.NET

About the author

Andrew Herrick
I am a full time developer for Blue Horseshoe Solutions based out of Carmel, Indiana. I enjoy learning new technology and hope to give back with some of the cool things I pick up along the way.  Check me out on Stack Overflow!


Categories

None

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008