Categories
jQuery Tips

jQuery Tips — Form Values, Select, and Request Headers

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.

Get Form Input Field Values Using jQuery

We can get the form fields and their values with various methods.

One way is to call submit and then get all the input fields.

For example, we can write:

$('form').submit(() => {
  const inputs = $('form :input');
  const values = {};
  inputs.each(function() {
    values[this.name] = $(this).val();
  });
});

We get the form element and call the submit method on it,

Then we loop through the inputs and call each to loop through their values.

In the each callback, we get the form name of the field with this.name and the inputted value with $(this).val() .

jQuery also has the serializeArray method to let us get the fields as an array.

Then we can use each on it to loop through each field.

For example, we can write:

const values = {};
$.each($('form').serializeArray(), (i, field) => {
  values[field.name] = field.value;
});

We call serializeArray on the form element to convert the fields into an array.

Then we have a callback that gets the field with the field parameter.

We get the name and value properties to get the name and value attributes respectively.

Also, we can call serialize to get the value of each field.

For example, we can write:

$('form').submit(function() {
  const values = $(this).serialize();
});

We get the values from the form element with the serialize method.

Get the Rendered Height of an Element with jQuery

We can get the rendered height of an element with jQuery by using various methods.

To do this, we can write any of the following:

$('#foo').height();
$('#foo').innerHeight();
$('#foo').outerHeight();
$('#foo').outerHeight(true);

height returns the height of the element excluding the margin, padding, or border.

innerHeight gets the height of the div with padding but without the border or margin.

outerHeight returns the height of the element including padding and border.

outerHeight with the argument true returns the height including border, margin, and padding.

Get All Options of a Select Using jQuery

To get all options of a select element using jQuery, we can just use the $ method with the selector to get all our options.

For instance, we can write:

$("select#id option").each(function() {
  //...
});

We get the select element with the ID id ‘s option elements with this selector.

Then we use each to iterate through all of them.

Alternatively, we can use the map method to get the values from the option elements:

$("select#id option").map(function() {
  return $(this).val();
}).get();

We get the value attribute value of each option element with the callback that we have.

get returns the DOM element matched bu the jQuery object.

We can also use find to specifically get the option child elements in the select element.

For example, we can write:

$('select#id').find('option').each(function() {
   console.log($(this).val());
});

We call find to get the option elements that are the child of the select with the ID id .

And we get the value of the option inside the callback.

Convert a jQuery Object into a String

We can convert a jQuery object into a string bu calling the html method.

For example, we can write:

$('<div>').append($('#foo').clone()).html();

to create a div.

Then we append the clone of the element with ID foo into it.

Finally, we get the HTML string representation of the element with ID foo .

Also, we can use the outerHTML property to make our lives easier.

For instance, we can write:

$('#foo').prop('outerHTML');

We get the element with ID foo and call the prop method on it with 'outerHTML' to get the outerHTML property of the element.

Add Request Headers to Request with jQuery

We can add access control request headers to a request with the setRequestHeader method.

For instance, we can write:

$.ajax({
  type: "POST",
  beforeSend(request) {
    request.setRequestHeader("Authority", authorizationToken);
  },
  url: "/login",
  data: JSON.stringify(request),
  processData: false,
  success(msg) {
    alert('success');
  }
});

We call ajax with the beforeSend method to run code before a request, which includes adding request headers.

It takes a request parameter, which we can call setRequestHeader with.

The first argument is the key and the 2nd is the value.

Conclusion

There are many ways to get the height of an element.

We can add request headers to a request with ajax .

We can also get form values and options in various ways.

Categories
jQuery Tips

jQuery Tips — Arrays, Ajax, Textbox Changes, and Arrow Keys

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.

Remove Specific Value from an Array Using jQuery

jQuery has a grep method to let us return a new array that doesn’t include the item that we want to remove.

For instance, we can write:

const arr = [1, 2, 2, 6, 2, 6, 8, 3];
const itemToRemove = 2;
const newArr = $.grep(arr, (value) => {
  return value !== itemToRemove;
});

We call $.grep with an array to check for.

And we pass in a callback to return an array that returns a boolean expression to return the matches.

value !== itemToRemove indicates that we return an array without the itemToRemove ‘s value.

Use Basic Authentication with jQuery and Ajax

With jQuery, we can use basic authentication if we set the request header.

To do that, we can write:

beforeSend(xhr) {
  const token = btoa(`${username}:${password}`);
  xhr.setRequestHeader ("Authorization", `Basic ${token}`);
},

We create a token from the username and password combined together.

Then we set the Authorization header with the token.

Binding Arrow Keys with jQuery

We can listen for arrow key presses by using the keydown method.

For instance, we can write:

const arrow = { left: 37, up: 38, right: 39, down: 40 };

$(window).keydown((e) => {
  switch (e.which) {
    case arrow.left:
      //..
      break;
    case arrow.up:
      //..
      break;
    case arrow.right:
      //..
      break;
    case arrow.down:
      //..
      break;
  }
});

We listen to the key down on the window.

Then we can get the event object in the parameter of the callback.

It has the which property with the key code for the key that we pressed.

Then we can use a switch statement to look for matches for the key that’s pressed.

Converting a JavaScript Object to an Array Using jQuery

We can convert a JavaScript object to an array using the map method.

It works with both objects and arrays.

For instance, we can write:

const obj = {
  1: 'foo',
  2: 'bar'
};
const array = $.map(obj, (value, index) => {
  return [value];
});
console.log(array);

We call map with our obj object as the first argument.

In the 2nd argument, we pass in a callback that takes value of each object entry as the first parameter.

The index is the key that’s being looped through is the 2nd parameter.

We return the value in the array to return put the item in the array.

It should be enclosed in an array.

Then we can check the array value with the console log.

How to Detect that a Textbox’s Content has Changed

To detect that a text box’s content has changed, we can listen to the input event.

For example, we can write:

$('#textarea').on('input', () => {
  //...
});

We can do the same thing with bind :

$('#textarea').bind('input', () => {
  //...
});

We can also listen to the propertychange and paste events to listen to input change and pasting text.

For instance, we can write:

$('#textarea').on('input propertychange paste', () => {
  //...
});

Scroll Automatically to the Bottom of the Page

We can scroll automatically to the bottom of the page by calling animate to scroll to the bottom of the page.

For instance, we can write:

$('html,body').animate({ scrollTop: document.body.scrollHeight }, "fast");

We call animate with an object.

The object has some options for scrolling.

scrollTop is the y-coordinate that we want to scroll to.

The 2nd argument is the speed of the animation.

Show Loading Spinner in jQuery

We can show and hide a loading spinner with the show and hide method.

For instance, we can write:

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

spinner has the loading spinner element.

We hide it at the beginning.

Then when the Ajax request starts, we show the spinner.

This is done by passing in a callback to the ajaxStart method and then calling show on our spinner element.

Likewise, we can hide the spinner by call spinner.hide() in the callback of the ajaxStop method.

Conclusion

jQuery has a grep method that acts like the filter method of JavaScript arrays.

We can listen to arrow key presses with jQuery.

ajaxStart and ajaxStop let us run code when the Ajax request starts and end respectively.

jQuery’s map method works with objects and arrays.

Categories
jQuery Tips

jQuery Tips — Disable Scroll, Copy for Formatting, Toggle Elements

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.

Disable Scrolling Temporarily

We can disable scrolling temporarily by hiding the overflow from the div that we’re scrolling.

For instance, we can create a disableScroll function to disable the scrolling.

We can do that by writing:

function disableScroll() {
  document.getElementById('scrollbar').style.display = 'block';
  document.body.style.overflow = 'hidden';
}

We get the element with ID scrollbar and make it display as a block element.

Then set overflow to hidden.

Copy to Clipboard with Formatting Using jQuery

To copy text to the clipboard with formatting using jQuery, we can make our element that has formatting editable.

Then we can set a handler for the focus event.

When the element is focused, we call the document.execCommand method to select all the items.

Once the items are selected, we can call the copy command on the document.

And then we call removeChild on the element.

To do that, we can write:

const copyWithFormatting = (elementId) => {
  const temp = document.createElement("div");
  temp.setAttribute("contentEditable", true);
  temp.innerHTML = document.getElementById(elementId).innerHTML;
  temp.setAttribute("onfocus", "document.execCommand('selectAll', false, null)");
  document.body.appendChild(temp);
  temp.focus();
  document.execCommand("copy");
  document.body.removeChild(temp);
}

We create a temporary div, then make that editable by setting the contentEditable attribute.

Then we get the HTML from the element with elementId and set that as the HTML content of the innerHTML of the temp element.

And then we add a focus handler on it to select all the items in the element with:

temp.setAttribute("onfocus", "document.execCommand('selectAll', false, null)");

Then we call appendChild to attach that to the body.

And then we focus on the temporary element we created.

Once we did that, we can call the 'copy' command to copy the content of the temporary element since we selected everything.

And then when we finish copying, we call removeChild to remove the temporary element.

However, we’ve to know that execCommand is marked as obsolete.

When the new clipboard API is widely available, then we should replace it with the new API.

Skip to the Next Iteration in jQuery.each()

To skip to the next iteration with $.each , we can return true in the callback to skip to the next iteration.

For instance, we can write:

const arr = ['foo', 'bar', 'baz', 'qux'];
$.each(arr, (i) => {
  if (arr[i] === 'bar') {
    return true;
  }
  console.log(arr[i]);
});

We skip to the next iteration by returning true in our callback as we did in:

if (arr[i] === 'bar') {
  return true;
}

Change CSS Display None or Block Property Using jQuery

jQuery has dedicated methods to let us change elements to display block or none.

For instance, we can write:

$('#foo').hide();

to hide the element with ID foo.

Also, we can write:

$('#foo').show();

to show our the element with the ID foo.

There’s also the CSS method that we can use to do the same thing.

For instance, we can write:

$("#foo").css("display", "none");

to hide the element and free up space for other elements.

And we can write:

$("#foo").css("display", "block");

to make the element with ID foo display as a block element.

Submitting a Form on ‘Enter’ with jQuery

We can submit a form when the Enter key is pressed by listening to the keypress event with the keypress method.

For instance, we can write:

$('.input').keypress((e) => {
  if (e.which === 13) {
    $('form#task').submit();
    return false;
  }
});

We listen to the keypress event on the element with class input .

We call keypress to add the keypress listener to it.

In the handler callback, we use the which property to get the key code for the key that’s pressed.

If it’s 13, then the Enter key is pressed.

Then we call submit on the form element with ID task to submit the form’s content.

And we’ve to return false at the end to stop the default submit behavior and to stop the propagation of the keypress event.

Conclusion

We can disable scrolling by disabling overflow from the body.

To copy content from an element, we can use the document.execCommand method to do it.

Even though it’s obsolete, we can use it until the clipboard API is widely available.

And we can return true to skip an iteration when we use each .

Categories
jQuery Tips

jQuery Tips — Slim Package, each and reverse, Copy to Clipboard

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.

Using jQuery .each() to Iterate Backwards

To call each to iterate through an array backward, we can use the reverse method to reverse the items.

For instance, we can write:

$($("li").get().reverse()).each(function() {
  /* ... */
});

We get all the li elements, convert the Node list to an array with get .

Then we call reverse to reverse the items.

Now we can call each to iterate through each item in reverse.

We can also create our own reverse plugin to reverse the items.

For example, we can write:

$.fn.reverse = [].reverse;
$("li").reverse().each(function (i) {
    $(this).text(`item-${i}`);
});

We created the reverse jQuery plugin with by getting the reverse method of the array and returning it.

Then we can call reverse with our jQuery object.

Then that returns an array and we can call each on it.

Use the Same Click Event for Multiple Elements with jQuery

We can add the same click handler to multiple elements by using the on method.

For instance, we can write:

$('.foo, .bar').on('click', onClick);

where onClick is an event handler function.

We listen to the click event on all elements with class foo and bar .

We can also use the on method to listen to multiple events with multiple elements.

For example, we can write:

$(document).on("click touchend", ".foo, .bar, .baz", function () {
  //...
});

We listen to the click and touchend events with all elements with the classes foo , bar , and baz .

The function is the event handlers.

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

Differences Between Normal and Slim Package of jQuery

The slim jQuery package has several features removed from the normal jQuery package.

jQuery.fn.extend is removed fo we can’t create our own instance methods with the jQuery constructor.

jQuery.fn.load is also removed so we can’t load data from the ether and place the returned HTML into a given element.

jQuery.each is also removed, so we can’t iterate over array items with it.

jQuery.expr.filters.animated is removed so that we can’t use it for animations.

Ajax methods like jQuery.ajaxSettings.xhr, jQuery.ajaxPrefilter, jQuery.ajaxSetup, jQuery.ajaxPrefilter, and jQuery.ajaxTransport are also gone.

XML parsing methods like jQuery.parseXML is also removed.

jQuery.easing , jQuery.animation and jQuery.speed aren’t included in the jQuery slim package.

These are animation effect packages that we may not need.

If we don’t use these methods, then we can use the jQuery slim package instead of the normal one.

jQuery Set Cursor Position in Text Area

We can set the cursor position in the text area by using the setSelectionRange or the createTextRange method.

For instance, we can write:

const setSelectionRange = (input, selectionStart, selectionEnd) => {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    const range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

We check if the setSelectionRange method and use that if it exists.

We call focus on the input and then call setSelectionRange to set the selection from by the start and end position.

With the createTextRange method, we can do the same thing.

It’s more complex that setSelectionRange .

We have moveEnd and moveStart to move the selection cursor to the position that we want.

And then we call select to make the selection.

Copy to Clipboard Using jQuery

We can create a function to copy to clipboard using jQuery.

The function would create an input, put the text in it, and then select the text.

Then we call execCommand with the argument 'copy' to copy the selection to the clipboard.

And then we remove the element that we created.

For instance, we can write:

const copyToClipboard = (element) => {
  const $tempInput = $("<input>");
  $("body").append($tempInput);
  $tempInput.val($(element).text()).select();
  document.execCommand("copy");
  $tempInput.remove();
}

We created an input element, attached it to the body.

And then put whatever element’s text into the element as its value.

Then we call select in it to select all the text.

And then we call execCommand on it.

Once that’s done we remove the element by calling remove .

Conclusion

We can copy text to the clipboard by putting it in an input and then send the 'copy' command on it.

With jQuery, we can attach multiple events to multiple elements.

And we can create our own reverse jQuery plugin to reverse the item we iterate through.

Categories
jQuery Tips

jQuery Tips — Checkboxes, Loading Messages, Getting Elements

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.