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

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
LVL 1
Michael SterlingWeb Applications DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MrunalCommented:
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
Marco GasiFreelancerCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PawełI Design & Develop SoftwareCommented:
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
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Michael SterlingWeb Applications DeveloperAuthor Commented:
@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
PawełI Design & Develop SoftwareCommented:
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
Michael SterlingWeb Applications DeveloperAuthor Commented:
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
PawełI Design & Develop SoftwareCommented:
On more thing try window.location.href = url

 not 100% on that part, in the ball park just not certain
0
Michael SterlingWeb Applications DeveloperAuthor Commented:
jQuery
jQueryStep1
0
Michael SterlingWeb Applications DeveloperAuthor Commented:
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
Michael SterlingWeb Applications DeveloperAuthor Commented:
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
PawełI Design & Develop SoftwareCommented:
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
Michael SterlingWeb Applications DeveloperAuthor Commented:
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
PawełI Design & Develop SoftwareCommented:
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
Michael SterlingWeb Applications DeveloperAuthor Commented:
@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
PawełI Design & Develop SoftwareCommented:
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
Michael SterlingWeb Applications DeveloperAuthor Commented:
Thank you for your help. This has been helpful on my journey to getting this solved.
0
Michael SterlingWeb Applications DeveloperAuthor Commented:
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
jQuery

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.