Categories
jQuery Tips

jQuery Tips — Attribute Check, Break out of Each, and Form Submission

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.

Check to See if There is an Attribute on an Element

We can check to see if there’s an attribute on an element by using the attr method to get the attribute with the given name.

For instance, we can write:

const attr = $(this).attr('name');

if (typeof attr !== 'undefined' && attr !== false) {
  // ...
}

We check if attr isn’t undefined and that it’s not false in the if statement.

Plain JavaScript also has the hasAttribute method.

For example, we can write:

this.hasAttribute("name")

where this is the DOM element object.

Preloading Images with jQuery

To preload images with jQuery, we can create our image element and then we cat set the src properties to the URL for the image.

For instance, we can write:

const arrayOfImages = [
  'http://placekitten.com/200/200',
  'http://placekitten.com/201/201',
  'http://placekitten.com/199/199'
];

$(arrayOfImages).forEach((a) => {
  $('<img/>')[0].src = a;
});

We create an img element on the fly and set the src property to the URL that we want.

Also, we can use the Image constructor to create the image element.

For example, we can write:

const arrayOfImages = [
  'http://placekitten.com/200/200',
  'http://placekitten.com/201/201',
  'http://placekitten.com/199/199'
];
$(arrayOfImages).each((a) => {
  (new Image()).src = a;
});

The a parameter in the callback is the URL.

jQuery Ajax POST Request with PHP

We can use the ajax method with to thw PHP script that we want to make the request to.

For instance, we can write:

const data = $('form').serialize();

$.ajax({
  url: "test.php",
  type: "post",
  data,
  success: (response) => {
     //...
  },
  error: (jqXHR, textStatus, errorThrown) => {
     console.log(textStatus, errorThrown);
  }
});

We make a POST request to test.php by first serializing the input values with the serialize method so that we can send the values.

We can then call the ajax method with an object that has the URL to make the request to.

type is the type of request.

data has the data.

success has the request success handler.

error has the error handler, which is invoked when a network error occurs.

If we want to submit a form on submit, we can call the submit method on the form element.

And in the callback for submit , we can make the Ajax request the same way.

For instance, we can write:

$("form").submit(function(event) {
  event.preventDefault();
  const data = $(this).serialize();

  const ajaxRequest = $.ajax({
    url: "test.php",
    type: "post",
    data
  });

  ajaxRequest.done((response, textStatus, jqXHR) => {
    alert('Submitted successfully');
  });

  ajaxRequest.fail(() => {
    alert('There is error while submit');
  });
});

We call the submit method with a callback.

The callback has the code to get the value from the form and then make an Ajax request.

First, we call event.preventDefault() to prevent the submission of the data with the default submission behavior.

We get the form’s value with:

const data = $(this).serialize();

this is the form element.

Next, we call jQuery’s ajax method to make the request for the form values to submit.

The url , type , and data properties are the same.

Then we can listen for the result with the done method to get the response when it’s successful.

We have the callback with the responnse parameter to get the response.

textStatus gets the status text.

jqXHR has the XmlHttpRequest object.

We also have the fail method to listen for any failures.

The fail callback will be called when there’s a network error.

How to Break Out of jQuery each Loop

We can return false in the callback by writing:

$.each(array, (index, value) => {
  if(value === "bar") {
    return false;
  }
});

We loop through an array with each .

In the callback, we get the index with the array index.

value has the value of the entry being iterated through.

We check that if value is 'bar' , then we return false to end the loop.

Conclusion

We can check for attribute values with the attr method.

To preload images, we can create image elements and set the src property of them with the image URL.

We can submit form input values with Ajax by serializing the values and then make the request.

And we can break out of an each loop with return false .

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 *