Learning Horizon | For Learners

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

Showing posts with label Jquery Tips. Show all posts
Showing posts with label Jquery Tips. Show all posts

Sunday, 29 December 2019

Cannot Bind Multiple Parameters To Request Content | WebApi

I was working on one of my projects last week and stuck in a problem. I was trying to pass a class object and List of a class object to the Asp.Net Web API controller from my Jquery Ajax method (maybe you also encounter it while working with Angular and ASP.NET MVC or any other technology). After some research, I got to know that the Web API controller can’t accept multiple complex objects, so we must send it as a single object. Let me illustrate with my example and its resolution.

Jquery Code : -



  var SaleModel = new Object();  
       SaleModel.id = “1”;  // for example
       SaleModel.customer_id = $("#ddlCustomer").val(); 
   
  var SaleDetailModel = new Object();
    SaleDetailModel.id = “1”;
    SaleDetailModel.quantity = “10”;
  var lstSaleDetail = [];   // javascript array
    lstSaleDetail.push(SaleDetailModel);

 $.ajax({
      type: 'POST',
      data: 
      "{'obj': '"+JSON.stringify(SaleModel) + "',
      'lstSaleDetail':  '"+JSON.stringify(lstSaleDetail)+ "' }",
      headers: {
                 'Authorization': 'Bearer ' + authData.token
             },
      url: 'http://localhost:53807/api/sale/addsale',
      dataType: 'json',
      contentType: 'application/json',
      success: function (data) {
                if (data == true) {
                    alert("Sale Added Successfully!!!");
                }
            },
      error: function (xhr) {
                alert(xhr.responseText);
          }
  });

C# Code : -



       public class SaleModel
       {
          public int id {get;set;}
          public int customer_id {get;set;}
       }

       public class SaleDetailModel
       {
         public int id {get;set;}
         public int quantity {get;set;}
       }

       [HttpPost]
       public bool AddSale(SaleModel obj, List<SaleDetailModel> lstSaleDetail)
       {            
          SaleBusService objSale = new SaleBusService();
          return objSale.saveSale(obj, lstSaleDetail);           
       }

Solution : -

To fix the problem, we need to pass it as a single object that requires a modification in the above code. Below is the C# code. I have added the List Object of the SaleDetailModel class to the SaleModel Class as per my needs. You can create a new request class that contains both SaleModel and SaleDetailModel Objects.

C# Code :


public class SaleModel
{
   public int id {get;set;}
   public int customer_id {get;set;}
   // I have added the list here
   public List<SaleDetailModel> lstSaleDetail {get;set;} 
}

public class SaleDetailModel
{
   public int id {get;set;}
   public int quantity {get;set;}
}


[HttpPost]
public bool AddSale(SaleModel obj)
 {            
      SaleBusService objSale = new SaleBusService();
      return objSale.saveSale(obj, obj.lstSaleDetail);           
 }

Jquery Code :


var SaleModel = new Object();  
       SaleModel.id = “1”;  // for example
SaleModel.customer_id = $("#ddlCustomer").val(); 
   
var SaleDetailModel = new Object();
    SaleDetailModel.id = “1”;
    SaleDetailModel.quantity = “10”;
var lstSaleDetail = [];   // javascript array
lstSaleDetail.push(SaleDetailModel);

 $.ajax({
            type: 'POST',
     data: JSON.stringify(SaleModel) ,
            headers: {
                 'Authorization': 'Bearer ' + authData.token
             },
            url: 'http://localhost:53807/api/sale/addsale',
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {
                if (data == true) {
                    alert("Sale Added Successfully!!!");
                }
            },
            error: function (xhr) {
                alert(xhr.responseText);
            }
        });

Friday, 4 September 2015

Apply Different Colors On Alternate Table Rows Using Jquery

In this tutorial I will show you how to apply two different colors on alternate rows of HTML table using JQuery. So let's start and create a simple table

<table border="1">
           
                <tr><td>John Doe</td></tr>
                <tr><td>Steve Waugh</td></tr>
                <tr><td>Wasim Akram</td></tr>
                <tr><td>Ricky Ponting</td></tr>
                <tr><td>Shahid Afridi</td></tr>          

        </table>

Now in ready function of JQuery we have to write like this:

Method 1:-

$(document).ready(function () {

            $("tr:even").css("background-color", "#ececec");  // silver grey color
            $("tr:odd").css("background-color", "#ffffff");  // white color

        });

or you can make a CSS class and then use addClass() function of JQuery

Method 2:-

$(document).ready(function () {

            $("tr:even").addClass('hor-minimalist-c');
            $("tr:odd").addClass('hor-minimalist-d');

        });

Hope you understand. Have a good day.

What Is Chaining In Jquery?

jQuery is an exceptionally incredible framework of JavaScript. With jQuery, we can utilize chaining which intends to chain together different methods in a solitary statement on a single element.

We have been using a solitary statement at once, but now utilizing the chain technique we can bind multiple methods to shorten the code. This way, browsers do not have to look for the same element(s) multiple times.

Advantage of Jquery Method Chaining:

When using chaining technique in jQuery, it means to connect multiple functions to same element/selectors or it allow us to run multiple JQuery functions/commands on same element(s)/selector(s).

Excessive use of selectors will severely slow down your code, because each call to the selector will force the browser to look for it. By combining or "linking" multiple methods, you can greatly reduce the number of times the browser finds the same element without setting any variables. Let's understand the concept with the help of examples.

Implementation of Simple Technique:

    $(document).ready(function () {

            $("#dvDemo").addClass('hor-minimalist-c');
            $("#dvDemo").css('color','red');
            $("#dvDemo").fadeIn('fast');

        });

Implementation of Chaining Technique:

         
$(document).ready(function () {

   $("#dvDemo").addClass('hor-minimalist-c').css('color', 'red').fadeIn('fast');

  });

While chaining, the line of code could turn out to be very long. However, jQuery isn't extremely strict on the syntax structure; you can organize it like you need, including line breaks and spaces.

         
$(document).ready(function () {

   $("#dvDemo").addClass('hor-minimalist-c')
               .css('color', 'red')
               .fadeIn('fast');

  });

Both the codes above will perform same as far as functionality is concerned but the difference is that second code is shorter and faster because we have use chaining concept in it. The first technique has a problem and that is JQuery have to find "dvDemo" three times in the whole DOM and then execute the functions attached to it.

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.

Friday, 26 April 2013

How To Check If Specific Value Exist In Dropdown List Or Not

Today in this tutorial we will learn to check if a specific value exist in drop down list or not with the help of Jquery. Let’s start this with an example.

Example:-
Suppose a drop down or select list with id="ddlNames".

    <select id="ddlNames">
        <option value="1">Nancy Davolio</option>
        <option value="2">Andrew Fuller</option>
        <option value="3">Janet Leverling</option>
        <option value="4">Margaret Peacock</option>
        <option value="5">Steven Buchanan</option>
        <option value="6">Michael Suyama</option>
        <option value="7">Robert King</option>
        <option value="8">Laura Callahan</option>
        <option value="9">Anne Dodsworth</option>
    </select>

Now I want to check if the name “Rober King” exists in the dropdown or not?

Method 1:-

            var name = "Robert King";

            $('#ddlNames option').each(function () {
                if (this.text == name) {
                    alert("Exist")
                    return false;
                }
            });

In this method we use each loop to iterate through all the options and check if the specific text exists or not.

Method 2:-

var name = "Robert King";

if ($("select[id$='ddlNames'] option:contains('" + name + "')").length > 0) {
                alert("Exist");
            }

In this method contains() a built-in Jquery function is used to check if the specified text exist or not. By using same method you can check the value as well. Let me know in the comment section if you know better way to check if a value exist in a select list or not.

Hope it 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, 18 April 2013

Holding document.ready() using jQuery.holdReady() function

Today in this tutorial we will learn about an important function holdReady() of Jquery. I was searching about Jquery on Google and I found it informative for me and I decided it to post this article.

We can hold or release the execution of jQuery’s ready event by using jQuery.holdReady() function.This method should be call before we run ready event.To delay the ready event, we need to call jQuery.holdReady(true);

Whenever we want to release the ready event then we need to call jQuery.holdReady(false);

UseFull Scenario:-


Whenever we want to load any Jquery plugins before the execution of ready event.

Example : -


$.holdReady(true);

$.getScript("abcplugin.js", function() {

$.holdReady(false);

});

Hope it will be informative and helpfull for you.

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>