Amiya Sahu Web Developer

Clear input Field on Focus using JQuery

This piece of code will clear the text input field on focus if the field is not changed by the user.

HTML code

<input type="text" id="username" data-default-value="username" value="username">

JQuery code

jQuery(document).ready(function ($) {
    var $field = $('#username'), 
        defaultValue = $field.data('default-value');
    $field.on('focus', function (event) {
        var $this = $(this);
        if ($this.val().trim() === defaultValue) $this.val('');
    });
    $field.on('focusout', function (event) {
        var $this = $(this);
        if ($this.val().trim() === '') $this.val(defaultValue);
    });
});

Here is a live example.

How to get checked radio button value in JQuery

This piece of code will help in getting the selected radio value.

$("input[name=my-radio]:checked").val();

Here is a live example.

Dealing with text nodes in JQuery

How to know if the element is a text node or not

The below method will help you to check if the given element is a text node or not.

function isTextNode(elem){
    // If this is a text node, return true.
    return( elem.nodeType === window.Node.TEXT_NODE );
}

How to get all the text nodes in a particular element.

The below piece of code can help you in getting all the text nodes in a element identified by the selector.

$('selector')
    .contents()
    .filter(function(){
        return this.nodeType === window.Node.TEXT_NODE 
                && $.trim(this.nodeValue) !== '';
    });

How to reset file input type in JQuery

If you want to reset the input type using traditional method will not work . For doing so you wrap() a <form> around the element, call reset() on the newly created form, then remove the form using unwrap()

function resetFileElement(e) {
  e.wrap('<form>').closest('form').get(0).reset();
  e.unwrap();
}

Reference & Live Example

Get Next or Previous record in MySQL

Query to get Next record in MySQL

SELECT * FROM foo WHERE id = (SELECT MIN(id) FROM foo WHERE id > 4)

Query to get Previous record in MySQL

SELECT * FROM foo WHERE id = (SELECT MAX(id) FROM foo WHERE id < 4)

Word count after trimming white spaces in Javascript

The below function can count the number of words in a line by ignoring the white space characters .

function wordCount (str) {
    if(!!str)
        return str.trim().replace(/\s+/gi, ' ').split(' ').length;
    else 
        return 0;
}

//usage 
var str = "Hello There. How is the   weather     today in   India",
count = wordCount();
console.log(count); // 8

Toggle Radio Buttons with jQuery

Are you looking for a piece of code where you need to toggle the radio button values. JQuery provices handful of methods by using which we can acomplish easily. Here you go with step by step approach.

Step 1. HTML Code

Create two checkboxes and by default let one of them be checked. Then create a button which will act as a switch. When we click the button the radio button will toggle.

<label>
	<input type="radio" name="car" value="Honda" checked>Honda
</label>
<label>
	<input type="radio" name="car" value="Benz">Benz
</label>

<button id="toggle_button">Toggle</button>

Step 2. JQuery Code

$('#toggle_button').click(function() {
	$('input[name="car"]')	    //get all checkboxes
		.not(':checked')		   //if it is not checked
		.prop("checked", true);   //make it checked
});

Difference between window.onload and $(document).ready()

The ready event occurs after the HTML document has been loaded (when the document is ready to be manipulated i.e browser has build the DOM tree ), while the onload event occurs later, when all content (e.g. images and other resources) also has been loaded.

The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn’t have to wait for all content to load.

window.onload Syntax

$(window).load(function () {
         console.log("window load complete");
});

window.onload = function () {
         console.log("window load complete");
}

$(document).ready() Syntax

$(document).ready(function () {
          console.log("document is ready.");
});
//short-hand 
$(function(){
    console.log("document is ready.");
});

Get random numebr with in a range in JQuery

To get random number between a range, we can make use of the Math.random() and Math.floor() function.

//returns random number between the min and max range
function getRandomNumber ( min , max ) {
	return  Math.floor(Math.random() * (max-min + 1)) + min ; 
}
//usage 
getRandomNumber(1 , 10) ; //a number between 1 and 10

Get current Mouse pointer coordinates using JQuery

$(document).ready(function() {
	$(document).mousemove(function(e)
	{
		console.log( "X : " + e.pageX );
		console.log( "Y : " + e.pageY );
	});
});