Dynamically add options to dropdown list using jQuery

Filed in Html | jquery Leave a comment

This post is going to be a fun little exercise, and is a technique that used to carry some overhead (in terms of postbacks and viewstate) back in the day. The objective is to provide users with a dropdownlist containing pre-selected options – but allow them to add their own options, and persist those options back to the database.

Ingredients:
1 – dropdownlist
1 – textbox
2 – divs
3 – links
3 – jquery functions
1 – controller method

First we will create our html form. So far there is nothing controversial here, we are simply creating one div to hold the dropdownlist and the “add” link, and another div to hold the textbox and save/cancel links. To keep it simple, we are going to make this a color list:

<div id="FavoriteColorsList">
<select name="FavoriteColor" id="FavoriteColor" style="width:350px;">
<option value=""> Choose your favorite color</option>
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
</select>
<a href="#" onclick="AddCustomFavoriteColor(); return false;">add my color</a>
</div>

<div id="CustomFavoriteColorform" style="display:none;">
<input type="text" id="CustomFavoriteColor" name="customFavoriteColor" style="width:250px;">&nbsp;&nbsp;
<a href="#" onclick="SaveCustomFavoriteColor(); return false;">save</a>&nbsp;&nbsp;
<a href="#" onclick="CancelCustomFavoriteColor(); return false;">cancel</a>
</div>

The expected behavior is to show the dropdown initially, and then once the user clicks the “add my color” link, to hide the dropdown div, and then display the textbox div. To make this happen, we have three jquery functions that are called from the links:


function AddCustomFavoriteColor() {
    $("#FavoriteColorsList").hide("fast");
    $("#CustomFavoriteColorform").show("fast");
    $("#CustomFavoriteColor").val("");
    $("#CustomFavoriteColor").focus();
}

function CancelCustomFavoriteColor() {
    $("#CustomFavoriteColor").val("");
    $("#FavoriteColorsList").show("fast");
    $("#CustomFavoriteColorform").hide("fast");
}

function SaveCustomFavoriteColor() {
    var opt = "<option value='" + $("#CustomFavoriteColor").val() + "'>" + $("#CustomFavoriteColor").val() + "</option>";

    $('#FavoriteColor').append(opt)
    $("#FavoriteColor").val($("#CustomFavoriteColor").val());

    $.post("/[YOUR-CONTROLLER]/[YOUR-METHOD]", { FavoriteColor: $("#CustomFavoriteColor").val() },
        function(data) {
            $("#CustomFavoriteColor").val("");
            $("#FavoriteColorsList").show("fast");
            $("#CustomFavoriteColorform").hide("fast");
        });
}

The last part is the server-side code to persist the saved value to the database. That is where you need to make sure you have some level of security, ideally something greater than what citibank rolled out.

Below is a video clip of the code in action:

Update textbox with ASP.NET, MVC, jQuery

Filed in ASP.NET MVC | jquery Leave a comment

This post arrives to you today from the awesome Hotel Dunn Inn in beautiful San Jose, Costa Rica! Best. Beds. Ever. It was time to clear the brain and work on some pet projects, and of course code.

In this sample we will look at updating values in textboxes, and then notifying the user of the results. The scenario would be having an Excel-style grid where the user can tab from field to field saving cell values with the onchange event.

Adding References

For this exercise, you just need a reference to the jquery library:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
1

<h2>Setting up the Html Form</h2>
We are going to add three textboxes--each with an onchange event--along with a div to hold the result. In real life, the 1, 2, and 3 values would be the item IDs.

1
    <div id="resultmessage" style="width:550px;"></div>
    Textbox 1<br />
    <input type="text" name="textbox1" id="textbox1" onchange="Update('1',this.value);" />
    <br /><br />
    Textbox 2<br />
    <input type="text" name="textbox2" id="textbox2" onchange="Update('2',this.value);" />
    <br /><br />
    Textbox 3<br />
    <input type="text" name="textbox3" id="textbox3" onchange="Update('3',this.value);" />
    <br /><br />

Whenever a user tabs off each box, it will trigger and update to the database. To do that, we add a jQuery function. The function is simple:

  • Use jQuery $.post to send the text change to your controller method
  • Check the result from the controller
  • Display the success or error message

Below is the entire function:

function Update(id, val) {
            $.post("/ControllerName/UpdateTextbox",
            {
                ID: id,
                Value: val
            },
            function(data) {
                <div style='color:blue;'>var myObject = eval('(' + data + ')');
                var saveresult = myObject;</div>
                if (saveresult != "") {
                    $("#resultmessage").html("<div style='display:block; background-color: Red; color: White; font-size: 18px; font-weight: bold; padding: 10px 10px 10px 10px;'>Oops! " + saveresult)
                    $("#resultmessage").show('slow');
                    setTimeout("$('#resultmessage').hide('slow');", 2500);
                }
                else {
                    $("#resultmessage").html("<div style='display:block; background-color: Green; color: White; font-size: 18px; font-weight: bold; padding: 10px 10px 10px 10px;'>Saved!")
                    $("#resultmessage").show('slow');
                    setTimeout("$('#resultmessage').hide('slow');", 2500);
                }
            });
        }

The final piece is a method in a controller–which is pretty vanilla–with one minor twist: instead of an ActionResult, we are going to use a JsonResult:

    public JsonResult UpdateTextbox(string ID, string Value)
    {
        //This is where you would update the database
        string result = (Value.ToLower().StartsWith("r")) ? "ID doesn't exist" : "";
        return Json(result);
    }

Below is a little video clip of the sample in action.

Check username availability with jQuery, ASP.NET MVC, C#

Filed in ASP.NET MVC | C# | jquery 5 Comments

This post shows how to add dynamic username availability lookup to an ASP.NET MVC view, using jQuery and C#. There are three parts to the solution: the html form, jQuery function, and the controller.

Html form

This part is pretty simple: a textbox for the username field with an onchange event, a div to hold the lookup results, and a lookup button.

    <h3>Username</h3>
    <%= Html.TextBox("Username", "", new { @onchange = "CheckAvailability()" })%>
    <div style="display:inline;" id="usernamelookupresult"></div><br/>
    <input type="button" value="Check Availability" onclick="CheckAvailability()" />
</code>

jQuery Username Lookup

This is where the magic happens. Well, nothing really magical, just a jQuery call to a controller, passing in the username value. In the example below, the function processing the result looks for a 0 to indicate the username is available. You can modify that to be whatever you want.


    function CheckAvailability() {
        $.post("/Home/CheckAvailability",
        { Username: $("#Username").val()},
            function(data) {
                var myObject = eval('(' + data + ')');
                var newid = myObject;
                if (newid == 0) {
                    $("#usernamelookupresult").html("<font color='green'>Available :-D</font>")
                }
                else {
                    $("#usernamelookupresult").html("<font color='red'>Taken :-(</font>")
                }
        });
    }

Controller

This is where your business logic lives, and is where the lookup occurs. For this exercise, we are keeping it simple, but you can see where to add your database lookup.


    public ActionResult CheckAvailability(string Username)
    {
            int Taken = 0;
            //  This is where you add your database lookup
            if (Username == "username")
            {
                Taken = 1;
            }
            return Json(Taken);
    }

Download Sample Application

Below is a quick clip to show the code from the downloadable sample in action:

,

Latitude and Longitude Lookup with jQuery, C#, ASP.NET MVC

Filed in ASP.NET MVC | C# | jquery 13 Comments

I recently had a requirement for a mapping application that required me to pass in longitude and latitude coordinates. It wasn’t realistic to have the user look those values up, so I had to figure out a way to automatically lookup the coordinates given a zip code.

There are tons of pay services (some of which I use), but for this project needed something free. I stumbled on http://www.geonames.org/ which has a great service. You can see their webservice documentation here: http://www.geonames.org/export/web-services.html.

Ok, let’s get started:

Web form

These are the input fields we will use to perform the lookup. We are going to have three textboxes, one which has an onchange event.

    Zip Code<br/>
    <%= Html.TextBox("Zip", "", new { @onchange = "LookupCoordinates(this.value)" })%>
    <br/><br/>
    Latitude: <%= Html.TextBox("Lat") %>,
    Longitude:<%= Html.TextBox("Lon") %>

jQuery Function

This function is responsible for looking up the latitude and longitude coordinates, and populating the results into the textboxes. Note that I’m wiring in US as the country below. The country is an optional parameter, when entered gives you more relevant results. Otherwise you are going to have to write some kind of loop.

    function LookupCoordinates(zip) {
            $.post("/Home/LookupCoordinates",
            { Zip: zip, Country: "US" },
            function(data) {
                var result = eval('(' + data + ')');
                var coordinates = result.split(",");
                $("#Lat").val(coordinates[0]);
                $("#Lon").val(coordinates[1]);
            });
        }

Call Geonames.org

In this sample, the call to geonames.org is wired into the controller. In real life, you probably want to wrap it in some kind of helper or service class. There are a few using statements you will need:

using System.IO;
using System.Net;
using System.Xml;

The above namespaces are important because we are going to make a WebRequest, and then parse the Xml results. The webservice method we are going to call is:

http://ws.geonames.org/postalCodeSearch?postalcode=78702&maxRows=10&country=US

Since we know the Zip and the Country, we should in theory only get 1 result. Below is a screenshot of the elements returned for our 78702 search (Austin):

Onto the method:

    public ActionResult LookupCoordinates(string Zip, string Country)
    {
        string Lat = "";
        string Lon = "";
        string PostUrl = "http://ws.geonames.org/postalCodeSearch?postalcode=" + Zip + "&maxRows=10&country=" + Country;
        WebResponse webResponse = webRequest.GetResponse();
        if (webResponse == null)
        { }
        else
        {
            StreamReader sr = new StreamReader(webResponse.GetResponseStream());
            string Result = sr.ReadToEnd().Trim();
            if (Result != "")
            {
                // Load the response into an XML doc
                XmlDocument xdoc = new XmlDocument();
                xdoc.LoadXml(Result);
                //  Navigate to latitude node
                XmlNodeList name = xdoc.GetElementsByTagName("lat");
                if (name.Count > 0)
                {
                    Lat = name[0].InnerText;
                }
                //  Navigate to longitude node
                name = xdoc.GetElementsByTagName("lng");
                if (name.Count > 0)
                {
                     Lon = name[0].InnerText;
                }
            }
        }
        return Json(Lat + "," + Lon);
    }

From there, the method returns the latitude and longitude in a comma separated string, the javascript call splits the results and populates each respective text box. Below is a video preview – really short, really lame, but you get to see the code in action:

,

Advanced Auto-Complete with jQuery, MVC, and thumbnail pictures

Filed in ASP.NET MVC | C# | jquery 1 Comment

This post extends an earlier post I wrote for a basic auto complete/auto suggest textbox.

In this version, we are going to return a list of our favorite social media websites, by adding a new method to the prior post’s controller which allows thumbnail pictures to appear in the auto-suggest list.

New MVC Controller Method

We are going to create another JsonResult method in the controller to lookup the websites. For demo purposes, we are going to hardcode the list. In real life, you probably will be pulling the list from a database, which is covered in the earlier post.

public JsonResult GetWebsites(string searchString)
        {
            StringBuilder sb = new StringBuilder();

            //
            //  Creating a static list here for demo purposes. In your system, you probably
            //  will have images generated from the database, disk, flickr, etc.
            //
            List<string> sites = new List<string>();
            sites.Add("Blogger");
            sites.Add("Delicious");
            sites.Add("Digg");
            sites.Add("Facebook");
            sites.Add("Flickr");
            sites.Add("FriendFeed");
            sites.Add("Friendster");
            sites.Add("LinkedIn");
            sites.Add("MySpace");
            sites.Add("StumbleUpon");
            sites.Add("Technorati");
            sites.Add("Twitter");
            sites.Add("Yahoo");
            sites.Add("Yelp");
            sites.Add("YouTube");

            for (int i = 0; i < sites.Count; i++)
            {
                if (sites[i].ToLower().StartsWith(searchString.ToLower()))
                {
                    string ImageUrl = "/images/" + sites[i].ToString() + ".png";
                    sb.Append("<li onClick=\"fill('" + sites[i].ToString() + "');\"><img src=\"" + ImageUrl + "\" border=\"0\">&nbsp;" + sites[i].ToString() + "</li>");
                }
            }
            return Json(sb.ToString());
        }

The big addition is adding the <img> tag into the list item value, that’s it :-) Now for tweaking the jquery function from the orinigal post to call the new method:

function lookup(inputString) {
    $.post(“/LookupCode/GetWebsites”, { searchString: “” + inputString + “”},
    function(data) {
        var myObject = eval(‘(‘ + data + ‘)’);
        if (data.length > 0) {
        $(“#suggestions”).show();
        $( “#autoSuggestionsList”).html(‘<ul>’ + myObject + ‘</ul>’);
        }
    });
}

You can download the fully-function code project here:

Download Sample Application

Below is a video clip of the sample in action:

, , , ,

Dynamically populate dropdownlist in ASP.NET MVC

Filed in ASP.NET MVC | C# | jquery 5 Comments

There are a few different ways to dynamically populate a dropdownlist in MVC: you could use a classic ASP old school loop with a bunch of response.writes, you can store the list’s collection into ViewData and use an html helper, or you can use jquery. We’ll look at samples for each way.

Populate dropdownlist with response.writes

We will start out with the least elegant solution, but it does work nonetheless. So this is the code inside your view:

        <select id="ID" name="ID">
            <%
             Contact[] contacts = Contact.FindAll();
             for(int i=0; i < contacts.length;i++){ %>
             <option value="\&quot;&quot;">" + contacts[i].FullName + "</option>
             <% } %>
        </select>

Populate dropdownlist with ViewData

This method is better, and is baked right into MVC. The downside is you can only use it in MVC, and involves using ViewData (detailed ViewData definition), the View and the Controller. First we prepare the Controller:

public ActionResult Index()
{
    Contact[] contacts = Contact.FindAll();
    ViewData["Contacts"] = new SelectList(contacts,"ID","FullName", <span style="color:red;">[Selectedvalue]</span>);
    return View();
}

Selectedvalue – this optional parameter can be used to select a specific value, useful if you are displaying a form in edit mode.

The last part is binding the ViewData contents to a dropdownlist in the View:

    <%= Html.DropDownList("Contacts") %>

Populate dropdownlist with jQuery

This is the most flexible of the three, and can be used in web forms, php, MVC, etc. This method involves a jquery call in javascript:

    <script language="javascript" type="text/javascript">
        $(function() {
            $.getJSON("YOURPATH/Contact/ContactList", function(data) {
                var items = "<option selected></option>";
                $.each(data, function(i, item) {
                    items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
                });
                $("#ContactID").html(items);
        });
    </script>

The above function calls the ContactList method, which returns a ListItem collection. You then loop through the result, and add the options. Finally, the html contents of the dropdownlist are set. The MVC method that returns the contact list looks like this:

        public ActionResult OrganizationList()
        {
            Contact[] contacts = Contact.FindAll();
            if (HttpContext.Request.IsAjaxRequest())
            {
                return Json(new SelectList(contacts, "ID", "FullName"));
            }
            return View(contacts);
        }

, ,

TinyMCE samples with ASP.NET MVC

Filed in ASP.NET MVC | C# | Html | jquery 3 Comments

After using Telerik’s RadEditor control for years with all my asp.net web form applications, I found myself looking for a javascript alternative when I moved up to MVC. Having paid top dollar for RadEditor (which is a fine product!) and never used TinyMCE, I couldn’t imagine something free could be that good. Well it is! And really easy to use–whether in c#, vb, php, etc.–plus no nasty viewstate to bloat your page.

You can download code samples here.

Downloading files

The first step is visiting the TinyMCE website and downloading the files: http://tinymce.moxiecode.com/download.php. Make sure you select the “jQuery package” link.

Extract the zip file, and copy the actual script files (tinymce\jscripts directory) into a folder in your project. I typically have a scripts folder, and create a “tiny_mce” subdirectory to hold the files.

Setting references

If you have a master page, just add the following line into the top of the master page:

<script type="text/javascript" src="<%=Url.Content("~/scripts/tiny_mce/tiny_mce.js") %>"></script>

Otherwise add the same line to the top of each page that will use the TinyMCE editor. Next, you initialize the textareas to use TinyMCE. The following javascript snippet initializes every textarea on the page (or every single page if added in the master page) using the defaults:

<script type="text/javascript">

tinyMCE.init({
mode: "textareas",
theme: "advanced"
});

We will dive deeper into configuring the available buttons.

Samples

TinyMCE in a dialog

One common need is allowing users to edit text in a modal window. Combining jQuery’s dialog (http://www.billsternberger.net/asp-net-mvc/jquery-modal-dialog-without-the-x-button/) with TinyMCE is a simple and elegant solution.

First, initialize the dialog and add the click event to show the editor:

$(function() {
$("#texteditorform").dialog({
height: 300,
width: 520,
autoOpen: false
});
});

function ShowModalEditor() {
$("#texteditorform").dialog('open');
}

Next, add the button to show the editor:

<a onclick="ShowModalEditor()" href="#">Show modal text editor</a>

Next, create the dialog div with the textarea inside:

<div title="Text Editor" id="texteditorform">
Add something below:<br />
<textarea rows="5" cols="25" id="modalTextarea"&gt;&lt;/textarea><br /><br />
<input type="button" onclick="CloseModalEditor()" value="Save" /><br />
</div>

Toggle TinyMCE editor and textarea

Occasionally you may want to allow users to toggle between the advanced editor and the regular textarea. There is a simple function to pull this off. First, add the javascript function to handle the toggling:

function toggleEditor(id) {
if (!tinyMCE.get(id)) {
tinyMCE.execCommand('mceAddControl', false, id);
}
else {
tinyMCE.execCommand('mceRemoveControl', false, id);
}
}

Next, add a button that will allow the user to toggle:

<a href="#" onclick="javascript:toggleEditor('toggleTextarea');">Toggle</a>

Validate input value

To validate the user input of a TinyMCE-enabled editor, the standard jqeuery $(“#field”).val() method won’t work.  Instead, you need to use a TinyMCE method instead:

var theValue = tinyMCE.get('valueTextarea').getContent();

Make TinyMCE editor Read Only

Should you need to initialize a TinyMCE editor as readonly, all you have to do is add a line to the init:

$(function() {
$("#texteditorform").dialog({
<span style="color: #0000ff;">readonly: true</span>
});
});

Customize TinyMCE Editor buttons

Include underline, copy, paste, and other formatting options in toolbar

Customizing which buttons appear on the toolbar is really easy, below are some sample configurations. Setting and aligning the buttons are done in theme_advanced properties.

tinyMCE.init({
mode: "textareas",
theme: "advanced",
plugins: "style,iespell,searchreplace,contextmenu,paste,html",

//  Theme options #1
theme_advanced_buttons1: "bold,italic,underline,formatselect,cut,copy,paste,pastetext,pasteword",
theme_advanced_buttons2: "fontselect,fontsizeselect,|,link,unlink,code",
theme_advanced_buttons3: "justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist",
theme_advanced_buttons4: "",

//Theme options #2
theme_advanced_buttons1: "bold,italic,underline,formatselect,cut,copy,paste,|,fontselect,fontsizeselect",
theme_advanced_buttons2: "",

// Align and place toolbar
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_resizing: true,
readonly: false
});

The above are the two standard configurations I use. To view a full list of buttons, click here.

, , , ,

jQuery Modal Dialog without the x button

Filed in ASP.NET MVC | CSS | Html | jquery 1 Comment

Found myself wanting to provide a modal dialog (preferably in jQuery of course!) to gate first-time page visitors. The requirements were:

  • On page load, display modal dialog with a form to request basic contact information
  • Disable the “esc” key to force the user to enter the info or click a “no thanks” button
  • Hide the x which appears in the dialog

My approach was using the jQuery dialog, $.post to send the contact information to my controller and then hide the modal dialog. We can do this in three easy steps:

Configure jQuery dialog

The jQuery dialog has some nifty properties out of the box to handle things like, disabling the esc key, displaying the modal dialog on page load, along with the usual suspects: style, size, resizing. Here is what my call looks like, with our special properties highlighted in blue:

$(function() {
$("#registrationform").dialog({
height: 470,
width: 520,
resizable: false,
<span style="color: #0000ff;">autoOpen</span>: true,
<span style="color: #0000ff;">modal</span>: true,
<span style="color: #0000ff;">closeOnEscape</span>: false
});
});
1

<h2>Hide the dialog's x button</h2>
The dialog shows a x in the top right corner by default, and there are no properties to hide it. The best way I found is using some old fashioned CSS:

1
<style>
.ui-dialog .ui-dialog-titlebar-close { display: none; }
</style>

So that is all it takes to set the dialog to display on page load and prevent users from escaping out or closing the form. Next is sending the results back to the server, which is pretty simple using $.post.

Post back to the server and process results

First, you need to handle a button’s click event, and have some logic to process the result. I primarily develop in ASP.NET MVC, but you could very easily use this technique in PHP, Ruby, etc. Here is the function:

function Register() {
$.post("/Contact/RegisterGuest",
{
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
Email: $("#Email").val(),
Phone: $("#Phone").val()
},
function(data) {
Result = eval('(' + data + ')');

if (Result == "") {
$('#registrationform').dialog('close');
$("#registrationform").hide("fast");
$("#result").show("fast");
}
else {
$("#errorblock").html("<ul>" + Result + "</u>");
}
});
}

Breaking down the function, we’re posting to the RegisterGuest method for the Contact controller, with the FirstName, LastName, Email, and Phone fields, and processing the result. Typically I’ll return any errors in listitem tags, so an empty Result means no errors occurred on the server-side. If the Result variable is empty, we hide the dialog and show whatever was hidden. Otherwise we set the html value for a pre-defined div to be the error list.

, ,

Use jQuery to change a form’s action url

Filed in ASP.NET MVC | Html | jquery 5 Comments

This is another quick and dirty post, more for future reference when I need to access this snippet again! The scenario is if you have one form on a page, but want to change the target on the fly for whatever reason. Here are the two magical lines:

$("form").attr("action", "/ControllerName/Method");
$("form").submit();

,

Microsoft and Google jQuery CDN Link

Filed in Html | jquery 2 Comments

So what is a Content Delivery Network (CDN)?

In a nutshell, a CDN is a network of computers strategically placed around the world that serve up cached content to users. The content types include images, videos, style sheets, and in this case,  script libraries. As you can imagine, your pages will load faster when browsers are downloading these objects from a server closer to them than from one central location half way across the globe.

When it comes to jquery, there are two main CDNs I’ll reference in projects: Microsoft’s and Google’s. Adding a reference to either CDN is really easy. All you have to do is add one of the following lines into your page header.

Microsoft’s jQuery CDN reference:

<script src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js” type=”text/javascript”></script>

Google’s jQuery CDN reference:

<script src=”http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js” type=”text/javascript”></script>

That’s it!

, , , ,

TOP