Link to home
Start Free TrialLog in
Avatar of Michael Sterling
Michael SterlingFlag for United States of America

asked on

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
Avatar of Mrunal
Mrunal
Flag of India image

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.
ASKER CERTIFIED SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of Michael Sterling

ASKER

@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

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?
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
On more thing try window.location.href = url

 not 100% on that part, in the ball park just not certain
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

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

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
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,
@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"?
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
Thank you for your help. This has been helpful on my journey to getting this solved.
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.