Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

jQuery

16K

Solutions

5K

Contributors

jQuery (Core) is a cross-browser JavaScript library that provides abstractions for common client-side tasks such as Document Object Model (DOM) traversal, DOM manipulation, event handling, animation and Ajax. jQuery also provides a platform to create plugins that extend jQuery's capabilities beyond those already provided by the library.

Share tech news, updates, or what's on your mind.

Sign up to Post

Article Header
This article discusses how to implement server side field validation and display customized error messages to the client.
5
On Demand Webinar: Networking for the Cloud Era
LVL 10
On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
2
This article discusses how to create an extensible mechanism for linked drop downs.
0
Introduction
JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more efficient and more widely supported, JSON has become the dominant technology for use in AJAX applications, APIs, and other data interchange applications where data structure and data elements must be communicated between applications and web services.

JSON is frequently found in combination with RESTful APIs, where XML has rightly fallen into disuse.  This article will examine some of the ways XML and JSON are similar and different, and will show ways of using JSON to our advantage.

Some code examples will show how to create and interpret JSON strings, and detect JSON errors.

A Bit of Test Data
Since the most important thing a programmer can have is a good test case, let's start with some good test data.  Here is the information we will use for all of our code examples.  This information will represent people, giving their names and ZIP codes.  While the example is truly minimalist, it's sufficient to illustrate the principles.
firstName lastName zipCode
John      Doe      20007
Mary      Doe      20016

Open in new window


A Bit of Test Data Organization
Both XML and JSON can represent the data structure.  Here is how our data will be organized.
People (with a date attribute)
|_ Person
   |_firstName
   |_lastName
   |_zipCode

Open in new window


The Old School Way: XML
XML, or Extensible Markup Language, is a text-string data transport mechanism.  It was popularized in the 1990s when SOAP
11
 
LVL 43

Expert Comment

by:Rob
Comment Utility
Ray,

Great article (as always) :).  I just wanted to address the "Using JSON Strings in JavaScript" section of your article.

I'd like to see the distinction between JavaScript and jQuery/AngularJS to show that jQuery & AngularJS are frameworks of the JavaScript language. In otherwords, they are just JavaScript. They do not implement their own version of the ECMA-262 standards.  Node.js on the other hand DOES have its own version but being only a server side language, that's a different story.

On another note, JSON in the browser still needs to be decoded from a string to be a useful JavaScript native object. Any data that PHP returns in JSON format will need to be decoded using the JSON.parse() native JavaScript function.  jQuery will do this automatically when the getJSON() or ajax() with the dataType set to "json" but vanilla JavaScript will not.  For your reference: http://www.w3schools.com/js/js_json.asp

Following on from this, the example you go on to give isn't a string, but a JS object.  I'd like to see an example of using the native functions for converting JSON strings to objects as indicated here: http://www.w3schools.com/js/js_json.asp
0
 
LVL 111

Author Comment

by:Ray Paseur
Comment Utility
Hey, Rob.  Thanks for your comments.  Why not add your clarification examples to the comment thread here, or post a new article about this?  Especially if any of my old code and data examples are overtaken by current events... technology is always advancing!
0
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
11
 
LVL 11

Expert Comment

by:Ackles
Comment Utility
Awesome!!!
Simple Beautiful
0
 

Expert Comment

by:Eduardo Fuerte
Comment Utility
Mario

Very good example and good foods!!!

Thanks
0
Introduction
If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entries by using the typographical error.  This is somewhat annoying, and if you're paying attention, you can visually identify the error.  You can usually get past this issue by telling the browser to forget your recent history.  But have you ever begun typing your password or passphrase into an online form and thought, "Did I get that right?"  You can't visually check your work because the browser is showing you a form input field with something like this: ········· The browser is "helpfully" hiding the password from prying eyes by masking the input control field.

This article teaches three ways to allow your clients to show or hide the password fields as they type them into your forms.  In my experience, the default behavior that hides the password input is only marginally useful.  Most of the time nobody is looking over your shoulder and the real risk of lost passwords does not rest with the human client or the client browser, but with the servers where passwords are stored.  We can't change the server's security, but we can choose to make life easier for our (human) clients!

How HTML <input type="password"> Works
HTML defines several different input types for different kinds of input controls
5
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX.

The logical flow for the problem should be:
  1. Write an event handler for the first drop down box to get the user's selections.
  2. Send the user input to the server
  3. At the server, retrieve the data from the client side and process it; then send the result to client side.
  4. At the client, use Javascript to parse the server response and update the other drop down box.


Write an event handler for the first drop down box to get the user's selections:

It sounds difficult. What is an "event handler"?  In fact, every user action performed on the web page triggers an event. To handle those events, we need to write a Javascript function, and we call these javascript functions "event handlers". To handle the user's selection of an item in drop-down box, we need to capture the onchange event. Here is a sample code:
 
 <select id=type name="type" onchange="updateData(this)">

Open in new window


The above code means that a function named "updateData" would be triggered when user selects an item from this drop down box. Here the variable "this" means the dropdown box itself. Let's see what happens in the "updateData" function:
function updateData(dropDownBox)
{
  var value=dropDownBox.options[dropDownBox.selectedIndex].value;
  if (value!="") //Ensure no empty value is submitted to server side
  {
    jQuery.post("getResult.php","type="+value,updateNumber);
  }
}

Open in new window


Send the user input to the server

The statement:

var value=dropDownBox.options[dropDownBox.selectedIndex].value;

Open in new window

retrieves user input from the first drop down box. The following statement mean user input is sent to server side php script "getResult.php".
 
jQuery.post("getResult.php","type="+value,updateNumber);

Open in new window

1

Introduction


Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).  

The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least complicated way as possible.

There are also other frameworks that essentially do the same thing in their own way. Find what works for you. React is what Facebook is built on and is very popular. AngularJS has also gained a lot of momentum and worth checking out.

Knockout takes a basic HTML structure and applies logic (written by you) to control the insertion and removal of HTML elements. This keeps the markup simple and straightforward, especially when it comes to repetitive content.

It's incredibly easy with Knockout to create dynamic interactive web pages with simplified markup. I've seen markup get out of control when creating content both from the server side (e.g. using PHP) or via the client side (e.g. using jQuery), making it virtually impossible to troubleshoot issues with layout and styling. 

I come across many questions in the web dev topic areas that are related to issues with the asker's website. Invariably this starts with them being told to fix their markup and validate it through the The World Wide Web Consortium's (W3C) Validation service.  When a site doesn't validate, it is not guaranteed to work on all …
1
 
LVL 3

Expert Comment

by:mmoore
Comment Utility
Really interesting stuff! So many technologies so little time.
A couple of typos you may wish to correct. "It incredibly easy" "know no only".
0
 
LVL 43

Author Comment

by:Rob
Comment Utility
Thanks @mmoore :)
0
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
1
 
LVL 31

Author Comment

by:Marco Gasi
Comment Utility
Well, I'm happy. But I've just realized that today is still May: will this article partecipate to the contest for the Blade-Runner HD?
0

Introduction

Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this tutorial, I have to assume that you understand basic statistics and how to interpret the data shown in the charts outlined by this tutorial. Chart.js offers the following types of Charts: Line, Bar, Radar, Polar Area, Pie and Doughnut. It is possible to create your own types of charts but one step at a time. These are the types we'll be working with in this tutorial.
 

So what do you need to do to get started?

Bookmark the documentation! http://www.chartjs.org/docs/

Either use a Content Delivery Network (CDN) OR Download the ZIP package and include it with the other files of your website.

I personally recommend to use a CDN via this script tag (version 1.0.2)

<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>

Open in new window

If you want to have the Chart.js files on your server, download the ZIP from https://github.com/nnnick/Chart.js("Download Zip" found on the right of the page or click this link https://github.com/nnnick/Chart.js/archive/master.zip (may be subject to change) Download.JPGExtract all the files from the ZIP, however the ONLY file needed is the Chart.min.js, and include it in the relative section of your site: 

<script src="/relative/path/to/Chart.min.js"></script>

Open in new window


Add jQuery

While we're at it, let's add jQuery to your page:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

Open in new window

So now your page should look like this


Open in new window

4
Linux Academy Android App Now Supports Chromecast
Linux Academy Android App Now Supports Chromecast

We have some fantastic news for our Android fans. We’re so excited to announce that the Linux Academy Android app is now available with Chromecast support. That’s right – simply download the latest update of the Linux Academy App and start casting your favorite course videos!

PROBLEM:

The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working fine until I tried to add an ajax request to the page to bring in some data below my form field.  Essentailly my page looked like this.
 
<div class="wrapper">
   <form>
     <input>
     <input>
   </form>
   <div id="ajaxId"></div>
   <div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front description" style="display: none;" tabindex="-1" role="dialog" aria-describedby="privateQuestionPopup" aria-labelledby="ui-id-1">
</div>

Open in new window

 For those of you who are used to using the jquery dialog function you will recognize the ui-dialog section div.   This is the html the jquery dialog function adds in for you automatically.  By default the jquery dialog automatically adds the html to the end of the html document.  It then leverages the jquery ui positioning function to relatviely position the element.  In my example I was positioning relaitve to my inputs.  See here for more information about positioning.  http://api.jqueryui.com/position/.  The jquery positioning worked perfectly.  The dialog was position:relative with a top:-999px to move it up to where it needed to be.  The problem then came when I added in content through an asynchronous(ajax) request …
3
There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation.

Delegation allows a single script that is added at page creation to match elements that will be added later. This will decrease the number of script elements on your page and eliminate the need for unique classes or IDs on each dynamic element. With the JQuery delegate() method being deprecated, the way to do this is using the JQuery on() method.
 
JQuery on() usage is as follows: 
$(selector).on(event, childSelector, function)

Open in new window


To use delegation, you must be able to create a selector for a parent element to your dynamically added elements. If you have no better choice, selecting the body tag will work. You will also need to create your dynamic elements in such a way that they can all match a common selector. Your DOM structure will look something like this:
 
<div id="parent">
   <div class="child"> child 1</div>
</div>

Open in new window


Your parent selector will use the ID "parent"
"#parent"

Open in new window

As stated above, you can alternatively select the body tag for your parent.

"body"

Open in new window

Your child selector for the dynamic elements will use the class "child".

".child"

Open in new window


To create your JQuery call, pass the parent selector as the “selector” argument and the child selector as the “childSelector” argument.
 
$("#parent").on("click", ".child", function (e) { //do something });

Open in new window

0

Introduction

A frequently asked question goes something like this:  "I am running a long process in the background and I want to alert my client when the process finishes.  How can I send a message to the browser?"  Unfortunately, the short answer is "You can't." This is a restriction of the HTTP client / server protocol. The only time the server can send information to the client is in response to a request.  So it follows that we need a way for the client to request a progress report and a way for the server to send the progress report.  This article sets up the two parts of the application and builds them step-by-step so you can see exactly how this can be done.  We use jQuery and AJAX in a way that allows the client script to call the server-side script and to get back an indicator of progress.


The Visual Effect in the Browser

When we first load the client web page, we will have an area reserved for the progress bar.  As progress occurs (as indicated by the signal from the server) our progress bar will become visible and move across from left to right until the process is completed.  At the end, it will say "All Done" then it will fade from view and collapse out of the web page.  Here are screen-capture examples of the visual effects.  We used very bright colors for this example; your choice of size and color would be made with your design goals in mind.  These are settable via CSS.


Before the process starts:

jquery-progress-bar-1.pngAfter the progress bar appears:

jquery-progress-bar-2.pngAs the progress bar continues to show greater and greater progress:

jquery-progress-bar-3.pngWhen the progress indicator exceeds 99%:

jquery-progress-bar-4.pngAfter "All Done!" the progress bar fades out and disappears from the page:

jquery-progress-bar-5.png

The Server-Side Script

First we will build a simulation of the server side of the two-part application.  The server will sense the progress of our long-running job and will return a single value to the client - an integer, representing the percentage of completion.  In order to simulate the progress, we will use a simple counter which we will keep in the PHP session.  By storing the counter in the session, we can add to it on each request to the server-side script, creating the same effect we might see if the server-side script were taking an actual measurement of our progress toward a goal.  Have a look at line 15.  It's only there to simulate some kind of variation in the reported progress.  In real life, this "counting" scenario would be replaced by some programmatic method of determining the percentage of progress toward our goal.  The determination, however it is made, would be set into a positive integer of range 1-99 which is echo'ed to the browser output stream (and therefore returned to the client-side jQuery script that called our progress monitor).

<?php // demo/jquery_progress_bar_server.php
                                        error_reporting(E_ALL);
                                        
                                        // SESSION ALLOWS US TO HAVE STATIC VARIABLES
                                        session_start();
                                        
                                        // IF THIS IS THE FIRST STEP, SET THE PROGRESS BAR TO ZERO
                                        if (empty($_SESSION['progress']))
                                        {
                                            $_SESSION['progress'] = 0;
                                        }
                                        
                                        // INCREMENT THE PROGRESS COUNTER
                                        $advance = 10;
                                        $advance = rand(5,10);
                                        $_SESSION['progress'] += $advance;
                                        
                                        
                                        // IF THIS IS THE LAST STEP, ELIMINATE THE SESSION VARIABLE
                                        if ($_SESSION['progress'] > 99)
                                        {
                                            unset($_SESSION['progress']);
                                            session_write_close();
                                            die('100');
                                        }
                                        
                                        // RETURN THE PROGRESS
                                        echo $_SESSION['progress'];

The Client-Side Script

Once we have the server side of the application running, it's time to build the client side (the part that runs in the client's browser).  For this we use a conventional HTML5 web page.  These notes apply to the snippet below.


Line 8: This loads the latest "minified" jQuery framework.


Line 11-13: This starts the progress bar when the document.ready event fires.  In a real-world example, this might be started by a browser event, such as a mouse click.  But for our tests, it is nice to be able to refresh the browser and see the progress bar started immediately.  The script here tells the browser to run the loadProgressBar() function, and to address it to the div named #progressBar.  In theory it would be possible to have multiple progress bars on the page, but for this demonstration, one will do.  Note that for this example to work, the document.ready event handler is not required.  I only put it into the script as a placeholder since some other event might be the initial trigger for the progress bar.


Line 16: Sets the interval value to 1,000 milliseconds (one second).  Each time the interval timer expires, the script will call the server-side script for an update on the progress.  There is no hard-and-fast rule about a one-second interval; you can choose any values that makes sense for your needs.  You might want to experiment with faster or slower values.


Line 17: Sets the interval timer to call the function loadProgressBar() every time the intval expires.


Line 22: Defines the loadProgressBar() function.  The function takes one argument called "element."  This is the name of the outer wrapper div that encapsulates the progress bar.


Line 23: Every time loadProgressBar() is run, it calls the server-side script and retrieves an integer representing the percentage of completion of the background task.  This value is assigned to the JavaScript variable percent.


Line 24-28: If the percentage indicates that the progress is not yet complete, we recompute the width of the progress bar and animate the movement of the dark green background across the bar from left to right.


Line 29-36: When the percentage indicates that progress is complete, we are finished with the progress bar.  We take the following steps.

1. We remove the interval timer -- there is no need to call this function again.

2. We remove the background color from the progress bar.

3. We set the alignment to "center" and write "All Done!" in the middle of the progress bar

4. We use jQuery fade() and hide() functionality to cause the progress bar to act like the Cheshire Cat, disappearing from view.


Line 43-47: Our CSS defines the size and color of #progressBar div.


Line 49-57: Our CSS defines the div inside the #progressBar div.  It starts with a width of zero (which grows with each call to the loadProgressBar() function) and a background-color of dark green.  With this styling and the jQuery .animate() function, we can produce the visual effect of a progress bar that slides more-or-less smoothly across the screen.

 

3

Requirements

JQuery 1.6+
HTML
CSS

Introduction

This article was inspired by an EE question on how to make a page show some balloons animate up a page. It seemed like a fun exercise so I cobbled something together. It turned out to be surprisingly simple so I thought it might be beneficial to post it here.

The Basics

The problem to solve is to randomly create different coloured balloons at different intervals at different locations on the screen and have them rise up at different speeds to disappear off the top of the screen.

To do this we need some resources

Firstly, a sprite that contains all the different balloon colours we will be using. We could use SVG and create the balloons on the fly but the title of this article is "simple" animation so I will leave that for another article.

Once we have the sprites we will need someway to generate new balloons and having done that a way to animate each balloon after it has been created.

This is where the power of JQuery comes to the fore as we will demonstrate below.

Firstly we need our sprite. Break out the trusty 'ol Gimp and use the ellipse tool to create a nice balloon shape. Then use the path tool to create a nice bezier curve string. I could have just used the pencil or paint tool to draw the string but I like bezier curves.
Next we increase the height of the canvas 4 times…
5
 
LVL 38

Administrative Comment

by:lherrou
Comment Utility
JulianH,

Congratulations. The Experts Exchange editors have designated your article as Experts Exchange Approved in recognition of the excellence of your article.
0
 
LVL 38

Administrative Comment

by:lherrou
Comment Utility
Julian,

When the Editors agree, we can also award the coveted Editor's Choice designation, which recognizes the very top articles at Experts Exchange.

CONGRATULATIONS AGAIN!

I look forward to seeing more excellent work from you.

LHerrou
Experts Exchange Editor
0
What is a Lightbox?
A Lightbox is the effect you see when you click, for example, an image and the screen fades out and up pops the same image but in its full size dimensions.

There are lots of Lightbox effects for jQuery.
Problem is they are all (including the smallest one) full of bloated javascript and CSS for what is essentially a very simple task.

This is not a fully fledged lightbox like you will find if you search Google.
It is meant to be a really tiny Lightbox effect you can implement without bloating your page size.

It is only for images and has no navigation (I will expand on this article later if the requirement exists/people want?)

Lets start...

First thing you need to do is make sure you have the jQuery library on your page. So before your closing BODY tag add:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Open in new window

Now we need our thumbnail image.
<img src="http://premium.imagesocket.com/images/2013/07/19/2637029-5czf.jpg" width="70" height="70">

Open in new window

We need to know this image should be targeted by our lightbox so we need to add a class of lightbox
<img src="http://premium.imagesocket.com/images/2013/07/19/2637029-5czf.jpg" width="70" height="70" class="lightbox">

Open in new window

For all your images you just need to continue to add the class="lightbox"

Now for the jQuery magic.
$(document).ready(function(){
	

Open in new window

5
 

Expert Comment

by:Danielx64
Comment Utility
Hi there,

Just a question, is it possible to to put a little x in the top right hand corner so that people know how to get out of the lightbox?
0
 
LVL 58

Author Comment

by:Gary
Comment Utility
Change the append statement to the following replacing the X with an X image or whatever you want to use
$('body').append('<div class="document_backdrop"></div><div class="lb_container"><div style="position:absolute;top:-10px;right:-10px" id="closer">X</div><img src=""></div>');

Open in new window

Replace this
$(document).on('click','.lb_container,.document_backdrop',function(){

Open in new window

with
$(document).on('click','#closer',function(){

Open in new window

0
The most up-to-date version of this article is on my Blog https://iconoun.com/blog/
3
 
LVL 38

Expert Comment

by:lherrou
Comment Utility
An elegant solution, and I can think of other ways to use it as well.

I voted YES above :)
0
Introduction
HyperText Transfer Protocol or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to the WWW in the days after 2005 (and therefore after the advent of jQuery), that seem to evince a misunderstanding of the way the HTTP protocol works.  Since HTTP is the basic building block of web sites and web applications, a clear understanding of the protocol is required to understand how web sites really work.  And perhaps more importantly, it is necessary to understand the protocol so you can build a web site that works like another site you've seen and appreciated.  This article is intended to lift the cloud of confusion that has appeared in the years since the arrival of jQuery, CSS3, animation in web sites, and the phenomenon called Web 2.0.

The confusion has arisen in large measure because of the design movement of web interactivity away from the static page loads and into design paradigms that more closely mimic native applications.  If the hyperlink was the design element that launched the internet revolution, the event handler may be thought of as the design element that has most refined the client experience.  In all cases, at the foundation is the HTTP protocol.

HTTP is a Stateless Client/Server Protocol
Client/Server protocols are two-way communication mechanisms that allow humans to get information from web sites
19
 
LVL 15

Expert Comment

by:Eric AKA Netminder
Comment Utility
Ray,

A typically outstanding article. I've been fumbling through telling people this stuff for a long time, so it's nice to have a clear resource to which to send them.

Thanks!

ep
0
jQuery is a JavaScript library that greatly simplifies JavaScript programming.

AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a new page load.  An HTTP request occurs, but it occurs as a result of a JavaScript event, rather than an explicit page load or form submission.  As a result, the web page takes on an appearance much like a desktop application, with smooth transitions as data is added or removed from the viewport.  This is often referred to as the "Web 2.0" effect.

I found myself looking around for a jQuery/AJAX "Hello World" example (that simplest of scripts to prove that the essential moving parts are working correctly).  There are lots of partial examples in many different places all over the WWW, but nothing seemed complete and well-documented, so I decided to write my own.  Here is the result of that effort.

The Server-Side of the Exercise
To make my example, I decided the essential parts would be the ability to send some data to the server and get a response back, so the first part of the exercise is the server-side script that produces a response containing the data it received from the AJAX request.  AJAX provides a RESTful interface.  The data for the request is sent via GET or POST and the response from the server is sent in the form of browser output.  As a result, it is very easy to test the back-end script. …
19
 

Expert Comment

by:Nico2011
Comment Utility
Thanks Ray - very helpful - hope you are well!
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
Comment Utility
It is very helpful.
0
Hi all! Recently there was EE question and the person wanted to have a multi-column textbox <div> selection, so as a first step to answer I provided a link but that was not complete with JavaScript selection, but had a good style sheet. So as a quest I added a client script using jQuery and as the question progressed I added the multi-column to drop-down div selection and things looked well.
Hence I thought of giving it a proper shape so that everyone can use it freely and tweak as per their requirement.
Here is the look at the completed multicolumn selection.

MultiColumnDropDownSelect
So let’s look at the code to understand better, though things are quite straight-forward.
Javascript:
Here we are using jQuery library shipped along with the VS2010 and updated release works fine.


    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {

            $("#text1").click(function () {
                $("#div1").slideToggle();
            });

            $("#div1 a").click(function () {
                $("#text1").val($(this).text());
                $("#div1").slideToggle();
                $("#text1").focus();
            });
        });
    </script>

Open in new window


1. $("#text1").click(...) : This simply toggles between show and hide of div.
2. $("#div1 a").click(...) : Here whenever we have select the anchor <a> within the <div> the text value of state is set and the div is toggled, we can here also have slideUp instead of slideToggle, and the textbox focus is set.

CSS:


Open in new window

1
Free Tool: Path Explorer
LVL 10
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

DOM Attributes and Properties treatment with jQuery 1.6
by Ivo Stoykov

jQuery 1.6 introduces .prop() and .removeProp() methods which allow modifying or removing a DOM property.


.prop()

method get a property value of the first found element and returns it as a string. If required property has not been set or searched element has not been found returned values will be undefined .

Earlier jQuery versions used to get the value of a property or attribute the .attr() method. Version 1.6 differentiate both attributes and properties supplying method for each of them. For instance .attr(“checked”) of an input type=”checkbox” element will return “checked” or empty string (“”) rather than true/false (as is the case is previous versions).

The preferred way to determine if a checkbox is checked (in cross-browser-compatible way) one of the following might be used:

   
if ( el.checked )
if ( $(el).prop("checked") )
if ( $(el).is(":checked") )

.attr(“checked”) will retrieve the attribute, which does not change but stores the default or initial value of the checked property. Here is a short snippet demonstrating this behavior:

<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>

<script>

Open in new window

2
I have answered several questions lately that were solved utilizing the power of jQuery's AJAX functions, so I thought I would write an article demonstrating the ease of use.

Why should I use jQuery as opposed to regular JavaScript?

Now I know what you may be thinking... why load a whole JavaScript library/framework, just to do a simple AJAX request?  

My answer:  There is no reason.  Don't.  
I believe that you should only use a library like jQuery if you are solving some complex problems and/or you want to use some of the vast custom plug-ins that are available with some libraries.

Should I host the jQuery library or let Google do it?

There are two ways you can include the jQuery library.

Download from jQuery's site and store it on your server
Host it externally through via Google's jQuery stored library
You will see me using the Google-hosted library for the few reasons explained here:
http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/

Enough of the talking, lets get to coding!

In this example I will be using PHP, but since jQuery can be used with just about all web languages - you can use any of them you would like. I am also going to make this article really really simple, so don't expect deep jQuery functionality!

First Include jquery.js (Again, I am using Google)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>

Open in new window


Next is the jQuery function that will execute the request

Open in new window

4
 
LVL 3

Expert Comment

by:Pedro Chagas
Comment Utility
Congratulations! Excellent article.
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
Comment Utility
Thx, great tip
0
by Julian Matz

As of jQuery 1.4 the .live() method supports custom events as well as some standard JavaScript events that it previously didn't support. Among these is the submit event.

Unlike other event listeners, the .live() method also works on DOM nodes that are dynamically loaded, making it very useful if you're working with AJAX for example. With .live('submit') we can now do event handling with HTML forms... Or at least I thought we could. Unfortunately, .live('submit') does not currently work with Internet Explorer.

I recently faced a problem where I needed to come up with an alternative to the .live('submit') method that worked with both Firefox and Internet Explorer. I was able to develop a work-around by using the .live('click') method, and I decided to share with you how I made this solution work.

Below is the code I used to solve the problem, along with a sample HTML form.

The HTML form was retrieved using an AJAX request, and this is why I needed to use the jQuery .live() method. The reason I couldn't have used a different method, like .submit(), for binding my event handler to the submit event is that this method only listens to events for already existing DOM elements, and since my AJAX request loaded the form elements as new DOM nodes, this wouldn't have worked. The .live() method, on the other hand, attaches "a handler to the event for all elements which match the current selector, now or in the future" (with future
3
 
LVL 21

Author Comment

by:Julian Matz
Comment Utility
No problem! And thanks for your feedback b0lsc0tt.
0
 

Expert Comment

by:sapamja
Comment Utility
Thats very nice document.
0
To Start with ...

One of the most annoying things in developing web pages is handling the 'Enter Key' for form submission. The 'Enter Key' makes form submission so easy that the user always tend to use it. The easiest and the most intuitive way is the user enters some text or make some changes to the existing text and then presses 'Enter Key' to submit the form.

Wait a minute....so is there a problem here ?

Yes, of course !

And what is it ?

There are 2 cases.

Case 1 - Form with multiple fields and single submit button

Case 2 -  Form with multiple fields and multiple submit buttons. Lets say - Delete, Update / Save, Cancel etc.

In general, Case 1 is very straight forward and you should not be having any issues because there is only one button and when you press 'Enter Key', that single button will get the focus and will submit the form.

But in Case 2, since there is more than one submit button, when you press 'Enter Key', in most cases the browser will either pick the button that comes first in the source code [IE] or depending on the lowest tab index [Firefox & Opera].

oh Gotchu!

Good.

Do we have a Solution?

Sure. There are several ways to resolve this issue. But if you are looking for an Enterprise Wide Solution you can probably start with the below code.

I am using simple jQuery and HTML form events

Code

Consider the following HTML page with multiple submit buttons -

 

Open in new window

1
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
.bind and .live have been replaced by .on
0
It's a problem I'm sure many of you have faced in developing web applications.  You've got a form to add a new something - perhaps a customer or an item in a to-do list.  When the user clicks that link to add a new item, a new page loads, they fill in the data, hit save, and then get re-directed back to the original page.  Wouldn't it be easier if they clicked that link and the form opened in a modal dialog instead, allowing them to quickly enter their information and hit save without ever having to move from page to page?  Now many of you are probably saying "Yah, that's easy, just create a div on your page, put the form in there, and make that your dialog."  Well that's great, but what if you're trying to achieve maximum compatibility? What happens if for whatever reason a user has JavaScript disabled in their browser?  Suddenly that entire 'add' functionality is lost.

What we'll look at in this article is how to create a generic function that will dynamically build a dialog, load the page via AJAX and display only the form, and then submit that form via AJAX, all without having to make a single change to your form.
For this article, I will be using the core jQuery library (available at http://jquery.com/) as well as the jQuery UI library (http://jqueryui.com/).  At the very least, you will need the UI core and the Dialog widget. The current versions as of writing this article are 1.3.2 of the jQuery library, and 1.7.2 of the jQuery UI library - those are the versions I…
16
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
I suggest you change click to .on("click",function(e) { e.preventDefault();
instead of the return false you have now
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
Comment Utility
Nice.
0

jQuery

16K

Solutions

5K

Contributors

jQuery (Core) is a cross-browser JavaScript library that provides abstractions for common client-side tasks such as Document Object Model (DOM) traversal, DOM manipulation, event handling, animation and Ajax. jQuery also provides a platform to create plugins that extend jQuery's capabilities beyond those already provided by the library.

Related Topics