Categories
jQuery Tips

jQuery Tips — Checkboxes, Loading Messages, Getting Elements

Spread the love

Despite its age, jQuery is still a popular library for manipulating the DOM.

In this article, we’ll look at some tips for working with jQuery.

jQuery Selectors on Custom Data Attributes

We can select custom data attributes by passing the data attribute name and value into the CSS selector.

For instance, we can write:

$("ul[data-group='fruits'] li[data-choice='apple']")

The code gets the ul with the data-group attribute set to fruits and the li inside it with the data-choice attribute set to apple .

We can also get elements with a data attribute not equal to something.

For instance, we can write:

$("ul[data-group='`fruits`'] li:not([data-choice='`apple`'])")

This gets the ul element with data-group attribute set to fruits .

And data-choice attribute is not set to apple as indicated by the not selector.

jQuery UI has the custom :data selector.

Check State Changed Even with jQuery Checkbox

To watch for state changes of a checkbox, we can call the change method.

For instance, we can write:

$("#checkbox").change(function() {
  if(this.checked) {
    //...
  }
});

We get the checkbox with ID checkbox and call change on it to listen for changes for the checkbox.

In the callback we pass in, we use this.checked to get the checked value of the checkbox.

Alternatively, we can use the on method to listen for the change event.

For example, we can write:

$(document).on('change', '#checkbox', function() {
  if (this.checked) {
    //...
  }
});

We call the on method to listen to events.

We call it on document so that we can do event delegation.

'change' means we’re listening to the change event.

'#checkbox' is the selector for the checkbox element that we’re listening to.

The 3rd argument is the callback.

document.getElementById vs jQuery $()

We can achieve the same effect as document.getElementById with the $ function.

To do that, we can write:

const fooEl = $('#foo')[0];

The [0] is what’s needed to get the DOM object of the element with ID foo .

That is the same as:

document.getElementById('foo');

Removing Multiple Classes with jQuery

To remove multiple classes with jQuery, we can call removeClass to remove multiple classes.

Each class should be separated by a space in a string.

For instance, we can write:

$("#foo").removeClass("class1 class2");

Then we cal remove the class1 and class2 classes from the element with ID foo with the removeClass method.

Escaping HTML Strings with jQuery

To escape HTML strings, we can pass it through the text method and then call the html method to return text that’s escaped with HTML entities.

For instance, if we have:

$('<div/>').text('peter, paul & mary').html();

We get:

"peter, paul &amp; mary"

returned.

Get Class Name of an Element

To get the class names of an element, we can do that in various way,

One way is to use the attr method with 'class' as the argument.

For instance, we can write:

const className = $('#foo').attr('class');

The get the class attribute of the element with ID foo as a string.

In event handlers for jQuery objects, we can use the className property of this to get the element.

For example, we can write:

$('#foo').click(function() {
  console.log(this.className);
});

We get the className property in the click handler for the element with ID foo .

The hasClass method lets us check if a class is added to an element.

For instance, we can write:

$('#foo').hasClass('class');

We can check if the class class name is added to the element with ID foo .

Check if Object is a jQuery Object

We can check if an object is a jQuery object using the instanceof operator.

For example, we can write:

if (obj instanceof jQuery){
  console.log('obj is a jQuery object');
}

We just check of obj is an instance of jQuery to check that.

Show a “ Loading…” Message Using jQuery

To make this easy, we just add an element with a loading message and show and hide it depending on what we’re doing.

For instance, for an ajax request, we can create a loading message by writing:

<div id="loading">
  <p>loading...</p>
</div>

Then we can write:

$(document)
  .ajaxStart(() => {
     $('#loading').show();
  }).ajaxStop(() => {
     $('#loading').hide();
  });

to toggle a message on and off.

We toggle the loading message on when an ajax request starts with ajaxStart ‘s callback.

And we do hide the loading message when the ajax request is done with the ajaxStop callback.

Conclusion

We can check if a checkbox if checked by listening to various events.

And we can show or hide a loading message with jQuery.

Strings can also be escaped with HTML entities.

Class names can be retrieved in various ways.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *