Handy Javascript code segments

The augmentation of Javascript to CSS and HTML is beautiful. While trying out jQuery to create my own tic tac toe game, I realised that there are Javascript/jQuery code segments that could be helpful to me when building web applications.

In this post, I collate Javascript and jQuery code segments that I had utilized in my web projects for ease of future references.

DOM manipulation

Get a jQuery reference for manipulating a DOM element

Suppose we have a html input text field

<input id="nameTextField" name="name" type="text"/>

The following will get a jQuery reference that allow us to act on the input text field.

$nameTextField = $('#nameTextField');

Check whether a DOM element exists

// Get a jQuery reference with id
// as nameTextField
$nameTextField = $('#nameTextField');
// If jQuery contains no results
if ($nameTextField.length == 0) {
    alert('nameTextField does not exists.');
} 
else {
    alert('nameTextField exists.');
} // end if

Hide a DOM element

// Get a jQuery reference to a DOM element with id
// as nameTextField
$nameTextField = $('#nameTextField');
// Hide the DOM element
$nameTextField.hide();

Show a DOM element

// Get a jQuery reference to a DOM element with id
// as nameTextField
$nameTextField = $('#nameTextField');
// Show the DOM element
$nameTextField.show();

Set the HTML contents of a DOM element

// Get a jQuery reference to a DOM element with id
// as firstParagraph
$firstParagraph= $('#firstParagraph');
$firstParagraph.html('New contents');

Add a DOM element as a sibling to another DOM element

// Get a jQuery reference to a DOM element with id
// as nameTextField
$nameTextField = $('#nameTextField');
// Add a paragraph as a sibling right 
// after nameTextField
$nameTextField.after('<p>A paragraph after nameTextField.</p>');

// Add a paragraph as a sibling 
// before nameTextField
$nameTextField.before('<p>A paragraph before nameTextField.</p>');

Remove a DOM element

// Get a jQuery reference with id
// as nameTextField
$nameTextField = $('#nameTextField');
// Remove the DOM element with id as nameTextField
$nameTextField.remove();

Check whether there is a sibling element after a DOM element

// Get a jQuery reference with id
// as nameTextField
$nameTextField = $('#nameTextField');
if ($nameTextField.next().length == 0) {
    alert('There is no sibling element after nameTextField');
}
else {
    alert('There is a sibling element after nameTextField');
} // end if

Check whether there is a sibling element before a DOM element

// Get a jQuery reference with id
// as nameTextField
$nameTextField = $('#nameTextField');
if ($nameTextField.prev().length == 0) {
    alert('There is no sibling element before nameTextField');
}
else {
    alert('There is a sibling element before nameTextField');
} // end if

Add a CSS style class to a DOM element

// Get a jQuery reference with id
// as nameTextField
$nameTextField = $('#nameTextField');
// Add the style class errorField to 
// nameTextField
$nameTextField.addClass('errorField');

Remove a CSS style class from a DOM element

// Get a jQuery reference with id
// as nameTextField
$nameTextField = $('#nameTextField');
// Remove the style class errorField to 
// nameTextField
$nameTextField.removeClass('errorField');

Detect clicks on a DOM element

// Get a jQuery reference with id
// as nameTextField
$nameTextField = $('#nameTextField');
// Add a function callback to the click
// event for nameTextField
$nameTextField.click(
    function(event) {
        alert('You had clicked on nameTextField.');
    } // end function(event)
);

Detect form submission

$contactMeForm = $('#contactMeForm');
$contactMeForm.submit(
    function(event) {
        alert('Form had been submitted');
    } // end function
);

Returning a false value inside the callback function can prevent the form from submitting the input contents to the server end. This is useful for form validation.

Field inputs and string value checking

Get value of input text fields

// Get a jQuery reference with id
// as nameTextField
$nameTextField = $('#nameTextField');
name = $nameTextField.val();

Check whether a checkbox is checked

// Get a jQuery reference with id as 
// milkOptionCheckbox
$milkOptionCheckBox = $('#milkOptionCheckbox');
if ($milkOptionCheckBox.is(':checked')) {
    alert('You have indicated that you like to drink milk.');
}
else {
    alert('You have indicated that you do not like to drink milk.');
} // end if

Get the length of a string

str = 'Hello there!';
alert('Length of str: ' + str.length);

Remove leading and trailing whitespaces

value = '   some value.  ';
trimmedValue = $.trim(value);

Check whether a string value contains only numbers

numberRegEx = /^[0-9]+$/;
value = '$1234567';

// If value contains only numbers
if (numberRegEx.test(value)) {
	alert('Value contains only numbers');
}
else  {
	alert('Value contains other non-numeric characters');
} // end if (numberRegEx.test(value))

Because of the dollar sign ($) in the value variable, the example code will display a dialog box with the message "Value contains other non-numeric characters".

Note the importance of the ^ and $ characters in numberRegEx. They specify that the regular expression matching spans from the start to the end of the test value. The + character indicates that there should be at least 1 number.

Without these two characters, the example code will display a dialog box with the message "Value contains only numbers".

Check whether a string value contains specific number of numbers

sevenNumbersAfterSixRegEx = /^[6][0-9]{7}$/;
value = '12345678';

if (sevenNumbersAfterSixRegEx.test(value)) {
    alert('Value contains a 6 followed by exactly 7 other digits.');
}
else {
    alert('Value is not of the format that we desire.');
} // end if

Because the number contained in value does not start with a 6, the example code will display a dialog box with the message "Value is not of the format that we desire.".

As with the previous example, the ^ and $ characters specify that the regular expression matching spans from the start to the end of the test value.

Within the ^ and $ characters, the matching consists of two main parts.

  1. [6] matches the number 6.
  2. [0-9]{7} matches any digit from 0 to 9, appearing for exactly 7 times.

Check whether a string value contains a decimal value to 2 decimal places and less than 100

decimalsLessThan100RegEx = /^([0-9]{1,2}\.)?[0-9]{1,2}$/;
value = '56.78';

if (decimalsLessThan100RegEx.test(value)) {
    alert('Value contains a decimal value to 2 decimal places and less than 100.');
}
else {
    alert('Value is not of the format that we desire.');
} // end if

Check whether a string value contains only words and spaces

onlyWordsAndSpacesRegEx = /^[a-zA-Z\s]+$/;
value = "I contain some signs";
if (onlyWordsAndSpacesRegEx.test(value)) {
	alert('Value contains only words and spaces.');
}
else {
	alert('Value contains other unwanted characters.');
} // end if

Check whether email is valid


emailRegEx = /^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$/;
value = 'techcoil@example.com';

if (emailRegEx.test(value)) {
    alert('Email is in a valid form.');
} 
else {
    alert('Email is not in a valid form.');
} // end 

Regular expression pattern taken from mkyong.com.

Related posts

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.