How to change the value of a check box onClick using JQuery?

With this code, you can change the value of the check box to 1 when it is checked, or to 0 when it is unchecked:

The HTML:

<input type="checkbox" id="read" onClick="" />
  1. You should do this:
    onclick="$(this).attr('value', this.checked ? 1 : 0)"
  2. Or even:
    onclick="$(this).val(this.checked ? 1 : 0)"
Advertisement

How to create simple alert or confirm messages with SimpleModal JavaScript plugin

Overview:

SIMPLEMODAL is a small plugin to create modal windows. It can be used to generate alert or confirm messages with few lines of code. Confirm configuration involves the use of callbacks to be applied to affirmative action; it can work in asynchronous mode and retrieve content from external pages or getting the inline content.

How to use:

SIMPLEMODAL is very simple to use; here are 4 ways to create SIMPLEMODAL: simple alert message, modal window, modal window with a single asynchronous call and lightbox.

simpleModal

Reference link: http://simplemodal.plasm.it/

Also you can use these other modals pop up:

BOOTBOX.js

Reference link: http://bootboxjs.com/examples.html

Pop Easy

Reference link: http://thomasgrauer.com/popeasy/

Use “id” or “name” attribute in HTML component with jQuery

Sometimes we need to use “id” or  “name” attribute in our html components. I would like to show the difference between them through jQuery:

The HMTL

<input type="text" name="_inputName" id="_inputId" ></input>
<select type="text" name="_selectName" id="_selectId" ></select>
  1. Use “id” attribute with jQuery:
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
    <script type="text/javascript"> 
    $(document).ready(function(){ 
    $('#_inputId').attr('disabled', true);
    $('#_selectId').attr('disabled', true);
    }); </script>
  2. Use “name” attribute with jQuery:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
    <script type="text/javascript"> 
    $(document).ready(function(){ 
    $('input[name="_inputName"]').attr('disabled', true);
    $('select[name="_selectName"]').attr('disabled', true);
    }); 
    </script>

“Show and Hide Html components with jQuery” vs “visible and hidden Html componets with JavaScript”

Sometimes we need to show or hide html components in our html files. I would like to show you several ways to do this through jQuery or JavaScript method:

The HMTL

<div  class="show_hide">
<a href="#">This is a link</a>
</div>
  1. Show and Hide Html components with jQuery:

    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
    <script type="text/javascript"> 
    $(document).ready(function(){ 
    //hide component 
    $(".show_hide").hide(); 
    //show component 
    $(".show_hide").show(); 
    }); 
    </script>
  2. visible and hidden Html componets with JavaScript:

    <script type="text/javascript">
    function displayText(_field, _value){
    document.getElementById(_field).style.display=_value;
    }
    
    function visibilityText(_field, _value){
    document.getElementById(_field).style.visibility=_value;
    }
    
    //hide component
    visibilityText('show_hide', 'hidden');
    displayText('show_hide', 'none');
    
    //show component
    visibilityText('show_hide', 'visible');
    displayText('show_hide', 'block');
    
    </script>

Set Focus to the Next Input Field with jQuery

Setting focus to input fields is easy enough with JavaScript: document.getElementById(‘theInputField’).focus(); but sometimes you need a more generic solution as what happens when the next input field changes ID?

There are some options to do it, we want to show you some of them:

  1. I was recently faced with the problem of setting focus to the next input field. The challenge was that I didn’t know what that field was. So given an input field, find the next logical (in the order of the DOM) input field and set focus. I came up with the following jQuery function (plugin) to accomplish this:
    $.fn.focusNextInputField = function() {
        return this.each(function() {
            var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select');
            var index = fields.index( this );
            if ( index > -1 && ( index + 1 ) < fields.length ) {
                fields.eq( index + 1 ).focus();
            }
            return false;
        });
    };
    

    Reference link: http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/

  2. Another option is with tabindex attribute:
    
    var tabindex = 1; //start tabindex || 150 is last tabindex
    $(document).keypress(function(event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '9' || keycode == '13') { //onEnter
    tabindex++;
    //while element exist or it's readonly and tabindex not reached max do
    while(($("[TabIndex='"+tabindex+"']").length == 0 || $("[TabIndex='"+tabindex+"']:not([readonly])").length == 0) && tabindex != 150 ){
    tabindex++;
    }
    if(tabindex == 150){ tabindex = 1 } //reseting tabindex if finished
    $("[TabIndex='"+tabindex+"']").focus()
    return false;
    }
    });
    
    $("input").click(function() { //if changing field manualy with click - reset tabindex
    var input = $(this);
    tabindex = input.attr("tabindex");
    });
  3. Another option:
    $("input,select").bind("keydown", function (e) {
    if (e.keyCode == 13) {
    var allInputs = $("input,select");
    for (var i = 0; i < allInputs.length; i++) {
    if (allInputs[i] == this) {
    while ((allInputs[i]).name == (allInputs[i + 1]).name) {
    i++;
    }
    
    if ((i + 1) < allInputs.length){
    $(allInputs[i + 1]).focus();
    }
    }
    }
    }
  4. How to catch enter key and change event to tab
    $('input').keydown( function(e) {
            var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
            if(key == 13) {
                e.preventDefault();
                var inputs = $(this).closest('form').find(':input:visible');
                inputs.eq( inputs.index(this)+ 1 ).focus();
            }
        });

Callback Functions in JavaScript

What is a Callback Function?

The above-linked Wikipedia article defines it nicely:

A reference to executable code, or a piece of executable code, that is passed as an argument to other code.

Here’s a simple example that’s probably quite familiar to everyone, taken from jQuery:


$('#element').fadeIn('slow', function() {
// callback function
});

This is a call to jQuery’s fadeIn() method. This method accepts two arguments: The speed of the fade-in and an optional callback function. In that function you can put whatever you want.

When the fadeIn() method is completed, then the callback function (if present) will be executed. So, depending on the speed chosen, there could be a noticeable delay before the callback function code is executed.

How to Write a Callback Function

If you’re writing your own functions or methods, then you might come across a need for a callback function. Here’s a very simple example of a custom callback function:


function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
callback();
}

mySandwich('ham', 'cheese', function() {
alert('Finished eating my sandwich.');
});

Continue reading

Difference between document.ready and window.onload or pageLoad

PageLoad() and jQuery’s $(document).ready() events do the same and seem too similar but in different time. $(document).ready() and pageLoad() methods are very much differ in functioning. In this article, I will explain the major differences between $(document).ready() and pageLoad() methods.

  1. Introducing $(document).ready()
    JQuery’s document.ready() method gets called as soon as DOM is ready (means browser has parsed the HTML and built the DOM tree). It is cross browser compatible means behave equally on all browsers. If your web page has large images, it will not wait for loading of images completely. Hence it may called before pageLoad() method. We can have multiple document.ready() methods on a web page that will be called in coming sequence.<script type=”text/javascript”>
    $(document).ready(function(){
    // Gets called as soon as DOM is ready
    //code here
    });
    </script>
  2. Introducing window.onload (pageLoad() )
    pageLoad() method gets called when images and all associated resources of the page have been fully loaded. Suppose your web page has large size images then until all the images are not fully loaded on the page, pageLoad() method will not called. pageLoad() method is not browser compatible. We can have only one pageLoad() method on a web page.<script type=”text/javascript”> function pageLoad()
    {
    // gets called when page have been fully loaded
    //code here
    }
    </script>

Reference link: http://www.dotnet-tricks.com/Tutorial/aspnet/D719120612-Difference-between-document.ready-and-window.onload-or-pageLoad.html

Stack Overflow

Stack Overflow is a question and answer site for professional and enthusiast programmers. It’s built and run by you as part of theStack Exchange network of Q&A sites. With your help, we’re working together to build a library of detailed answers to every question about programming.

apple-touch-icon

Stack Overflow is all about getting answers. It’s not a discussion forum. There’s no chit-chat.

Reference link: http://stackoverflow.com/about

How to reduce the file size of your PNG files

The answer is TinyPNG free service:

TinyPNG uses smart lossy compression techniques to reduce the file size of your PNG files. By selectively decreasing the number of colours in the image, fewer bytes are required to store the data. The effect is nearly invisible but it makes a very large difference in file size!

Difference between images:

Below are two photos of my cousin. The left image is saved as 24-bit PNG directly from Adobe Photoshop. On the right is the same image, processed by TinyPNG. Spot any difference?

difference between images

In the above image the file size is reduced by more than 70%. I have excellent eyesight but can’t spot the difference either! Use the compressed image to save bandwidth and loading time and your website visitors will thank you.

Reference link: http://tinypng.org/

What is jQuery?

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.

Reference link: http://jquery.com/

Continue reading