Beginner

3 Useful jQuery Snippets for Handling Table Data

Do you want the ability to be able to dynamically edit and manage your tables? With jQuery, it’s pretty easy to get data and change table elements dynamically using only a few lines of code. The snippets below will show you how to add a new row to your table, how to retrieve all values in a row from a click event, and how to count the number of rows that a table has by using simple and lightweight plain jQuery code.

Counting Table Rows

If you find yourself wanting to know how many rows are in your table, you can use the following snippet to let jQuery do all the calculations for you:

$("#my-table").after(function () {
 console.log($('tr', this).length + " rows.");
});

The code above logs to the console how many rows are in your table with the ID of “my-table”, and it only takes two lines of jQuery to do it!

Get Row Values from Click Event

What if you want to be able to click on a table row and have all the data within the cells of that row be logged to the console? Achieving this is actually pretty straightforward. Check out the code snippet below to see how it’s done using jQuery:

$(“#my-table tbody”).on(“click”, “tr”, function () {
var rowdata = $(this).closest(‘tr’).find(‘td’).map(function () {
return $(this).text();
}).get().join();
console.log(rowdata);
});

In only 5 lines of jQuery, you can log all the data of a table row to your console just by clicking on it. As you can see, the trigger is a click event, and then we use other jQuery methods like find, map, and join events to gather all the data before logging it to the console.

Add Row on Click Event

This code will add a new row below any row that you click on using jQuery. Be sure to customize the row variable so that the amount of cells the new row has matches the amount of your table. Check out the code snippet below.

$(function () {
 $("#my-table tbody").on("click", "tr", function (e) {
 if (e.target.type != "text") {
 var row = $("<tr><td><input /></td><td>-</td><td>-" +
 "</td><td>-</td><td>-</td></tr>");
 $(this).after(row);
 }
 });
});

 

How to Use jQuery’s .delay() Method

jQuery’s .delay() method is one that can be used, probably quite obviously, to delay code from being executed. In particular, it can be used to make certain actions or animations last longer because the code is delayed. As a developer, there are a bunch of different reasons that you might want to use a delay. Maybe you want things to load or animate a certain amount of time after a page load or an event trigger. Using this method is also a really easy way to have something happen, have a short delay, and then go back to the way that it was.

For example, if you want a div to hide after a certain trigger event and then show again after a certain delay, you would use the delay method in a similar context to the way its used in the snippet below:

$("div").click(function{
    $(this).hide().delay(5000).show();
})

So in the snippet above, the div will be hidden after you click it for 5000 milliseconds (5 seconds) and then after the 5000 ms delay, it will appear again. The first line with the .click() method is the trigger event, which is followed by a function that executes the hide/delay/show events. So the div is hidden, then there is a 5 second delay where no code is executed, and then it is shown again.

This is just one example of how to use this versatile method. The speed parameters taken by the method (in the example above it’s “5000) can either be a number value (in milliseconds) or a fixed value (slow or fast). This is quite important, as it determines the length of time of the delay and, in the example above, the duration of the hide/show effect. Remember when using number values that the time is measured in milliseconds, so multiply the amount of seconds you want the delay to last by 1000 to be sure that you’ve got the right time.

How to Use JavaScript to Detect Devices

The great thing about JavaScript is how it enables you to dynamically make changes to your code based on certain events or conditions. One such condition that might cause you to want to make changes to  your code (or at least some slight modifications) is which type of device is being used to view your projects or web pages. This is because each mobile device (iPhone, Android, iPad, etc) have different dimensions and aspect ratios that unfortunately don’t always respond to your code and display your designs in exactly the way you’d like. Luckily, JavaScript provides a very easy and simple way to test for a particular type of device and execute some code based on whether or not your user is using the particular device you’ve singled out.

Check out the snippet below to see how it works:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
 // Do something
} else {
 // Do something else
}

Obviously, the snippet as it stands wouldn’t really do anything. You ned to choose one of the 7 device options provided and use that with the .test() method to test for that one particular device you’re trying to compensate for (if you want to set code specific to another type of device, you’ll have to add another if statement). Then, once you’ve selected the type of device you’re trying to write code for, you can insert the code you want to be executed into the if statement. You can be trying to change the color, shape, or dimensions your elements so that they better fit within the viewports of your chosen type of device, or you can simply use the code to troll iPhone users (see example below) — it’s totally up to you.

Check out the example below to see one way in which you can use the device detector code.

if( iPhone.test(navigator.userAgent) ) {
 alert("Androids Rule");
} else {
 alert("Congratulations, you're not using an iPhone");
}

How to Find the Coordinates of Your Mouse Position

Did you know you can use jQuery to find the coordinates of your cursor? It only takes a few lines of code to get the x and y coordinates of where the mouse is positioned on a page. With these coordinates, you can execute other functions and lines of code based on where the cursor is located on the page. It’s also just a cool trick to offer your users — for example, you can choose to allow them to click a button that will reveal the x and y coordinates of their mouse.

Check out the code snippet below to see how it’s done:

function cursorPosition(elementID, mouseX, mouseY) {
  var offset = $('#'+elementID).offset();
  var x = mouseX - offset.left;
  var y = mouseY - offset.top;

  return {'x': x, 'y': y};
}

Insert the above function into your code to reveal the values of the x and y coordinates of your cursor’s position. This code can be customized to be used however you like it — if you want to execute a function based on the cursor’s position, you’ll probably need an if statement. If you want to reveal the cursor’s coordinates to your users, you might want a click event (or some sort of trigger event) and code that will make the data available to the user (perhaps an alert box). The possibilities are endless.

Handy jQuery Code Snippets for Textboxes

Code snippets are great time savers as these are essentially just reusable pieces of code. Implementing client side validations can be done using jQuery, as well as some other basic tasks like clearing value or enabling and disabling textboxes. This post provides a list of useful jQuery code snippets for handling textbox related tasks with ease. These snippets are useful for validation, clearing out values on key stroke, copying one textbox value to another in real time and several other tasks. Check it out!

1. Clear input textbox value using ESC key

The ESC key is mainly used for cancelling your current process, closing popups, or clearing out input. If you wish to implement textbox value clearing when the ESC key is pressed, then following jQuery code will help you achieve this. It checks for the ASCII code of the key and if it matches with the ASCII code of the ESC key, then it simply clears the value of the textbox in focus. Like this:

$(document).ready(function() {
    $('input[type="text"]').keyup(function(e){
        if(e.keyCode == 27) {
            $(this).val('');
        }
    });
});​

2. Clear input textbox on page load

Following jQuery code will clear all the input-type textboxes, when DOM is ready. It loops through all the textboxes present on the page and within the loop, clearing its value.

$(document).ready(function() {
    $('input[type=text]').each(function() {
        $(this).val('');
});
});​

If you want to clear the value of the event in focus, then use the following jQuery code:

$('input[type=text]').focus(function() {
      $(this).val('');
   });

3. Allow only numbers in textbox

As part of some form validations, there may be a restriction that only allows numbers in the textboxes. For example, when the value represents age, price, number of days, etc. The following jQuery code will allow only numbers in the textbox with ID “txtNumber”. It uses the keydown event to detect the user input value’s ASCII code. In this case the ASCII code must be in a range of numbers. The following code allows keys like backspace for clearing the value and TAB keys for moving out of the textbox:

$(document).ready(function(){
   $("#txtNumber").keydown(function(e)
   {
       if (e.shiftKey)
           e.preventDefault();
       else
       {
           var nKeyCode = e.keyCode;
           if (nKeyCode == 8 || nKeyCode == 9) //Ignore Backspace and Tab
               return;
           if (nKeyCode < 95)
           {
               if (nKeyCode < 48 || nKeyCode > 57)
                   e.preventDefault();
           }
           else
           {
               if (nKeyCode < 96 || nKeyCode > 105)
                 e.preventDefault();
           }
       }
   });
});
4. Disable Cut, Copy and Paste operation

The following jQuery code will disable ‘cut’, ‘copy’ and ‘paste’ operations on the input text boxes. Using the jQuery .on() method, the ‘cut’, ‘copy’ and ‘paste’ events are attached to all input text boxes and the code will prevent the default behavior, like this:

$(document).ready(function(){
  $('input[type="text"]').on("cut copy paste",function(e) {
      e.preventDefault();
  });
});

5. Set focus on the first textbox of the page

The following code will set the focus to the very first enabled input textbox on the page, when the page is originally loaded:

$(document).ready(function(){
   $('input[type=text]:enabled:first').focus();
});

But if the very first textbox is not visible, for example if it is set to “display:none;” then the above code will fail. So the best solution is to check for visible and enabled textboxes and then set the focus. Like this:

$(document).ready(function(){
   $('input[type=text]:visible:enabled:first').focus();
});

6. Turn off autocomplete for all textboxes

These days most modern browsers cache every single input and smartly houses a list based on the input, like a list of email addresses for an email address inbox. When you visit any website, the browsers will display a list of all previously used inputs. When this is not necessary for your work, it can be quite frustrating. If you wish to disable autocomplete for all textboxes present on the page, the following jQuery code will help:

$(document).ready(function(){
  $('input[type="text"]').attr("autocomplete", "off");
})

Though you can set the autocomplete=”off” attribute on textboxes, you will have to set it for all the text boxes and that takes time. Instead, use the single line of jQuery code and you can achieve the same for all the text boxes present on the page at once!

7. Copy value from one textbox to another while typing

If you wish to copy the content of one input textbox to another in real time, the following jQuery code will do the job. This jQuery code attaches a keyup event to the source and then assigns its value to the destination textbox:

$(document).ready(function() {
    $('#txtSource').keyup(function(e) {
        $('#txtDestination').val($(this).val());
    });
});

The above code will copy the text from one textbox to another. But if you wish to sync multiple textboxes then assign a CSS class to every textbox which should be part of syncing and then bind the keyup event to the CSS class selector. The HTML code will look something like this:

<input type="text" id="txt1"/>
<input type="text" id="txt2" />

Below is the jQuery code that binds the event to copyText and assigns the same value to all the elements that have copyText CSS class:

$(document).ready(function() {
    $('.copyText').keyup(function(e) {
        $('.copyText').val($(this).val());
    });
});

8. Convert textbox value to uppercase

The following jQuery code will convert the textbox’s value to uppercase lettering when the focus goes out of the textbox. toUpperCase() is a JavaScript method which converts the string to upper case letters:

$(document).ready(function() {
    $('#txtSource').blur(function(e) {
        $(this).val($(this).val().toUpperCase());
    });
});

You can also set to lower case using the toLowerCase() method. Like this:

$(this).val($(this).val().toLowerCase());

9. Change textbox width on focus and restore on focus out

The following jQuery code will change the textbox width to 350px and then restore again to 200px when the focus goes out. This code makes use of the jQuery animate method, which provides simple animation while changing width:

$(document).ready(function() {
  $('#txtValue').focus(function() {
    $(this).animate({ width: '300px'}, 'fast');
  });
  $('#txtValue').blur(function() {
    $(this).animate({ width: '200px'}, 'fast');
  });
});

Using the animate() method, duration can be assessed. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The default duration is 400 milliseconds. The strings ‘fast’ and ‘slow’ can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

10. Disable all textboxes

The following jQuery code will disable all the textboxes present on the page by setting the “disabled” property to true:

$(document).ready(function() {
    $('input[type="text"]').prop("disabled", true);
});

If there are multiple forms on your page and you wish to disable textboxes of a particular form, then all you need to do is supply the form Id to jQuery selector. Like this:

$(document).ready(function() {
    $('#frm1 input[type="text"]').prop("disabled", true);
});

In this case, all the input textboxes for “frm1” will be disabled.

 

To sum up, these jQuery code snippets for input textboxes are handy when implementing validations, disabling and enabling, setting focus for providing a better user experience and, from a security point of view, to disable copying. These tiny snippets can save you valuable minutes, and allow you to complete tasks with ease!

How to Refresh One Section of a Page

There are plenty of times where you might want to refresh only part of your page’s content, leaving the static content to be, well, static, and refreshed at the user’s discretion. Reloading an entire page on a user can be jarring, confusing, and doesn’t make for a great user experience. However, if your page features timely news stories or breaking news, featured content that is updated often, or even promotional or dynamic content that you’d like to reload to give your users more opportunities to see everything you’ve got to offer, refreshing just these particular areas of a page is a good option. This way, you can make sure your targeted content is updated, without alienating any users.

If you’d like to reload just a section (or a few sections) of a page, you can do so relatively easily and simply with jQuery. Check out the lightweight snippet below to easily add this functionality to any of your projects:

setInterval(function() {
$("#reloadContent").load(location.href+" #reloadContent>*","");
}, 200000);

As you can see, in the example above, we’re choosing to refresh the #reloadContent element. If you’d like to refresh an element with a different class or ID (note: it’s probably wise to only refresh elements using their IDs, rather than classes, so you don’t accidentally end up refreshing several different elements at once),  you can simply replace the #reloadContent with the name of your chosen element. You can then use the second parameter of the function (in the example above, 200000) to set the amount of milliseconds that should pass in between the initial page load and when you want your content and elements to refresh. Remember — the time interval is in milliseconds, so be sure to keep that in mind when setting your refresh time, so it doesn’t end up refreshing too often.

Use this snippet as many times as you’d like in your code to refresh several different elements at different time intervals.