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:

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!

, , , ,

Dynamically Changing the iframe src in jQuery

Filed in Html | jquery 1 Comment

This little function allows you to dynamically change the content of an iframe, using jQuery and javascript. It is perfect if you have a single page where you want to preview other websites without navigating away. To pull this off, you need a textbox, a link, and an iframe:

Enter website url below:<br/>
<input type="text" value="http://www.google.com" name="ifrmSite" id="ifrmsite"/> <a href="#" onclick="Navigate()">Navigate</a>
<br /><br />
<iframe name="iframe1" id="iframe1" src="http://www.google.com" width="600" height="700" scrolling="auto">
</iframe>

Next we add the javascript:

function Navigate() {
var newurl = $('#ifrmSite').val();
$('#iframe1').attr('src', newurl);
window.frames["iframe1"].location.reload();
}

And we’re done!

, ,

Javascript, jQuery Rich text editor

Filed in C# | Html | jquery Leave a comment

I did a post earlier today (yes, I’m on a roll while jr. is sleeping!) on my Top 10 favorite jQuery functions and plugins. This post is dedicated to one of them: TinyMCE. In the past I’ve used editors like Telerik’s RAD Editor and obout’s Html Editor, both very powerful editors. I was turned on to TinyMCE not too long ago, and haven’t looked back since.

Integrating TinyMCE into any ASP.NET project (MVC included) is really easy, this post will cover the basics of setting up TinyMCE, and then some of the different variations available.

Setup TinyMCE

After you download TinyMCE, copy all the files into your project. Typically I’ll drop the TinyMCE folder into my “Scripts” directory. Once copied, you add a reference in either your page’s header:

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

<h2>Initialize TinyMCE</h2>
This is where the fun begins. You can show all the possible buttons, or just a subset of buttons if you need to keep it simple. Below is a "keep it simple" scenario, where only the most basic buttons are presented to the user:

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

// Theme options
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_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_resizing: true,
readonly: false
});

The theme_advanced_buttons1 – 4 represent the rows where the buttons will appear. If you have a really wide textarea, you could theoretically show all the buttons on a single row. Consult the TinyMCE documentation for a detailed list of every single button.

Next is the generic “advanced” configuration I’ll use when I have a more savvy user. It gives users a html button so they can modify the markup:

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

theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_resizing: true,
readonly: false
});

There are also times where I want to keep the custom toolbar, but also allow the user to show/hide the html. To accomplish that, you can add this hyperlink:

<a href="#" onclick="ToggleEditor('textareaID');">Show/Hide Html</a>

And this function:

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

, , ,

Using jQuery to enable and disable radio buttons onclick

Filed in Html | jquery Leave a comment

This is by far the funnest pieces of code I’ve written in a long time. So simple, so stupid, so useful! The scenario is you want users to click a radio button from a series of options…but only after they choose a parent radio button. In this example we want the user to select only one city from one state.

Add the radio buttons

I’m going to keep this simple, so we’ll have only two parent radio buttons:

<input type="radio" name="rdoState" value="Texas"  onclick="EnableTexas()" />
<div id="DivTexas">
<input type="radio" name="rdoTexas" value="Austin" />Austin<br/>
<input type="radio" name="rdoTexas" value="Dallas" />Dallas<br/>
<input type="radio" name="rdoTexas" value="Houston" />Houston<br/>
</div>
<br/><br/>
<input type="radio" name="rdoState" value="Virginia"  onclick="EnableVirginia()" />
<div id="DivVirginia">
<input type="radio" name="rdoVirginia" value="Arlington" />Arlington<br/>
<input type="radio" name="rdoVirginia" value="McLean" />McLean<br/>
<input type="radio" name="rdoVirginia" value="Reston" />Reston<br/>
</div>

Add jQuery function for onclick event

We are going to add two functions, and one initialization routine to disable all the child radio buttons by default. First, we initialize everything to be unchecked and disabled, pretty self-explanatory:

$(function() {
//init Texas
$('#DivTexas :input').attr('checked', false);
$('#DivTexas :input').attr('disabled', true);
//init Virginia
$('#DivVirginia :input').attr('checked', false);
$('#DivVirginia :input').attr('disabled', true);
});

Next we add the two onclick functions:

function EnableTexas()
{
//disable Virginia options
$('#DivVirginia :input').attr('checked', false);
$('#DivVirginia :input').attr('disabled', true);
//enable Texas options
$('#DivTexas :input').removeAttr('disabled');
}

function EnableVirginia()
{
//disable Texas options
$('#DivTexas :input').attr('checked', false);
$('#DivTexas :input').attr('disabled', true);
//enable Virginia options
$('#DivVirginia :input').removeAttr('disabled');
}

,

Top 10 jQuery Functions and Plugins (Part I)

Filed in Html | jquery 1 Comment

The following is a set of jQuery shortcuts I use at some point on a daily basis.

10. appendTo()

While there are many ways to use appendTo(), I find myself taking advantage of it when dealing with dual listboxes. With that one little command, I can move listitems from one listbox to another with no crazy loops. To illustrate the ease of use, here the entire function corresponding to the “add all items” button:

jQuery(“#availableItems option”).appendTo(“#selectedItems”);

Read more here: http://docs.jquery.com/Manipulation/appendTo

9. html()

The html attribute allows you to get or set the innerHTML of an element. Typically I’ll have a div to handle some kind of validation results, and populate it based upon some logic. For example, here is a div to hold the results:

<div id=”someresults” style=”display:none;”></div>

Then some function to populate it, in this case, display an error:

function someFunction()
{
$(“#someresults”).show();
$(“#someresults”).html(“<h2 style=’color:red;’>Something bad happened…</h2>”);
}

While that example is pretty vanilla, you can imagine how far you can stretch this.

Read more here: http://docs.jquery.com/Attributes/html

8. val()

If you plan on doing any kind of form manipulation, this one’s a must! The val attribute gets/sets a form field’s value. When called with a value like here:

$(“#firstName”).val(“William”);

The value of the firstName textbox is overwritten with William. To read the value, you simply call without an argument:

var theFirstName = $(“#firstName”).val();

One fun way to use the val attribute is creating the classic “billing address is the same as the mailing address” checkbox button. Here is how the code would look:

$(“#BillingAddress1″).val($(“#MailingAddress1″).val());
$(“#BillingAddress2″).val($(“#MailingAddress2″).val());
$(“#BillingCity”).val($(“#MailingCity”).val());
$(“#BillingState”).val($(“#MailingState”).val());
$(“#BillingZip”).val($(“#MailingZip”).val());
$(“#BillingCountry”).val($(“#MailingCountry”).val());

Read more here:  http://docs.jquery.com/Attributes/val

7. TinyMCE

Back when I used to exclusively program in ASP.NET 2.0, Telerik’s RAD Editor (http://demos.telerik.com/aspnet-ajax/editor/examples/overview/defaultcs.aspx) was the coolest thing ever. It is still really cool with some really advanced features, but for projects with a tight budget, found an awesome free tool in TinyMCE.

While there are unlimited numbers of configurations, I’ll typically use it in one of two modes:

1. I’ll convert all textareas into rich text editors, usually for an admin master page

2. Initialize individual textareas as needed

Initializing the textbox is the same, the difference is where you call it. Here is how you initialize the editor:

tinyMCE.init({
mode : “textareas”,
theme : “advanced”,

theme_advanced_toolbar_location: “top”,
theme_advanced_toolbar_align: “left”,
theme_advanced_resizing: true,
readonly: false
});

Read more here:  http://tinymce.moxiecode.com

6. tablesorter 

This might be one of my favorite plugins of all! This jQuery plugin converts a generic html table into a sorting machine, with the smarts to distinguish between dates, integers, markup, etc. baked right in. Like TinyMCE, you can initialize every table to be sortable, or on an individual basis. There is also an optional paging add-on which works decently, although I tend to go with my own personal paging control. So what do you need to do?

1. Add the reference to the plugin, then the following javascript:

jQuery(document).ready(function() {
jQuery(“table”)
.tablesorter({ widthFixed: true, widgets: ['zebra'] })
});

2. Set the table’s class to tablesorter, and include <thead> and <tbody> tags.

The link above takes you to the detailed documentation and how far you can bend and flex this plugin. But if you need to support sorting, this is one powerful plugin.

Read more here:  http://tablesorter.com/docs/

Stay tuned for Part II!

, , , ,

How to use jQuery to copy form values

Filed in Html | jquery Leave a comment

This is a simple little exercise to show how to copy form values from one set of fields into another. The sample will be a “check box if billing information is the same as contact information.”

To set this up, first we create the form fields:

<fieldset>
<legend>Contact Information</legend>
<b>Name</b> (first, last)<br>
<input id="ContactFirstName" name="ContactFirstName" style="width: 100px;" value="" type="text">&amp;nbsp;
<input id="ContactLastName" name="ContactLastName" style="width: 120px;" value="" type="text">
<br><br>

<b>Address</b><br>
<input id="ContactAddress1" name="ContactAddress1" style="width: 150px;" value="" type="text"><br><br>
<input id="ContactAddress2" name="ContactAddress2" style="width: 150px;" value="" type="text">
<br><br>

<b>City, State</b><br>

<input id="ContactCity" name="ContactCity" style="width: 100px;" value="" type="text">,&amp;nbsp;
<select id="ContactState" name="ContactState"><option value="AK">Alaska</option>
</select>
<br><br>

<b>Zip Code</b><br>
<input id="ContactZip" name="ContactZip" style="width: 70px;" value="" type="text">
</fieldset><br/>

<fieldset>
<legend>Billing Information</legend>
<input onclick="CopyContactInfo()" type="checkbox"> Check box if same as Contact Information
<b>Name</b> (first, last)<br>
<input id="MailingFirstName" name="MailingFirstName" style="width: 100px;" value="" type="text">&amp;nbsp;
<input id="MailingLastName" name="MailingLastName" style="width: 120px;" value="" type="text">
<br><br>

<b>Address</b><br>
<input id="MailingAddress1" name="MailingAddress1" style="width: 150px;" value="" type="text"><br><br>
<input id="MailingAddress2" name="MailingAddress2" style="width: 150px;" value="" type="text">
<br><br>

<b>City, State</b><br>

<input id="MailingCity" name="MailingCity" style="width: 100px;" value="" type="text">,&amp;nbsp;
<select id="MailingState" name="MailingState"><option value="AK">Alaska</option>
</select>
<br><br>

<b>Zip Code</b><br>
<input id="MailingZip" name="MailingZip" style="width: 70px;" value="" type="text">
</fieldset>

Next we paste in the jquery code:

function CopyContactInfo() {
$("#BillingAddress1").val($("#ContactAddress1").val());
$("#BillingAddress2").val($("#ContactAddress2").val());
$("#BillingCity").val($("#ContactCity").val());
$("#BillingState").val($("#ContactState").val());
$("#BillingZip").val($("#ContactZip").val());
}

That’s it!

TOP