loads of useful information, examples and tutorials pertaining to web development utilizing asp.net, c#, vb, css, xhtml, javascript, sql, xml, ajax and everything else...

 



Advertise Here
C-Sharpener.com - Programming is Easy!  Learn Asp.Net & C# in just days, Guaranteed!

jQuery moveTo() plugin

by naspinski 2/6/2013 3:26:00 PM

simple way to move an element from A to B

Say you have these elements:
<ul id="A">
    <li id="L1">Stan</li>
    <li id="L2">Arnold</li>
</ul>
<ul id="B">
</ul>

And you want to move 'L1' (Stan) to ul 'B' - using this simple short plugin:
(function ($) {
    $.fn.moveTo = function (selector) {
        return this.each(function () {
            var element = $(this).detach();
            $(selector).append(element);
        });
    };
})(jQuery);

You can do that with this:
$('#L1').moveTo('#B');

Now you have this in your DOM:
<ul id="A">
    <li id="L2">Arnold</li>
</ul>
<ul id="B">
    <li id="L1">Stan</li>
</ul>

Or, similarly, you can do something like this:
$('li').moveTo('#B');

Now you have this in your DOM:
<ul id="A">
</ul>
<ul id="B">
    <li id="L1">Stan</li>
    <li id="L2">Arnold</li>
</ul>

Monitoring a DOM Element for Modification with jQuery

by naspinski 9/29/2011 4:47:00 PM

'watching' an element for any change within it

I recently ran into a situation where I had to modify a site that relied on an incredibly obfuscated and impossible to understand javascript file. I had to add in some elements after everything was populated with some function I didn't get, so I had to wait until a specific element was populated to do anything. Turns out the DOMNodeInserted event is what I needed:
var title = $("b.facility");
var title = $('#title');//the element I want to monitor
title.bind('DOMNodeInserted', function(e) {
    alert('element now contains: ' + $(e.target).html());
});

Pretty simple, but took me forever to figure out...

Inline AJAX DropDown and Text Editing with Asp.Net MVC and jQuery

by naspinski 7/12/2010 5:31:00 AM

including how to use a database to populate the dropdown

First thing is first, you will need to download jQuery and the Jeditable plugin (I prefer to refer to it as the Jedi-Table!). Be sure to put these references in your View (or Masterpage). Next, you have to set up a view on which to use an inline edit. I find that I often want to use this approach on tables of information. For this View, I will set it to use an IEnumerable of an Item I have called 'ItemOwner' (this is arbitrary and does not really matter). It will be a simple table that lists the Name and the Country of the owner, both of which will be editable inline. Here is the Index in my ExampleController.cs:
myDataContext db = new myDataContext();
public ActionResult Index()
{
    // get the info for the 'Countries' dropdown:
    ViewData["countries"] = db.Countries
        .Select(x => new SelectListItem() 
        { 
            Text = x.Name, 
            Value = x.Id.ToString() 
        }).ToJson();

    // get the 'ItemOwners' I am interested in:
    var owners = db.ItemOwners.Take(3);

    return View(owners);
}

As you can see there, I am also pulling the countries from the database and throwing them into the ViewState - we will get to this later. Since the Country is actually a foreign key relation, the value is set to an integer which is the identity field in the database. It is also using a .ToJson() extension which takes a IEnumerable<SelectListItem> and puts it into a simple JSON string that I use which is here:
public static string 
    ToJson(this IEnumerable<SelectListItem> slis)
{
    string output = "{";
    if (slis != null)
    {
        for (int i = 0; i < slis.Count(); i++)
        {    
            output += " '" + slis.Skip(i)
            .First().Value + "': '" + 
            slis.Skip(i).First().Text + "'" + 
            (i == slis.Count() - 1 ? " " : ",");
        }
    }
    return output += "}";
}

There is probably a better way to do that... but I don't know it?!

I am also pulling 3 ItemOwners from the database, I know this is silly, but it just an example. Here is how I am displaying them in the view:
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Country</th>
        </tr>
    </thead>
    <tbody>
        <% foreach(var owner in Model) { %>
        <tr>
            <td><%= owner.Name %></td>
            <td><%= owner.Country.Abbreviation %></td>
        </tr>
        <% } %>
    </tbody>
</table>

Now that there is a simple table we want to make it a bit more interactive. Since we aregoing to make all of these fields editable, we need to add in a way to distinguish exactly what they are. To do that, we will need two things: the id of the item they are editing, and the type of inline editing we will be doing (i.e. dropdown or text input). So to do that, let's add in a few css classes and an identifieng ID:
<td id="name<%= owner.Id %>" class="editable text">
    <%= owner.Name %></td>
<td id="ctry<%= owner.Id %>" class="editable dropdown">
    <%= owner.Country.Abbreviation %></td>

And now add a little css to make them appear to be clickable:
td.editable:hover 
{ cursor:pointer; background-color:Orange; }

Now they all look like you can click on them, so we can move on to making the click actually do something.

This is where the jQuery comes in, and it is very simple. I have made these 'helper' methods in Javascript to make all of my inline calls centrally controllable, I keep this in my sites script folder so if I change one inline edit, I change them all; it also makes for more readable Javascript on each page.
function InlineDropdown(collectionToDropDown, ajaxAddress, dropDownDataSet) {
    collectionToDropDown.editable(ajaxAddress,
    {
        data: dropDownDataSet,
        type: 'select',
        indicator: 'saving...',
        tooltip: 'click to edit...',
        submit: 'Save',
        style: 'inherit',
        placeholder: 'click to edit'
    });
}

function InlineTextbox(collectionToInline, ajaxAddress) {
    collectionToInline.editable(ajaxAddress, 
    {
        indicator: 'saving...',
        tooltip: 'click to edit...',
        style: 'inherit',
        placeholder: 'click to edit'
    });
}

function InlineTextarea(collectionToInline, ajaxAddress) {
    collectionToInline.editable(ajaxAddress, 
    {
        type        : 'textarea',
        rows        : 4,
        indicator   : 'saving...',
        tooltip     : 'click to edit...',
        style       : 'inherit',
        submit      : 'Save',
        onblur      : 'ignore',
        placeholder : 'click to edit'
    });
}

Obviously you can read all about the options on the Jeditable page, but this is how I set them. Also notice I have a InineTextarea included as well for a textarea which is not covered here but works the exact same.

Now the jQuery calls are almost trivial:
InlineTextbox(
    $('td.editable.text'), 
    "<%= Url.Content("~/Ajax/ItemOwner.ashx") %>"
);

InlineDropdown(
    $('td.editable.dropdown'), 
    "<%= Url.Content("~/Ajax/ItemOwner.ashx") %>", 
    <%= ViewData["countries"].ToString() %>
);

What that is doing is sending the POST requests to the specified address. The POST contains a few things:
  • id - the id of the element that sent the request
  • value - the new value passed by the element
We are also passing more information there - remember that we passed both the type of field to edit and the id of the ItemOwner to edit, ie [name837] which emans we want to edit the Name field of ItemOwner 837. So we simply set up an ashx handler (which we specified above) to do the dirty work:
public void ProcessRequest(HttpContext context)
{
    string newValue;
    try
    {
        myDataContext db = new myDataContext();
        string elementId = context.Request.Form["id"];

        // since we made the first 4 of the id the 'field' whic to edit
        // we can just pull the first 4 letters for use in our switch:
        string fieldToEdit = elementId.Substring(0, 4);

        //now take anything after those 4 and it is the Id:
        int idToEdit = Convert.ToInt32(elementId.Remove(0, 4));

        // the value is simply a string:
        newValue = context.Request.Form["value"].Trim();

        // now that we have the id, get the ItemOwner from the db
        ItemOwner owner = db.ItemOwners.FirstOrDefault(x => x.Id == idToEdit);

        // after all is said and done, we will return newValue to the user so the field
        // looks as if the change has taken place (which it has)

        // using the field we pulled above, decide what to do:
        switch (fieldToEdit)
        {
            // name is easy
            case "name": owner.Name = newValue; break;

            // since the country is an integer foreign key, we need to Convert.ToInt32:
            case "ctry":
                owner.CountryId = Convert.ToInt32(newValue);
                // now that we have recorded the value, we want to return the text to
                // the user and not the id value which would make no sense
                newValue = db.Countries.FirstOrDefault(x => x.Id == owner.CountryId).Abbreviation;
                break;
            // if it wasn't caught, something is wrong:
            default: throw new Exception("invalid fieldToEdit passed");
        }

        db.SubmitChanges(); // save it
    }
    // now if an exceptions were reported, the user can see what happened
    // this also inform the user nothing was saved
    // you could easily make this not reported to the user and logged elsewhere
    catch (Exception ex) 
    { newValue = "Error: " + ex.Message + " [nothing written to db]"; }

    //now return what you want in the element:
    context.Response.Write(newValue);       
}

And that is all it takes.

Automatically refresh your user's Session behind the scenes using jQuery and Asp.Net

by naspinski 5/15/2009 10:17:00 AM

Incredibly simple script will keep your user's Session alive without any worries

Now this is something that may or may not be useful to a lot of people, depending on you situation, you may want the user to elect to refresh their Session or not (like banks usually do); but this is for applications that may have a lot of idle time and users are annoyed with their Sessions dying... considering most users don't know what a Session is, but they know that the application stops working correctly.

It uses jQuery and is incredibly simple, just a few lines of code, and no screen flicker or any annoyance to the user at all; ignorance is bliss. First I include the following in the code-behind in any page you need to keep refreshed (works on masterpages as well):

code-behind
protected int timeout;
protected void Page_Load(object sender, EventArgs e)
{
    // one minute prior to timeout (milliseconds)
    timeout = (Session.Timeout * 60000) - 60000; 
}

Then add this jQuery to your script:

aspx or master
var to;
$().ready(function() {
  to = setTimeout("TimedOut()", <%= timeout %> );
});
            
function TimedOut() {
  $.post( "refresh_session.aspx", null,
    function(data) { 
      if(data == "success") {
        to = setTimeout("TimedOut()", <%= timeout %>);
      }
      else { $("#timeout").slideDown('fast'); }
    }
  );
}

Notice that the jQuery calls the $.post() function, where it calls the page refresh_session.aspx. That page does only one thing: Response.Write("success"); so if data comes back and it does not equal 'success' (something went wrong) it then stops the cycle of checking for timeout and shows my 'timeout' div that tells the user it is not a current session.

infinitely refreshing session...

Yup, it is just that easy. The code-behind gets the Session.Timeout, and subtracts one minute from it, this is when the refresh will be triggered. Inside the script, the setTimeout() call will then wait that amount of time and use the jQuery $.post() to hit the page in in turn refresh the Session; once that is done, it starts the cycle over again, so it should repeat on into infinite. And since this is all done via a jQuery ajax call, there is no evidence to the user this is even happening, no flicker or popup, nothing.

Use jQuery to add all the values in a table column

by naspinski 5/8/2009 10:53:00 AM

simple way to get the total for a table

There are a lot of times when a table of data needs to be added up, or a summary provided; for Asp.Net users specifically, when you are using a dynamic GridView. Using jQuery, we can do this in just a few lines of code. If you don't care how it's done, skip to the bottom for a quick function to do the work for you. Here is a quick example:
nameageweightbenchpress
stan27177325
rj3013595
jose29230375

agesweightsbenchpresses
86542795

The first table is just a normal table holding the data, the second table is filled dynamically with jQuery adding up the columns. Yes, the numbers are real... RJ needs to hit the gym. Here is the jQuery to get these sums the manual way:
//these will hold the totals
var ages = 0;
var weights = 0;
var benchpresses = 0;

//reference the rows you want to add
//this will not include the header row
var rows = $("#data tr:gt(0)");
rows.children("td:nth-child(2)").each(function() {
    //each time we add the cell to the total
    ages += parseInt($(this).html());
});
rows.children("td:nth-child(3)").each(function() {
    weights += parseInt($(this).html());
});
rows.children("td:nth-child(4)").each(function() {
    benchpresses += parseInt($(this).html());
});

//then output them to the elements
$("#ages").html(ages);
$("#weights").html(weights);
$("#benchpresses").html(benchpresses);

First, I grabbed the table and each of it's rows; I also skipped the first row with the :gt() selector; I am grabbing all rows in #data (the id of the table with the data in it) greater than index '0' (the header that we don't want to include in the calculation). Also notice that I grabbed var rows = $("#data tr:gt(0)"); just once since we would be looping through it 3 times, there is no need to call it each time we sum a column; if I were just doing one column, I wouldn't use an extra line to place this into a var.

Next, I iterate through each cell using children() grabbing the correct index with :nth-child(); one thing I found strange was that though gt() started with a 0-based index, this uses a 1-based index.

Last, using the each() loop, I simply added the cell value to the total, then dumped them out to the cells I had reserved for the totals. All very simple and really only a few lines of jQuery to get it done.

function

If you don't really care how it works and just want a little snippet to get it to work, here you go:
function sumOfColumns(tableID, columnIndex, hasHeader) {
  var tot = 0;
  $("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
  .children("td:nth-child(" + columnIndex + ")")
  .each(function() {
    tot += parseInt($(this).html());
  });
  return tot;
}

It takes in 3 arguments, and returns the sum of the columns:
  • tableID [string] id of the table
  • columnIndex [int] 1-based column index to sum up
  • hasHeader [bool] if the table has a header to exclude

The same thing above would be accomplished like this (though this is less efficient as jQuery is selcting the same table 3 times):
$("#ages").html(sumOfColumns("data", 2, true));
$("#weights").html(sumOfColumns("data", 3, true));
$("#benchpresses").html(sumOfColumns("data", 4, true));

As you can see, my function uses integers, so change it if you need to.