Solved

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

Posted on 2016-07-21
17
173 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
ID: 41724100
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 31

Accepted Solution

by:
Marco Gasi earned 250 total points
ID: 41724182
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 9

Expert Comment

by:Paweł
ID: 41724189
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
The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 41724862
@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 9

Expert Comment

by:Paweł
ID: 41724917
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
ID: 41724926
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 9

Expert Comment

by:Paweł
ID: 41724930
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
ID: 41724948
jQuery
jQueryStep1
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 41724957
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
ID: 41725132
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 9

Assisted Solution

by:Paweł
Paweł earned 250 total points
ID: 41725155
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
ID: 41725167
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 9

Expert Comment

by:Paweł
ID: 41725994
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
ID: 41728417
@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 9

Expert Comment

by:Paweł
ID: 41728903
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
ID: 41734991
Thank you for your help. This has been helpful on my journey to getting this solved.
0
 
LVL 1

Author Closing Comment

by:mikesExpertExchange
ID: 41734993
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Because your company can’t afford for you to make SEO mistakes, you’ll want to ensure you’re taking the right steps each and every time you post a new piece of content. This list of optimization do’s and don’ts can help you become an SEO wizard.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

792 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