Solved

How do I add an OnClick event to my button in my jQuery DataTable.

Posted on 2016-07-21
17
136 Views
Last Modified: 2016-07-29
I'm so very close to accomplishing this, I just need a few lines of code (jQuery maybe) to make this work. I've added two buttons to my jQuery datatable, but don't know how to add click events or Urls to them so that when the user clicks them, it takes them to a page or does something else. I'm looking for code examples, preferably, or links to code examples, for how to add a URL to my buttons?

I may decide to make one of them a link, and would, at that point need to know how to add an on hover to that link.

<%@ Page Title="" Language="C#" MasterPageFile="MasterPageStock.master" AutoEventWireup="true" CodeFile="SignInGrid.aspx.cs" Inherits="SignInGrid" %>

<asp:Content ID="Content0" ContentPlaceHolderID="head" runat="Server">
    <style type="text/css">
        td.details-control {
            background: url('Images/bullet_add.png') no-repeat center center;
            cursor: pointer;
        }

        tr.shown td.details-control {
            background: url('Images/red_minus.png') no-repeat center center;
        }

        .navbar-right {
            display: block;
        }

        .lnkBtnLogOut, .pageTitle {
            display: inline;
        }

        .rwBtn {
            margin: 30px 0 0 0;
        }
    </style>

    <script type="text/javascript">
        //MYSQL DB VERSION
        $(document).ready(function () {
            $.ajax({
                "url": "SignInGrid.aspx/getData",
                "type": "POST",
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                success: function (json) {
                    var table = $('#example').DataTable({
                        "columns": [
                            {
                                "targets": 0,
                                "data": "StudentID",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '">' + data + '</a>';
                                }
                            },
                            { "data": "StudentName" },
                            { "data": "TimeIn" },
                            { "data": "TimeSignedIn" },
                            {
                                "targets": -1,
                                "data": null,
                                "defaultContent": "<button>Week Total</button>"
                            },
                            {
                                "targets": -1,
                                "data": null,
                                "defaultContent": "<button>Sign Out</button>"
                            },
                        ],
                        "aaData": $.parseJSON(json.d)
                    });
                }
            });

            var lblVal = $(".userIDLabel").html();
            var lblVal1 = $(".dealerTypeLabel").html();

            if (lblVal.indexOf("ADMIN") >= 0) {
                $(".adminLinks").css("display", "block");
                $("#liViewVendorSubmissions").css("display", "block");
                $("#liVendorList").css("display", "none");
                $("#topdropdown").css("display", "none");

                $("#liSearchInvintoryMenuItem").css("display", "none");
                $("#liRequstBoardMenuItem").css("display", "none");
                $("#liProfileMenuItem").css("display", "none");
                $("#liContactUsMenuItem").css("display", "none");
            }
            else {
                $(".adminLinks").css("display", "none");
            }
        });
    </script>
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
    <div class="row myRow">
        <div class="col-lg-12 text-page-title-center" style="background: #000; height: 33px;">
            <div id="divPageTitle" class="center-page-title center" runat="server">
                <asp:Label class="pageTitle" runat="server" ID="pageTitle" Text="SIGNED IN LIST"></asp:Label>
            </div>
        </div>
    </div>
    <table id="example" class="display responsive nowrap" data-page-length="5" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th data-orderable="true">StudentID</th>
                <th data-orderable="true">StudentName</th>
                <th data-orderable="true">TimeIn</th>
                <th data-orderble="true">TimeSignedIn</th>
                <th>Week Total</th>
                 <th>Sign Out</th>
                <%--<th>Delete</th>--%>
            </tr>
        </thead>
    </table>
</asp:Content>

Open in new window

myScreen.jpg
0
Comment
Question by:mikesExpertExchange
17 Comments
 
LVL 22

Expert Comment

by:Mrunal
Comment Utility
Hi
First thing you can find those buttons/links you have added in your table (may be by id/class/traversing)

After that you can use .on() method to attach (any) event on that element (buttons).

Note: this .on() is available on jQuery 1.8 above. for earlier version (1.7) you can use .live() and before that you can use delegates

$( selector ).live( events, data, handler );                // jQuery 1.3+
$( document ).delegate( selector, events, data, handler );  // jQuery 1.4.3+
$( document ).on( events, selector, data, handler );        // jQuery 1.7+

Source: http://api.jquery.com/live/

Hope this helps you.
0
 
LVL 30

Accepted Solution

by:
Marco Gasi earned 250 total points
Comment Utility
Extending Mrunal answer with a code sample, you can add an id to your buttons:
                            {
                                "targets": -1,
                                "data": null,
                                "defaultContent": "<button id='week-total'>Week Total</button>"
                            },
                            {
                                "targets": -1,
                                "data": null,
                                "defaultContent": "<button id='sign-out'>Sign Out</button>"
                            },

Open in new window


Then, in your javascript you can use something like this:
$(document).ready(function(){
    $(document).on('click', '#week-total', function(){
         //do something here
    });
    $(document).on('click', '#sign-out', function(){
         //do something here
    });
});

Open in new window


A quick and dirty way to add some code to your buttons is using onclick() event:
                            {
                                "targets": -1,
                                "data": null,
                                "defaultContent": "<button onclick='calcWeekTotal()'>Week Total</button>"
                            },
                            {
                                "targets": -1,
                                "data": null,
                                "defaultContent": "<button onclick='signOut()'>Sign Out</button>"
                            },

Open in new window

This will make clicking a button to execute anyt code inside the called function.
1
 
LVL 8

Expert Comment

by:Paweł
Comment Utility
you could also go Native JavaScript on this one.

you just need to select your buttons
iterate over each one and add a event listener that does whatever it is you would like it to do.
(function(){
 var btns = document.querySelectorAll("input");
  for(var i = 0; i < btns.length; i++){
    var btn = btns[i];
   
    btn.addEventListener("click", function(){
      var url = this.getAttribute("data-url");
    
      window.location = url;
   });
    
  }
  
})();

Open in new window


now the question becomes where are you getting the URL you want to redirect to, usually you have two options:
1) you have a JavaScript DataSource you query for it (json object or even an ajax call with parameters to a web service)

2) you can render it as a data dash attribute on your button when the HTML page renders.

I'd recommend option two if you know the urls before the page renders. basically when you build your buttons just build them like so

<input type="button" value="click Me" data-url ="http://myurl.com" />

then you add your event listener as above

  btn.addEventListener("click", function(){
      var url = this.getAttribute("data-url");
    
      window.location = url;
   });

Open in new window




https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...in
http://www.w3schools.com/jsref/met_document_addeventlistener.asp


here's a codepen to take a look at

http://codepen.io/anon/pen/grZqGP?editors=1010
0
 
LVL 1

Author Comment

by:mikesExpertExchange
Comment Utility
@Pawel: Would the following work? I'm trying it now but the page is just posting back to itself when I click the Week Total button.

                            {
                                "targets": -1,
                                "data": null,
                                "defaultContent": "<button id='btnWeekTotal' data-url='SignInGrid.aspx?getweektotal=y'>Week Total</button>"
                            },

Open in new window


            $("#btnWeekTotal").addEventListener("click", function () {
                var url = this.getAttribute("data-url");
                window.location = url;
            });

Open in new window

0
 
LVL 8

Expert Comment

by:Paweł
Comment Utility
Try a relative path /signingrid.aspx?etc in the data-url attribute or an absolute one i.e. http://domain/page.aspx

I take it your using web forms?
0
 
LVL 1

Author Comment

by:mikesExpertExchange
Comment Utility
When I put the jQuery code in as following:

        $("#btnWeekTotal").click (function () {
            var url = this.getAttribute("data-url");
            window.location = url;
        });

Open in new window


OR

        $("#btnWeekTotal").on("click" (function () {
            var url = this.getAttribute("data-url");
            window.location = url;
        });

Open in new window


it skips the code in my function whether the code lives inside of:

     $(document).ready(function () {

     });
or outside of it.
jQuery1.jpg
jQueryStep1.jpg
0
 
LVL 8

Expert Comment

by:Paweł
Comment Utility
On more thing try window.location.href = url

 not 100% on that part, in the ball park just not certain
0
 
LVL 1

Author Comment

by:mikesExpertExchange
Comment Utility
jQuery
jQueryStep1
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Author Comment

by:mikesExpertExchange
Comment Utility
ok, i've tried to upload my images 5 times but its not working so:

.
.
.
       {
            "targets": -1,
             "data": null,
              "defaultContent": "<button id='btnWeekTotal'data- 
                url='SignInGrid.aspx?getweektotal=y'>Week Total</button>"
        },
.
.


            $(document).on('click', '#btnWeekTotal', function () { <--i stop the debugger here
                var url = this.getAttribute("data-url");
                window.location = url; 
            }); <--when I step through it skips the code in the middle and lands here, why?

Open in new window


            $(document).click('#btnWeekTotal', function () { <--i stop the debugger here
                var url = this.getAttribute("data-url");
                window.location = url; 
            }); <--when I step through it skips the code in the middle and lands here, why?

Open in new window

0
 
LVL 1

Author Comment

by:mikesExpertExchange
Comment Utility
This works, but only when I set a break point in the script in fire fox, on this line: "var url = this.getAttribute("data-url");" inside my on click function

    <script type="text/javascript">
        //MYSQL DB VERSION
        $(document).ready(function () {
            $.ajax({
                "url": "SignInGrid.aspx/getData",
                "type": "POST",
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                success: function (json) {
                    var table = $('#example').DataTable({
                        "columns": [
                            {
                                "targets": 0,
                                "data": "StudentID",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '">' + data + '</a>';
                                }
                            },
                            { "data": "StudentName" },
                            { "data": "TimeIn" },
                            { "data": "TimeSignedIn" },
                            {
                                "targets": -1,
                                "data": null,
                                "defaultContent": "<button id='btnWeekTotal' data-url='SignInGrid.aspx?getweektotal='>Week Total</button>"
                            },
                            {
                                "targets": -1,
                                "data": null,
                                "defaultContent": "<button>Sign Out</button>"
                            },
                        ],
                        "aaData": $.parseJSON(json.d)
                    });
                }
            });

            var lblVal = $(".userIDLabel").html();
            var lblVal1 = $(".dealerTypeLabel").html();

            if (lblVal.indexOf("ADMIN") >= 0) {
                $(".adminLinks").css("display", "block");
                $("#liViewVendorSubmissions").css("display", "block");
                $("#liVendorList").css("display", "none");
                $("#topdropdown").css("display", "none");

                $("#liSearchInvintoryMenuItem").css("display", "none");
                $("#liRequstBoardMenuItem").css("display", "none");
                $("#liProfileMenuItem").css("display", "none");
                $("#liContactUsMenuItem").css("display", "none");
            }
            else {
                $(".adminLinks").css("display", "none");
            }
        });

        $(document).on('click', '#btnWeekTotal', function () {
            var url = this.getAttribute("data-url");
            window.location = url;
        });
    </script>

Open in new window

0
 
LVL 8

Assisted Solution

by:Paweł
Paweł earned 250 total points
Comment Utility
I'm reading this on a phone so I might be off but it looks to me like you're building your buttons in the success delegate of your Ajax call. But your binding your events in the document on ready.

Basically your assigning your event receivers before the button exists.

Try adding the event at the end of you r success function.
1
 
LVL 1

Author Comment

by:mikesExpertExchange
Comment Utility
Well that sounds believable. I may have to try to do this with a link, like the existing one that I have that already works. I don't know how anyone gets the buttons to work in jQuery DataTables. I did put the code where you suggested, but got nothing.
0
 
LVL 8

Expert Comment

by:Paweł
Comment Utility
http://api.jquery.com/on/

try

$(document).on('click', '#btnWeekTotal', null, function () {
            var url = this.getAttribute("data-url");
            window.location = url;
        });

if you call the three parameter on function then it doesn't take a function it takes data as a parameter.

try the above,
0
 
LVL 1

Author Comment

by:mikesExpertExchange
Comment Utility
@Pawel: Thanks for the suggestion. I put it in play and unfortunately, I got the same results: The page just reposts to itself and doesn't include the "data-url" query string parameter. Not sure why it won't: "take"?
0
 
LVL 8

Expert Comment

by:Paweł
Comment Utility
add an alert to see what url is when you fire the event

$(document).on('click', '#btnWeekTotal', null, function () {
            var url = this.getAttribute("data-url");
  alert(url);
alert(window.location);
          window.location = url;
     
        });

if the alerts don't fire that means that we're binding the event before the button exists, if the first alert is blank that means we are not setting the data-url attribute
0
 
LVL 1

Author Comment

by:mikesExpertExchange
Comment Utility
Thank you for your help. This has been helpful on my journey to getting this solved.
0
 
LVL 1

Author Closing Comment

by:mikesExpertExchange
Comment Utility
Thank you both for your contributions. They helped give me more avenues to research and I learned a few things from your suggestions as well.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
"In order to have an organized way for empathy mapping, we rely on a psychological model and trying to model it in a simple way, so we will split the board to three section for each persona and a scenario and try to see what those personas would Do,…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now