Showing posts with label attributes. Show all posts

jQuery: How many elements were selected

Anyone who used jQuery, starts with a CSS selector to either attach an event or apply some DOM manipulation. The power of jQuery lies in it’s CSS selector. One of the reasons why jQuery become so popular is probably in the concept shift it made to front-end development. Instead of starting your code with javascript function definitions, you start with DOM element selection and straight to your business requirements manipulating those elements. It abstracted away the problems of code structure and let you get on with your needs by selecting the objects you need.

Sometimes your code might require to identify how many elements were selected by jQuery. It might be to identify if there are any elements on the page or to use the number of elements in some other way. For example to set rowspan on your newly created table row. In this post, you will learn how to find out how many elements were selected and see some examples.

jQuery selector returns an array of elements jQuery object that has .length attribute. So the easiest way is to get the length of returned jQuery object. The size of that object will be equal to the number of selected elements. Also, you can use built in jQuery helper function called .size(). It returns the same value as .length property. So you can use .length or .size() depending on your choice, whichever makes your code more readable.

Examples

Assume we have the following HTML structure:

<div class="container">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
</div>

Here is how you get the number of selected elements and check if there are any elements on the page.

  1. Check the number of elements:

    $('.container').length;  // returns 1
    $('.item').length;       // returns 2
    
    // Same with .size()
    $('.container').size();  // returns 1
    $('.item').size();       // returns 2
  2. Check if there are any elements:

    if($('.container').size() > 0) {
      // There is an element with class "container"
    } else {
      // There is no element with class "container"
    }

Let's see another example. Consider we have the following mark-up for a shopping cart with several order lines in it.

<div class="shopping-cart">
  <div class="order-line">Product 1 – <span>$4.99</span></div>
  <div class="order-line">Product 2 – <span>$9.99</span></div>
</div>

Business requirement: Show a modal box with special offer, if user has more than 1 products in his/her shopping cart.

if($('.shopping-cart .order-line').length > 1) {
  // Show modal box with special offer
}

jQuery: Test/check if checkbox is checked

Testing if certain checkbox is checked using jQuery is pretty simple task. But I, just like many other developers, keep forgetting the exact syntax. So I decided to carry on a little research on the subject and gather all related information including small caveats and write this article for the future reference.

This post covers 4 methods to check if checkbox is checked. All methods especially do the same thing: test if checkbox has checked property set. But depending on the version of jQuery you are using, the methods may vary. Lets consider we have the document setup below and see how to test checkbox checked using different versions of jQuery.

<input id="checkbox"  type="checkbox" name="one" value="1" checked="checked">
<input id="checkbox2" type="checkbox" name="two" value="2">
<input id="checkbox3" type="checkbox" name="thr" value="3">

Using jQuery version 1.6 or newer

As I mentioned above, we need to check the checked property of an element and correct way of doing it is to use .prop() method. So if other methods do not add any value to your code’s readability, please use the first method below.

// First method - Recommended
$('#checkbox').prop('checked')  // Boolean true

// Second method - Makes code more readable (e.g. in if statements)
$('#checkbox').is(':checked')  // Boolean true

// Third method - Selecting the checkbox & filtering by :checked selector
$('#checkbox:checked').length  // Integer >0
$('#checkbox:checked').size()  // .size() can be used instead of .length

// Fourth method - Getting DOM object reference
$('#checkbox').get(0).checked  // Boolean true
$('#checkbox')[0].checked      // Boolean true (same as above)

Earlier version of jQuery (up to v1.5)

jQuery version 1.6 introduced .prop() method to get HTML/DOM element’s property instead of an attribute. Prior to version 1.6 we had to use .attr() method instead. Read more about the difference between .prop() and .attr().

// First method - Recommended
$('#checkbox').attr('checked')  // Boolean true

// Second, Third & Fourth methods – The same as for version 1.6. See above.

Caveats & problems

What if your jQuery selector has a set of more than one checkbox? This is how the methods above will behave?

Case 1:
<input class="check" type="checkbox" name="one" checked="checked">
<input class="check" type="checkbox" name="two">

Case 2:
<input class="check" type="checkbox" name="two">
<input class="check" type="checkbox" name="one" checked="checked">
// Case 1:
$('#checkbox').prop('checked') // true
$('#checkbox').is(':checked')  // true
$('#checkbox:checked').length  // 1
$('#checkbox')[0].checked      // true

// Case 2:
$('#checkbox').prop('checked') // false
$('#checkbox').is(':checked')  // true
$('#checkbox:checked').length  // 1
$('#checkbox')[0].checked      // false

jQuery attribute selector $('elem[name]') does not return updated property value. So use other methods instead.

$('#checkbox[checked]').length;        // Integer 1
$('#checkbox').prop('checked', false); // Uncheck the checkbox
$('#checkbox[checked]').length;        // Still returns 1, not 0

Select all checked checkboxes on the page or within a container.

$("input[type=checkbox][checked]"); // All checkboxes in the document that are checked

This is all I could find on the subject. Please bookmark or share the article so that it is easier to find it later.

HTML: The difference between attribute and property

In this short post I will explain the difference between attributes and properties in HTML. The .prop() function introduced in jQuery 1.6 raised a lot of questions about the difference and I hope this post will help you to understand it.

What is an attribute?

Attributes carry additional information about an HTML element and come in name=”value” pairs. Example: <div class=”my-class”></div>. Here we have a div tag and it has a class attribute with a value of my-class.

What is a property?

Property is a representation of an attribute in the HTML DOM tree. So the attribute in the example above would have a property named className with a value of my-class.

Our DIV node
 |- nodeName = "DIV"
 |- className = "my-class"
 |- style
   |- ...
 |- ...

What is the difference between attribute and property?

Attributes are in your HTML text document/file, whereas properties are in HTML DOM tree. This means that attributes do not change and always carry initial (default) values. However, HTML properties can change, for example when user checks a checkbox, inputs text to textarea or uses JavaScript to change the property value.

Here is a visual representation:
HTML                          DOM
<input value="default" />     value = default



----------------
Current values:
Attribute: "default"          Property:  "default"

Assume user inputs his name "Joe" into the inputbox. Here are what attribute and property values of an element will be.

HTML                          DOM
<input value="default" />     value = Joe



----------------
Current values:
Attribute: "default"          Property:  "Joe"

As you can see, only element’s property is changed, because it is in the DOM and dynamic. But element’s attribute is in HTML text and can not be changed!

I hope this helps to understand the difference between attributes and properties. If you have any questions please leave them on jQueryHowto Facebook page.

Also, stay tuned for the next post about the difference between jQuery.attr() and jQuery.prop() and when to use one over another.

Can't set / change CSS background image with jQuery problem solution

Hello everyone. I’ve been busy lately with some projects and could not write much on “jQuery HowTo” blog. So, when I came across this little problem, I thought I would share it with you.

Anyway, I was working on one of my projects and I needed to set a background image using jQuery on some div. At first my background setting code looked like this:

$('#myDiv').css('background-image', 'my_image.jpg');
// OR
$('#myDiv').css('background', 'path/to/image.jpg');

But to my surprise it didn’t do the trick. My div’s had no background images. FireBug showed no CSS background properties set and I could not see why background images were not being set by jQuery. Anyway, after 10-20 minutes I realized that jQuery sets CSS properties as key : value and in our case valued had to be in url(image.jpg) form.

Solution to “background images are not being set” problem is to set them like this:

$('#myDiv').css('background-image', 'url(my_image.jpg)');
// OR
$('#myDiv').css('background', 'url(path/to/image.jpg)');

Identifying & locating mouse position in jQuery

While writing the next jQuery tutorial I needed to identify and locate where the mouse was on the page. Tracking mouse position on the page with jQuery is easy. You don’t need to check what browser the script is running like it is used to be with plain JavaScript. To identify where the mouse is in jQuery all you have to do is to read event object’s .pageX and .pageY properties.

Example:

$().mousemove(function(e){
   // e.pageX - gives you X position
   // e.pageY - gives you Y position
});

The above jQuery code is binding a new ‘on mouse move’ event to the current document and triggered every time mouse moves. The coordinates are calculated in pixels from top left corner of the document. See the above code in action.

You may also want to know the coordinates of the mouse relative to some <div> or an element. Since jQuery returns mouse position relative to the document root, by subtracting element’s position from document root you get mouse positions relative to that element. Long story short here is the code to do just that:

$("#someDiv").click(function(e){
    var relativeX = e.pageX - this.offsetLeft;
    var relativeY = e.pageY - this.offsetTop;
});

Don’t forget that you can bind any mouse event to any element and then get mouse positions. You can easily create a draggable object with click and mousemove events by simply setting the CSS top and left values to .pageX and .pageY.

Anyway, that’s how you locate and handle mouse positions in jQuery. As always, you don’t need to worry about cross browser compatibility issues while using jQuery. To learn more see more examples here.

Disable submit button on form submit

Form submission is one of the most used actions and double form submission is one of most occurred problems in web development. Rather than dealing with this problem server side, eating up your CPU process time, it is much easier and better to deal with this problem client side using JavaScript. When we talk javascript, what it a better way to write it other than using jQuery?!

So this Friday’s quick tip is disabling form submit button on its click or preventing double form submission by disabling submit button.

Consider we have this HTML form in our code:

<form id="myform" action="someUrl.php" method="get">
    <input name="username" />
    <!-- some more form fields -->
    <input id="submit" type="submit" />
</form>

Here is a jQuery code that disables submit button on form submission:

$('#myform').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
});

The above jQuery code binds a submit event to our #myform form, then finds its submit button and disables it.

Bonus: disable submit button on form submission for all forms on your page.

// Find ALL <form> tags on your page
$('form').submit(function(){
    // On submit disable its submit button
    $('input[type=submit]', this).attr('disabled', 'disabled');
});
Want to disable any other elements using jQuery? Read my previous “Disabling and enabling elements in jQuery” (very short) post.

jQuery image swap or How to replace an image with another one using jQuery

Swapping one image with another is probably one of the most used javascript techniques. Also Dreamweaver made “image replacement” even easier for non HTML/Javascript programmers by including this feature out of the box. One thing about Dreamweaver’s image swapping javascript is that it’s not the most beautiful javascript code. Well, as always with anything javascript related, jQuery is to the rescue.

jQuery makes dynamic image swapping a peace of cake. All you need to do to replace your image with another one is to replace its src attribute. The browser will take care of the rest.

Here is an example:

$("#myImage").attr("src", "path/to/newImage.jpg");

In the code above we are:

  1. Selecting an image to be replaced;
  2. Changing its src attribute to the new replacer image’s URL.

TIP:
To avoid page jumping and improve user experience it is a good idea to preload your images before you swap them.

jQuery: How to disable form element, link, etc.

In this post you will learn how to disable and enable different HTML elements (input, textarea, links, etc.) using jQuery. First, let's categorize the diffent types of elements that can be disabled using jQuery. We can categorize them into 3 general categories. Method of disabling items in each category is different.

If I missed some other element that does not fall under any of those 3 categories please leave a comment. The idea behind any method is very simple though. Usually all you have to do is to change element's attribute. See example below to get an idea.


Here are the three categories that we mentioned:

  1. Form elements - input fields, textarea, buttons, select boxes, radio buttons, etc.
  2. Anchor links - make text links non clickable.
  3. Bound jQuery events - for example bound click event on a <div>.

1. Disable form elements

Consider you have a form and you need to disable some element on it. All you have to do to disable it is to add disabled property to that element (input, textarea, select, button). Let's see an example:

<form action="url" method="post">
  <input type="text" class="input-field" value=".input-field">
  <input type="button" class="button-field" value=".input-field">
  <input type="radio" class="radio-button" value=".input-radio">
  <select class="select-box">
    <option value="1">One</option>
  <select class="select-box">
</form>

jQuery code to disable form elements and enable them back:

// jQuery code to disable
$('.input-field').prop('disabled', true);
$('.button-field').prop('disabled', true);
$('.radio-button').prop('disabled', true);
$('.select-box').prop('disabled', true);

// To enable an element you need to either
// remove the disabled attribute or set it to "false"
// For jQuery versions earlier than 1.6, replace .prop() with .attr()
$('.input-field').prop('disabled', false);
$('.button-field').removeAttr('disabled');
$('.radio-button').prop('disabled', null);
$('.select-box').prop('disabled', false);

Caveats & notes

Setting form element's disabled attirbute causes browsers not to sent that element to the server on form submit. In other words, your server script will not receive that form element's value. The workaround to that problem is to sent readonly attribute instead of disabled. This will make your fields non editable, but browser will still send the data to the server.

2. Disable anchor link (<a href="" ...>)

Now, let's see how to disable a link on your page, so that when user clicks on it browser does not follow it. There 2 methods to do that:

  1. Catch click event and prevent default bahaviour;
  2. Replace link's href property to "#".

I personaly prefer the first method, but you may have different needs. Let's see both methods in action.

<!-- Consider we have this HTML -->
<a href="aboutus.html" class="internal">some internal link<a>
<a href="http://www.google.com" class="external">external link<a>
// Bind "onclick" event
$('.internal').on("click", function(e){
  e.preventDefault();
  return false;
});

// Replace link's "href" attribute
$('.external').prop('href', '#');

Caveats & notes

In the onclick example above we added e.preventDefault() method which would stop event propagation. If you have other events relying on it on parent elements, please remove that method call. Also, when setting link's new href attribute, you can save the initial value with .data() method in order to set it back later.

// Removing e.preventDefault();
$('.internal').on("click", function(e){
  return false;
});

// Recording link's "href" attribute for later use
$('.external').data('original-href', $('.external').attr('href'));
$('.external').prop('href', '#');

// Setting it back
$('.external').prop('href', $('.external').data('original-href'));

3. Unbinding bound jQuery events

Last but not least is unbinding previously bound events. This is probably the easiest of the batch. All you have to do is to use jQuery's .unbind() method. Let's see an example:

<div class="some-elem">
  Click me
</div>
// Bind "click" event
$('.some-elem').on('click', function(){
  alert("Div is clicked!");
});

// Unbind "click" event
$('.some-elem').unbind('click');

Caveats & notes

Unbinding click event will unbind all click events that were bound to that element. So, if you want to unbind only your click event, without affecting others you have 2 options:

  1. Namespace your events;
    // Namespacing events
    $('.some-elem').on('click.my_event', function(){
      alert("Div is clicked!");
    });
    
    // Unbind namespaced event
    $('.some-elem').unbind('click.my_event');
  2. Use function reference when binding and unbinding.
    // User function reference
    var my_func = function(){
      alert("Div is clicked!");
    };
    
    // Bind using function reference
    $('.some-elem').on('click', my_func);
    
    // Unbind namespaced event
    $('.some-elem').unbind('click', my_func);