Tag Archives: forms

jQuery UI Autocomplete Widget with ASP.NET VB

You might also be interested in the Using jQuery Autocomplete to Populate Another Autocomplete post.

As a follow up to the jQuery UI Autocomplete Widget with ColdFusion and the jQuery UI Autocomplete Widget with PHP posts, I did one with ASP.NET (VB.NET) as the backend. I swear this is the last one I’m doing. I’m running out of languages that I work in.

The jQuery UI folks have released an autocomplete widget that is pretty slick. This example uses the JavaScriptSerializer() function in .NET 3.5. I heard a rumor .NET 4 might make this json encoding with data easier. We’ll see.
autocomplete
This example will use US states and territories to populate the autocomplete. It will also demonstrate how to fill other fields with data returned from the database. This data can be used to fill a visible text box or a hidden form field. It also demonstrates the basic autocomplete functionality which may be fine for some applications.

Of course, you will need the jQuery core file, the jQuery UI core file, and the jQuery UI style sheet of choice. The style sheet comes from the themes available in the jQuery UI website and can be downloaded with the core file or you can link to the latest versions of both the core files and the css:

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" /> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>

The HTML is straight forward and stripped down for the example:

<form action="Default.aspx"  method="post">
<fieldset>
<legend>jQuery UI Autocomplete Example - ASP.NET VB Backend</legend>
<p>Start typing the name of a state or territory of the United States</p>
<p class="ui-widget"><label for="state">State (abbreviation in separate field): </label>
	<input type="text" id="state"  name="state" /> <input readonly="readonly" type="text" id="abbrev" name="abbrev" maxlength="2" size="2"/></p>
    <input type="hidden" id="state_id" name="state_id" />
<p class="ui-widget"><label for="state_abbrev">State (replaced with abbreviation): </label>
<input type="text" id="state_abbrev" name="state_abbrev" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</fieldset>
</form>

As a bonus, we dump out the form values to see what we have right underneath the form itself:

Sub Page_Load(Source As Object, E As EventArgs)
 	Dim formfields As String = "<p>" 

     For Each sItem In Request.Form
	 	formfields = formfields + "<strong>" + sItem + "</strong> = " +  Request.Form(sItem) + "<br />"
  	Next
	formoutput.Text = formfields + "</p>"
 End Sub

And the jQuery on the page is equally brief:

$(function() {

            $('#abbrev').val("");

            $("#state").autocomplete({
                source: "states.aspx",
                minLength: 2,
                select: function(event, ui) {
                    $('#state_id').val(ui.item.id);
                    $('#abbrev').val(ui.item.abbrev);
                }
            });

            $("#state_abbrev").autocomplete({
                source: "states_abbrev.aspx",
                minLength: 2
            });
        });

Notice that there are two autocomplete functions on the page, one for each example in the demo. Each function calls a different aspx file which return slightly different result sets.

Also, the minLength for autocomplete to return results is set to 2 to prevent too many rows from being returned.

The jquery autocomplete will append the text typed into the autocomplete field as the URL parameter ‘term.’ This URL parameter is used to query the database.

From the jquery documentation:

The request parameter “term” gets added to that URL.

Both .NET pages return the data after a few steps:

  1. It creates a new javascript serializer
  2. It creates an object to hold the data from each returned row in the query
  3. It queries the database and fills a dataset (keep reading if you like readers better)
  4. Loops an array of the query results adding each row to an object
  5. Adds the object to an ArrayList
  6. Outputs the ArrayList as JSON data

The states.aspx file returns the id field, the state field as ‘value’, and the abbrev field. These values are placed in the appropriate text boxes by the autocomplete jQuery function.

<%@ Page Language="VB" Debug="false" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Dim serializer As JavaScriptSerializer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        serializer = New JavaScriptSerializer()
        Response.Write(JSONData(Request.QueryString("Term")))
    End Sub

    Public Class State
        Public id As Integer
        Public value As String
        Public abbrev As String
    End Class

    Private Function JSONData(ByVal term As String) As String

        Dim stateArray As New ArrayList
        Dim index As Integer = 0

        Dim objConn As New SqlConnection("YOUR-CONNECTION-STRING-HERE")
        Dim myds As New DataSet("States")

        objConn.Open()

        Dim adapter As New SqlDataAdapter("SELECT id, state, abbrev FROM states WHERE state like '%' + @ac_term + '%'", objConn)
        adapter.SelectCommand.Parameters.Add("@ac_term", SqlDbType.VarChar)
        adapter.SelectCommand.Parameters("@ac_term").Value = term
        adapter.Fill(myds, "States")

        For Each dr As DataRow In myds.Tables(0).Rows
            Dim st As New State()
            st.id = dr("id").ToString()
            st.value = dr("state").ToString()
            st.abbrev = dr("abbrev").ToString()
            stateArray.Add(st)
        Next

        objConn.Close()

        Return serializer.Serialize(stateArray)
    End Function

    </script>

The states_abbrev.aspx shows the basic functionality of the autocomplete function by just assigning results of the query to the ‘label’ and ‘value’ fields. Explanation on the ‘label’ and ‘value’ fields from the jQuery UI site:

Very important information below. Please read and understand before expecting the autocomplete to work properly.

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.”

<%@ Page Language="VB" Debug="false" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Dim serializer As JavaScriptSerializer

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        serializer = New JavaScriptSerializer()
        Response.Write(JSONData(Request.QueryString("Term")))
    End Sub

    Public Class State
        Public label As String
        Public value As String
    End Class

    Private Function JSONData(ByVal term As String) As String

        Dim stateArray As New ArrayList
        Dim index As Integer = 0

        Dim objConn As New SqlConnection("YOUR-CONNECTION-STRING-HERE")
        Dim myds As New DataSet("States")

        objConn.Open()

        Dim adapter As New SqlDataAdapter("SELECT id, state, abbrev FROM states WHERE state like '%' + @ac_term + '%'", objConn)
        adapter.SelectCommand.Parameters.Add("@ac_term", SqlDbType.VarChar)
        adapter.SelectCommand.Parameters("@ac_term").Value = term
        adapter.Fill(myds, "States")

        For Each dr As DataRow In myds.Tables(0).Rows
            Dim st As New State()
            st.label = dr("state").ToString()
            st.value = dr("abbrev").ToString()
            stateArray.Add(st)
        Next

		objConn.Close()

        Return serializer.Serialize(stateArray)
    End Function

    </script>

Usual recommended jQuery and .NET reading:



jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion

This is the same as the previous jquery form submit post that used PHP just flavored with CF this time.

Two jQuery functions that allow for the submission of form are the jQuery.ajax function and the jQuery.post function (there is also jQuery.get but that is not addressed here).

More functionality, along with more complexity, is offered with the .ajax function while the .post function, with its more simple functionality and implementation, will be all that is needed for simple form posts.

It is highly recommended that you get a tool like Firebug to see the post response coming back from the page. It helps immensely.

Here is an example of both in action doing the same thing: form submit with email validation.

jQuery.ajax

The form:

<form id="JqAjaxForm">
<fieldset>
<legend>jQuery.ajax Form Submit</legend>
<p><label for="name_ajax">Name:</label><br />
<input id="name_ajax" type="text" name="name_ajax" /></p>
<p><label for="email_ajax">E-mail:</label><br />
<input id="email_ajax" type="text" name="email_ajax"  /></p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
<div id="message_ajax"></div>

Pretty simple, nothing fancy. There is a form for each jQuery function, .ajax and .post. The only difference in the forms are the element names.

jQuery controls the submit for the forms. For the .ajax submission the jQuery is this:

$(function(){
    $("#JqAjaxForm").submit(function(){
        dataString = $("#JqAjaxForm").serialize();

        $.ajax({
        type: "POST",
        url: "process_form.cfm",
        data: dataString,
        dataType: "json",
        success: function(data) {

            if(data.email_check == "invalid"){
                $("#message_ajax").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
            } else {
                $("#message_ajax").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
            }

        }

        });

        return false;            

    });
});

The .serialize function is used to put the form data in a format that can be processed by a page on the server. The .ajax function options include:

  • type: “get” or “post”
  • url: the page to receive the form data
  • data: the form data itself
  • dataType: the data type the function should expect back from the server
  • success function: runs on a succesful post to the page

More information on the options and further explanations of the options used here can be found on the jQuery.ajax documentation page.

jQuery.post

As in the .ajax example, the form is simple, only the names have been changed:

<form id="JqPostForm">
<fieldset>
<legend>jQuery.post Form Submit</legend>
<p><label for="name_post">Name:</label><br />
<input id="name_post" type="text" name="name_post" /></p>
<p><label for="email_post">E-mail:</label><br />
<input id="email_post" type="text" name="email_post" /></p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
<div id="message_post"></div>

And again, jQuery controls the submit for the forms. For the .post submission the jQuery is this:

$(function(){
    $("#JqPostForm").submit(function(){
        $.post("process_form.cfm", $("#JqPostForm").serialize(),
        function(data){
            if(data.email_check == 'invalid'){

                    $("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
            } else {
                $("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
                }
        }, "json");

        return false;

    });
});

jQuery.post is a shorter, easier way to post the form data. The function arguments are:

  • url of the form processing page
  • the form data
  • the callback function
  • the data type of the return data

More information can be found on the jQuery.post documentation page.

Processing the Form

Both methods are processed by the same page. It processes the form data, process_form.cfm in this example, by checking to see if the e-mail submitted is valid. Much more than that could be done on the page if needed.

<cfset email_check = "" />
<cfset return_json_string = "" />
<cfset return_struct = StructNew() />

<cfif (isDefined("form.email_ajax") AND isValid("email",form.email_ajax)) OR (isDefined("form.email_post") AND isValid("email",form.email_post))>
   <cfset email_check = "valid"/>
<cfelse>
    <cfset email_check = "invalid"/>
</cfif>

<cfset StructInsert(return_struct, "email_check", email_check) />

<cfif isDefined("form.email_ajax")>
	<cfset StructInsert(return_struct, "name", form.name_ajax) />
	<cfset StructInsert(return_struct, "email", form.email_ajax) />

	<!---return_json_string is for pre-CF 8 only, delete if you have cf 8 or later--->
	<cfset return_json_string = '{"email_check":"#email_check#","name":"' & form.name_ajax & '","email":"' & form.email_ajax & '"}' />

<cfelse>
	<cfset StructInsert(return_struct, "name", form.name_post) />
	<cfset StructInsert(return_struct, "email", form.email_post) />

	<!---return_json_string is for pre-CF 8 only, delete if you have cf 8 or later--->
	<cfset return_json_string = '{"email_check":"#email_check#","name":"' & form.name_post & '","email":"' & form.email_post & '"}' />

</cfif>

<!--- serializeJSON is CF 8 and above only, see below for pre-CF 8 --->
<cfoutput>#serializeJSON(return_struct)#</cfoutput>

<!--- Uncomment the cfoutput statement below and remove the cfoutput statement above if you don't have CF 8--->
<!--- <cfoutput>#return_json_string#</cfoutput> --->

This code puts the results of the e-mail validation and the form data in a JSON-formatted string. It then will output the return data string which is picked up by the success function in the .ajax function or the function(data) function in the .post function on the original page.

I prefer working with JSON, but there are other options for the return data. Check the jQuery documentation for the types available to you.

The JSON response will look like this:

{"email_check":"valid","name":"Julia","email":"julia@example.com"}

NOTE: If you have ColdFusion 8 or better use the serializeJSON function. This function can return query results, arrays, dates, strings, and the like to JSON which is easily consumed and digested by javascript. Pre-CF 8 will require building the JSON string manually but with some loops and other creativity, it can be done.

The appropriate message based on the e-mail validation check is then displayed.

Pretty simple, pretty handy couple of jQuery functions. Once you see it in action, you get the idea.

Usual recommended jQuery and CF reading:

Download zip of all files

jQuery.ajax and jQuery.post Form Submit Examples with PHP

For a version of this using ColdFusion, see the CF jquery form submit post.

Two jQuery functions that allow for the submission of form are the jQuery.ajax function and the jQuery.post function (there is also jQuery.get but that is not addressed here).

More functionality, along with more complexity, is offered with the .ajax function while the .post function, with its more simple functionality and implementation, will be all that is needed for simple form posts.

It is highly recommended that you get a tool like Firebug to see the post response coming back from the page. It helps immensely.

Here is an example of both in action doing the same thing: form submit with email validation.

jQuery.ajax

The form:

<form id="JqAjaxForm">
<fieldset>
<legend>jQuery.ajax Form Submit</legend>

<p><label for="name_ajax">Name:</label><br />

<input id="name_ajax" type="text" name="name_ajax" /></p>

<p><label for="email_ajax">E-mail:</label><br />

<input id="email_ajax" type="text" name="email_ajax"  /></p>

<p><input type="submit" value="Submit" /></p>

</fieldset>
</form>
<div id="message_ajax"></div>

Pretty simple, nothing fancy. There is a form for each jQuery function, .ajax and .post. The only difference in the forms are the element names.

jQuery controls the submit for the forms. For the .ajax submission the jQuery is this:

$(function(){
    $("#JqAjaxForm").submit(function(e){
       e.preventDefault();

        dataString = $("#JqAjaxForm").serialize();

        $.ajax({
        type: "POST",
        url: "process_form.php",
        data: dataString,
        dataType: "json",
        success: function(data) {

            if(data.email_check == "invalid"){
                $("#message_ajax").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
            } else {
                $("#message_ajax").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
            }

        }

        });          

    });
});

The .serialize function is used to put the form data in a format that can be processed by a page on the server. The .ajax function options include:

  • type: “get” or “post”
  • url: the page to receive the form data
  • data: the form data itself
  • dataType: the data type the function should expect back from the server
  • success function: runs on a succesful post to the page

More information on the options and further explanations of the options used here can be found on the jQuery.ajax documentation page.

jQuery.post

As in the .ajax example, the form is simple, only the names have been changed:

<form id="JqPostForm">
<fieldset>
<legend>jQuery.post Form Submit</legend>

<p><label for="name_post">Name:</label><br />

<input id="name_post" type="text" name="name_post" /></p>

<p><label for="email_post">E-mail:</label><br />

<input id="email_post" type="text" name="email_post" /></p>

<p><input type="submit" value="Submit" /></p>

</fieldset>
</form>
<div id="message_post"></div>

And again, jQuery controls the submit for the forms. For the .post submission the jQuery is this:

$(function(){
    $("#JqPostForm").submit(function(e){
       e.preventDefault();   

        $.post("process_form.php", $("#JqPostForm").serialize(),
        function(data){
            if(data.email_check == 'invalid'){

                    $("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
            } else {
                $("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
                }
        }, "json");
    });

});

jQuery.post is a shorter, easier way to post the form data. The function arguments are:

  • url of the form processing page
  • the form data
  • the callback function
  • the data type of the return data

More information can be found on the jQuery.post documentation page.

Processing the Form

Both methods are processed by the same page. It processes the form data, process_form.php in this example, by checking to see if the e-mail submitted is valid. Much more than that could be done on the page if needed.

$email_check = '';
$return_json = '';

function isValidEmail($email){
    return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}

if(isValidEmail($_POST['email_ajax']) || isValidEmail($_POST['email_post'])) {
   $email_check = 'valid';
}
else {
    $email_check = 'invalid';
}

$return_json = '{"email_check":"' . $email_check . '",';

if (isset($_POST['email_ajax'])){
    $return_json = $return_json . '"name":"' . $_POST['name_ajax'] . '",';
    $return_json = $return_json . '"email":"' . $_POST['email_ajax'] . '"}';
} else {
    $return_json = $return_json . '"name":"' . $_POST['name_post'] . '",';
    $return_json = $return_json . '"email":"' . $_POST['email_post'] . '"}';
}

echo $return_json;

This code puts the results of the e-mail validation and the form data in a JSON-formatted string. It then will echo the return data string which is picked up by the success function in the .ajax function or the function(data) function in the .post function on the original page.

I prefer working with JSON, but there are other options for the return data. Check the jQuery documentation for the types available to you.

The JSON response will look like this:

{"email_check":"valid","name":"Julia","email":"julia@example.com"}

NOTE: If you have PHP 5.2 or better and the filter_var and json_encode functions available, use the following code instead:

$email_check = '';
$return_arr = array();

if(filter_var($_POST['email_ajax'], FILTER_VALIDATE_EMAIL) || filter_var($_POST['email_post'], FILTER_VALIDATE_EMAIL)) {
   $email_check = 'valid';
}
else {
    $email_check = 'invalid';
}

$return_arr["email_check"] = $email_check;

if (isset($_POST['email_ajax'])){
    $return_arr["name"] = $_POST['name_ajax'];
    $return_arr["email"] = $_POST['email_ajax'];
} else {
    $return_arr["name"] = $_POST['name_post'];
    $return_arr["email"] = $_POST['email_post'];

}

echo json_encode($return_arr);

The appropriate message based on the e-mail validation check is then displayed.

Pretty simple, pretty handy couple of jQuery functions. Once you see it in action, you get the idea.

Usual recommended jQuery and PHP reading:

Demo

Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties

jQuery files updated June 23, 2010. Because Thickbox is no longer supported, I may have to drop its example to update the jQuery files in the future.

If you liked this post, you might also like the jQuery.ajax and jQuery.post Form Submit Examples with PHP post.

I wanted to make a nice modal dialog box that would confirm submission of a form. And, specifically, it had to ask if their e-mail address was correct that they listed on the form. Typos, particularly transposed letters, cause a number of undeliverable e-mails. Making matters worse, sometimes by the time they get to the ‘Submit’ button, the all important e-mail field is no longer in view. Yes, despite the web developer’s best efforts, people still manage to type in their own e-mail incorrectly. I’ve done it. We’re all human.

I already knew about the javascript 1.0 method of ‘return confirm’ but I wanted more control over the look and feel. As an added requirement, I wanted to use Thickbox since I already had that loaded into the app. I don’t like throwing in a bunch of js files for every little nuance. If I can use what I already have, it makes the app much leaner.

So, I Googled it. I only found partial solutions. I wanted to go all the way and have the modal box pop up whether the user hit ‘Submit’ or whether they hit enter on the keyboard in as many browsers as possible (hint: IE). Maybe I didn’t look hard enough, but I ended up creating the solution on my own.

Here are three examples (including a complete demo) of a form submission confirmation dialog. One each for just javascript, the jQuery UI dialog box, and Thickbox.

Javascript 1.0

Echo back a message for fun:

<?php if (isset($_POST['emailJS'])){
 echo "<p class='message'>Javascript 1.0 worked!!! Your e-mail address is " .$_POST['emailJS'];
 echo "</p>";
 }?>

For pure javascript it’s painfully straightforward:

<form id="testconfirmJS" name="testconfirmJS" method="post" onsubmit="return confirm('You entered your e-mail address as:\n\n' + document.getElementById('emailJS').value + '\n\nSelect OK if correct or Cancel to edit.')">>
<fieldset>
<legend>Javacript Return Confirm</legend>

<p><label for="email">E-mail:</label><br />

<input id="emailJS" type="text" name="emailJS" value="" /></p>

<p><input type="submit" value="Submit" /></p>

</fieldset>
</form>

And you get something that looks like this:
javascript confirm box

Low overhead, not too much strain on the brain but pretty plain vanilla. And boring. Let’s do something a little fancier.

jQuery UI

The jQuery UI library is awesome. Loads of flexibility and customization available and they hand you everything you need. For this solution we have to load in an additional stylesheet (you can download a custom ready-made css), the jQuery base js, and the jQuery UI js. The jQuery UI site allows you to customize its js file to include only the parts you will use.

And, because this example uses Thickbox which is no longer supported, the jQuery core and jQuery core have not been updated to the latest versions. If you are not using Thickbox, use the latest version of jQuery.

<link rel="stylesheet" type="text/css" href="css/blitzer/jquery-ui-1.8.2.custom.css">

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.2.custom.min.js"></script>

The form is untouched for this approach, but we do have to add some js to the document itself and an additional div element that will hold the contents of our modal box.

Here the we set some parameters for the dialog box including what the buttons should say and do. Then a little jQuery is added so that the e-mail is displayed in the box and the box opens on submit allowing the user to hit the ‘Submit’ button or the enter key.

        $(function(){
                // jQuery UI Dialog    

                $('#dialog').dialog({
                    autoOpen: false,
                    width: 400,
                    modal: true,
                    resizable: false,
                    buttons: {
                        "Submit Form": function() {
                            document.testconfirmJQ.submit();
                        },
                        "Cancel": function() {
                            $(this).dialog("close");
                        }
                    }
                });

                $('form#testconfirmJQ').submit(function(e){
                    e.preventDefault();

                    $("p#dialog-email").html($("input#emailJQ").val());
                    $('#dialog').dialog('open');
                });
        });

Echo back a message for fun:

<?php if (isset($_POST['emailJQ'])){
 echo "<p class='message'>jQuery UI worked!!! Your e-mail address is " .$_POST['emailJQ'];
 echo "</p>";
 }?>

The form is pretty clean and the div containing the text for the dialog box can be placed anywhere on the page.


<form id="testconfirmJQ" name="testconfirmJQ" method="post">
<fieldset>
<legend>jQuery UI Modal Submit</legend>

<p><label for="email">E-mail:</label><br />

<input id="emailJQ" type="text" name="emailJQ" value="" /></p>

<p><input type="submit" value="Submit" /></p>

</fieldset>
</form>

<div id="dialog" title="Verify Form jQuery UI Style">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0 0;"></span> You entered your e-mail address as:</p>
<p id="dialog-email"></p>
<p>If this is correct, click Submit Form.</p>
<p>To edit, click Cancel.<p>
</div>

Using this method you get a much prettier result:
jQuery dialog box

Thickbox method

The ever helpful and massively adaptable Thickbox was easily coded to do this as well. Thickbox also requires its own stylesheet and js along with the base jQuery file. Many apps have this already loaded since Thickbox is so wildly popular.

<link rel="stylesheet" type="text/css" href="css/thickbox.css">

<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/thickbox-compressed.js"></script>

As with the jQuery UI method, we add some js to the document to put in the e-mail from the form, open the Thickbox, and instruct the buttons on what actions to take when clicked.

        $(function(){
                //Thickbox

                $('form#testconfirmTB').submit(function(e){
                    e.preventDefault();

                    $("p#TB-email").html($("input#emailTB").val());
                    tb_show('Verify Form Thickbox Style','TB_inline?height=155&amp;width=300&amp;inlineId=TBcontent');

                });

                $('input#TBcancel').click(function(){
                    tb_remove();
                });

                $('input#TBsubmit').click(function(){
                    document.testconfirmTB.submit();
                });
        });

Echo back a message for fun:

<?php if (isset($_POST['emailTB'])){
 echo "<p class='message'>Thickbox worked!!! Your e-mail address is " .$_POST['emailTB'];
 echo "</p>";
 }?>

The form is also clean for this method and a div is added for the Thickbox content.

<form id="testconfirmTB" name="testconfirmTB" method="post">
<fieldset>
<legend>Thickbox Modal Submit</legend>

<p><label for="email">E-mail:</label><br />

<input id="emailTB" type="text" name="emailTB" value="" /></p>

<p><input type="submit" value="Submit" /></p>

</fieldset>
</form>

<div id="TBcontent" style="display: none;">
<p>You entered your e-mail address as:</p><p id="TB-email"></p>
<p>If this is correct, click Submit Form.</p><p>To edit, click Cancel.<p>
<input type="submit" id="TBcancel" value="Cancel" />
<input type="submit" id="TBsubmit" value="Submit Form" />
</div>

The Thickbox, generically styled (the default styling actually), looks like this:
Thickbox modal confirm box

Three flavors for confirming on form submission. Enjoy.

Recommended:

Demo

Internet Explorer (IE) Not Submitting Form on Enter

While working on a ColdFusion application, I noticed that the login form was not submitted when enter was pressed in Internet Explorer. Other browsers, Firefox and Chrome specifically, did not have this issue. There are many methods used to fix this error if you Google it, but I found that the simplest solutions are usually the best. No javascript, no funky CSS to hide fields, yada, yada, yada.

The Situation

This app had a form with a single text field and a submit button. The form submitted back to its own page were the logic executed if form.submit (the submit button itself) came back with the form variables collection.

When you pressed the enter button, IE did not send the input type=submit field back with the form vars and the form logic did not execute. The page appeared to refresh and you started over again.

The Solution

All that was necessary was to add a hidden input field that the form logic used instead.

<input type="hidden" name="login" value="loginSubmit" />

If form.login and form.login = ‘loginSubmit’, the form logic executes and the user is logged in.

So, from now on, I am not going to rely on the input submit button to check for form submission. Call me crazy, but I think IE has the right idea here; the input submit should not be part of the form variables collection.