Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Saturday, 25 February 2017

How To Implement Search Using JavaScript Function

Last week I was working on a report and the need was to have search field from where user can search the product names out of hundreds of products. I then searched on Google a lot, there were some JQuery plugins coming up that fulfill the requirements but I don’t want to use any JQuery plugin because when we add JQuery files on page it increases the size of the page so I need a small & light function to do the job. After so much searching in Google I found a function in JavaScript that did an awesome job. I thought to share it with all of you as it is very helpful.

Let’s try to understand with the help of an example. I’ve made a table with id=”example” inside a div and place a text box with id=”txtSearch”. I’ve written a searchFunction on keyup event on this text box and passed table id i.e. ‘example’ in my case as second parameter and ‘0’ as third parameter. ‘0’ is cell index on which you want to implement search. So in this case search function will work on first cell.

<div style="font-size: 14px; padding: 15px;">
       <input type="text" id="txtSearch" onkeyup="searchFunction(this,'example',0);" />
            <table id="example" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        <th style="text-align: left">Name</th>
                        <th style="text-align: left">Position</th>
                        <th style="text-align: left">Office</th>
                        <th style="text-align: left">Age</th>
                        <th style="text-align: left">Start date</th>
                        <th style="text-align: left">Salary</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Tiger Nixon</td>
                        <td>System Architect</td>
                        <td>Edinburgh</td>
                        <td>61</td>
                        <td>2011/04/25</td>
                        <td>$320,800</td>
                    </tr>
                    <tr>
                        <td>Garrett Winters</td>
                        <td>Accountant</td>
                        <td>Tokyo</td>
                        <td>63</td>
                        <td>2011/07/25</td>
                        <td>$170,750</td>
                    </tr>
                    <tr>
                        <td>Ashton Cox</td>
                        <td>Junior Technical Author</td>
                        <td>San Francisco</td>
                        <td>66</td>
                        <td>2009/01/12</td>
                        <td>$86,000</td>
                    </tr>
                    <tr>
                        <td>Cedric Kelly</td>
                        <td>Senior Javascript Developer</td>
                        <td>Edinburgh</td>
                        <td>22</td>
                        <td>2012/03/29</td>
                        <td>$433,060</td>
                    </tr>                                     

                </tbody>
            </table>

        </div>


The search function is getting the string written in search text box as first parameter, _id of the table as second parameter and table cell ‘cellNr’ (on which you want to implement search filter) as third parameter. It gets the search string and loop on the table rows and in the loop JavaScript indexOf function is used to check whether the searching string exist in the first cell of the table or not. If it is not in the row set its display property to none and if it is there just set its display property to empty/blank to show it.

      function searchFunction(term, _id, cellNr) {
            var searchString = term.value.toLowerCase();
            var table = document.getElementById(_id);
            var ele;
            for (var r = 1; r < table.rows.length; r++) {
                ele = table.rows[r].cells[cellNr].innerHTML.replace(/<[^>]+>/g, "");
                if (ele.toLowerCase().indexOf(searchString) >= 0)
                    table.rows[r].style.display = '';
                else table.rows[r].style.display = 'none';
           }
     }


Sunday, 17 May 2015

How To Check or Uncheck All Check Boxes Using JavaScript | Jquery

In this tutorial I will show you how to check and uncheck all checkboxes using javascript. I was assigned this task so I decided to write a tutorial on it.

Scenario:-


Let’s start with a scenario where we have a gridview in which there is a column Enable/Select All Option (checkbox to check all options). When select all checkbox in header row is checked all checkboxes in the gridview under the same column should be checked and when user uncheck select all checkbox in the header row all the checkboxes in the same column of the gridview should be unchecked.



Header Row Checkbox HTML:-


<asp:CheckBox ID="chb_SelectAll" Text="Select All" runat="server" Enabled="true" AutoPostBack="false" Style="font-size:11px;" onclick="CheckAll(this);"/>

Javascript Function:-


  function CheckAll(Checkbox) {
            // By using the gridview id = GridView1
            var GridVwObj = document.getElementById("<%=GridView1.ClientID %>"); 
            // Using for loop on gridview object. started loop from i=1 because we need to skip header row.
            for (i = 1; i < GridVwObj.rows.length; i++) {
            // Cells[0] shows that checkboxes are in first column so you can give any column where you have checkboxes i.e cells[1],celss[2]...etc.              
                GridVwObj.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = Checkbox.checked;  
            }
        }

Note:- I have used GridView having ID = GridView1, if you are using simple html table having id = table1 then you need to replace this document.getElementById("table1"); line in above function and you are good to go.

Jquery Function:-



By using jquery first we need to give a class attribute to every checkbox in the table. E.g. I have used .checkboxClass in this case

Method 1:-



function CheckAll(ref) {
            
            if ($(ref).checked) {
                $('.checkboxClass').each(function () { //loop through each checkbox
                    this.checked = true;  //select all checkboxes with class "checkboxClass"              
                });
            } else {
                $('.checkboxClass').each(function () { //loop through each checkbox
                    this.checked = false; //deselect all checkboxes with class "checkboxClass"                      
                });
            }
        }

Method 2:-



$('input[id$=chb_SelectAll]').click(function (event) {  //on click
            // this will represent chb_SelectAll check select status
            if (this.checked) {
                $('.checkboxClass').each(function () { //loop through each checkbox
                    this.checked = true;  //select all checkboxes with class "checkboxClass"              
                });
            } else {
                $('.checkboxClass').each(function () { //loop through each checkbox
                    this.checked = false; //deselect all checkboxes with class "checkboxClass"                      
                });
            }
        });

Friday, 3 May 2013

Difference Between e.preventDefault () And Return False

In this tutorial we are going to discuss the difference between e.preventDefault () and return false as lot of people doesn’t know the difference between them.

e.preventDefault ():- Prevents the default action of event from happening/triggering but do not stop the propagation of event to parent elements.

return false :- Prevents the default action of event from happening/triggering as well as stop the event propagation.

Now the question arise in everyone's mind is what is event propagation? I will explain it in my next tutorial very soon.

Ok, let's try to understand e.preventDefault() and return false with the help of examples.

Example 1:-

This is a simple example.Let's suppose we have a div and there is an anchor tag inside it like this.

<div id="someID" onclick="executeParentFunction()">
        <a href="http://aspsqltutorials.blogspot.com">Click here to visit my blog</a>
 </div> 


And script tag like this:

<script type="text/javascript">

 $("a").click(function (e) {

 $("a").text("Click Event is going to happen");  // this line will change the hyperlink text

  });

  function executeParentFunction() {

            alert("First Comes Here");
        }
    </script>

Now when we execute above code and click on the anchor tag link first we will get alert("First Comes Here") as the parent div calls function executeParentFunction() then after that we will see that hyperlink text "Click here to visit my blog" will be replaced by text "Click Event is going to happen" and then you will be redirected to my blog.

Example 2:-

This is a simple example. Let's suppose we have a div and there is an anchor tag inside it like this.

<div id="someID" onclick="executeParentFunction()">
        <a href="http://aspsqltutorials.blogspot.com">Click here to visit my blog</a>
 </div> 


And script tag like this:

<script type="text/javascript">

       $("a").click(function(e){         
              e.preventDefault();         // this line prevents the default action       
              $("a").text("Click Event is going to happen");  // this line will change the hyperlink text
       });

       function executeParentFunction(){
              
              alert("First Comes Here");
       
       }
    </script>

so when we execute example 2 we will first get the javascript alert("First Comes Here") as usual after that hyperlink text "Click here to visit my blog" will be replaced by text "Click Event is going to happen" but you will not redirected to my blog in this case because we use e.preventDefault to stop the default click action to be triggerd.

Example 3:-

In this example we use return false, after executing this final example you will surely know the difference.

<div id="someID" onclick="executeParentFunction()">
        <a href="http://aspsqltutorials.blogspot.com">Click here to visit my blog</a>
 </div> 
<script type="text/javascript">

       $("a").click(function (e) {

           $("a").text("Click Event is going to happen");  // this line will change the hyperlink text
           return false;
       });

       function executeParentFunction() {

           alert("First Comes Here");

       }

</script>

Here when we will execute the code of example 3 and we'll see that function excuteParentFunction () will not be called and we will not get any alert (). This is because we use return false here which stop the default action from happening as well as the event propagation. Also this time hyperlink text "Click here to visit my blog" will be replaced by text "Click Event is going to happen" but you will not be redirected to my blog.
Try and execute these examples to see the difference and how they work.

Hope this post will be helpful for you.

Monday, 22 April 2013

How To Stop Default Action From Happening Using Jquery

In this tutorail we will learn about how to stop the default action of an element from happening and for this purpose we will use jquery method event.preventDefault().

Example :-

Below example will show you how we can prevent a link to follow the URL. So when you click on the link it will not go to google.com rather it will give you an alert.


<!DOCTYPE html>

<html>

<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">

</script>

<script>

$(document).ready(function(){

  $("a").click(function(event){

    event.preventDefault();

    alert("Hello World");

  });

});

</script>

</head>

<body>


<a href="http://google.com/">Go to Google</a>


</body>

</html>

Thursday, 11 April 2013

How To Get Specific Row ID In Dynamic Table Using Jquery

Today we will learn how to find/pick id of a row when tables are dynamic. I will explain it to you with the help of an example.

Example:-


I have generated a simple dynamic table with the help of for loop. Every row in a table has dynamic id e.g. Row0, Row1, Row3… and we need to find the id of the row when user clicks on any specific row. Normally you need id of the row when you want to perform some operation like edit/modify or delete.
I have used live () function here to pick row id of dynamic table. live () function simply attach an event with the selector. However in Jquery version 1.7 it is deprecated and in 1.9 it is removed. There are other function like delegate () and on () which you can use to attach event handlers.
This is the jquery code I have used to pick the id.

// ------------- Pick row id of the dynamic Table

        var tableRow = $("#tbl_Dynamic").find('tr');
        tableRow.live('click', function (e) {
            alert($(this).attr('id'));
        });
//-----------------end here--------------------------

Below mentioned is the full code example of simple dynamic table generation and pick the row id of a dynamic table.

<html>
<head>
<title>Getting Row Id of a Dynamic Table</title>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>

  <body>
       <div id="tableDiv" ></div>

</body>
    
    <script type="text/javascript" language="javascript">

// ------------- Pick row id of the dynamic Table

        var tableRow = $("#tbl_Dynamic").find('tr');
        tableRow.live('click', function (e) {
            alert($(this).attr('id'));
        });
//-----------------end here--------------------------
         
 $(document).ready(function () {
            dynamicTable();
 });

function dynamicTable(){
       
var table="";
var arrName = 
['Amir', 'Zeeshan', 'Kalim', 'Yasir', 'Zafar', 'Adeel', 'Majid', 'Pravin'];
var arrDept = 
['IT', 'HR', 'Finance', 'Marketing', 'Billing', 'IT', 'Web', 'Finance'];

table+="<table id='tbl_Dynamic' style='text-align:center;'>";
table+="<thead>";
table+="<tr><th>Serial #</th>";
table+="<th>Name</th>";
table+="<th>Department</th>";
              table+="</thead><tbody>";

              for (var i = 0; i < 8; i++) {

                  table += "<tr id='Row"+i+"'>";
                  table += "<td>" + i + " </td>";
                  table += "<td>" + arrName[i] + "</td>";
                  table += "<td >"+arrDept[i]+"</td>";
                  
                  table += "</tr>";

              }
                     table+="</tbody></table>";
                     $("#tableDiv").html(table);
}

</script>
</html>


jquery-example-one
jquery-example-one

Wednesday, 10 April 2013

Find Row Id Of Specific Row In Static Table Using Jquery

This tutorial explain you how to find id of a row when user clicks on a specific row in a table. Normally we need to get the row id to perform specific operation on a table row. And for beginners or new learner of jquery it is difficult to get row id of a table so I decided to write this two tutorial series to explain how to get row id especially when we are making dynamic tables.

Static Example:-
In the example we have a table having id=”tbl_Example” and Five rows. Every row has a specific id. e.g.

<table id="tbl_Example" border="1" >
        <tr id="Row0">
            <th>
                Serial Number</th>
            <th>
                Name</th>
        </tr>
        <tr id="Row1">
            <td>
                1</td>
            <td>
                Anwar</td>
        </tr>
        <tr id="Row2">
            <td>
                2</td>
            <td>
                Aslam</td>
        </tr>
        <tr id="Row3">
            <td>
                3</td>
            <td>
                Hammad</td>
        </tr>
        <tr id="Row4">
            <td>
                4</td>
            <td>
                Zahid</td>
        </tr>
        <tr id="Row5">
            <td>
                5</td>
            <td>
                Ashfaq</td>
        </tr >        
    </table>

   <script  type="text/javascript">

        $(document).ready(function () {
            $("#tbl_Example tr").click(function () {
                alert($(this).closest('tr').attr('id'));
            });

        });
    </script>

Note:- See my next tutorial on how to get row id of dynamic table when user click on specific row.

Calculating Minimum Y-Axis Value | Dynamic Y-Axis | Highcharts

Couple of weeks ago when I was working on a project in office where we need to show graphical representation of data so we use high-chart library which is one of the top 10 in graphic representation.
Now the reason behind the decision to write this post is the difference I have found between the below two figures of high-chart graph.

I have given a static example  here however you can use Jquery Ajax() to get your data from database on client-side and then draw high-chart graphs. If somebody finds it difficult then do post me and i will write another tutorial on how to draw high-chart graph dynamically after picking data from database.
 
I will explain the difference between the below two figures but first I want to tell you that I have written the same code and data (data: [400, 405, 395]) for the two charts (Figure 1 is the “Column Graph” and Figure 2 is “Line Graph”). Only the small difference is that for column graph you need to write defaulteSeriesType: ‘column’ and for line graph defaultSeriesType:’line’ and below is the code.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Calculating Y-Axis scale dynamically in highchart</title>
    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="Scripts/highcharts.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">   
    <div id="container" style="margin:auto auto;height:300px;width:400px;"></div>   
    </form>

 <script type="text/javascript">

     var chart = new Highcharts.Chart({

         chart: {
             renderTo: 'container',
             defaultSeriesType: 'column'
         },
         xAxis: {
             title: {
                 text: 'X-Axis Values'
             }

         },
         yAxis: {
             title: {
             text:'Y-Axis Values'
             }
         },
         series: [{
             data: [400, 405, 395]
         }]

     });
    </script>
</body>

</html> 
                  Figure 1                                               Figure 2
Fig. 1               Fig. 2

Have a look at the Y-Axis scale of both figures even that I draw two graphs with same data array (data: [400, 405, 395]) but “Column” graph start the y-scale from 0 and “Line” graph starts it from 390. At  first glance of column graph you find no difference between the three columns until unless you mouse over the column and see the value in the tool tip. On the contrary, line graph shows the difference of values in the first glance even without tool tip so the end users very easily identify the performance from line graph.

The problem is that Y-Axis on column graph is not dynamic but for line graph it is dynamic so we need to make dynamic Y-Axis on column graph. The first solution of this problem in my mind was find the maximum and minimum values of your data and assign the min. value of your data to min. value of y-axis scale and then a bit of searching on Google also works it for me when I find the example as well.
Here is the link as well from where I found this formula and bit of explanation as well: http://stackoverflow.com/questions/10222613/calculating-a-min-y-axis-value-in-highcharts

Formula for dynamic Y-Axis Scale in highchart Column Graph: -   min = min-((max-min)*0.05)
Note: - The above has been derived from highchart Line Graph.

By applying this formula in your code you will find the difference. I am giving you the code and figures as well.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Calculating Y-Axis scale dynamically in highchart</title>
    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="Scripts/highcharts.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="container" style="margin: auto auto; height: 300px; width: 400px;">
    </div>
    </form>
    <script type="text/javascript">

        var data = [400, 405, 395];

        Array.max = function (array) {
            return Math.max.apply(Math, array);
        };
        Array.min = function (array) {
            return Math.min.apply(Math, array);
        };

        var min = Array.min(data);
        var max = Array.max(data);

        var chart = new Highcharts.Chart({

            chart: {
                renderTo: 'container',
                defaultSeriesType: 'column'
            },
            yAxis: {
                min: min - ((max - min) * 0.05)
            },
            series: [{
                data: data
            }]

        });

    </script>
</body>
</html>