Dashboards & Visualizations

Jquery datepicker in splunk

michaelrosello
Path Finder

Has anyone successfully implemented the jquery datepicker in their spunk dashboard?

https://jqueryui.com/datepicker/

0 Karma
1 Solution

niketn
Legend

[UPDATED ANSWER] Refer to the post for updated answer with generic JS to allow html date input to be added and controlled via SimpleXML without changing the JS (based on the request from@nagar57 ) : https://community.splunk.com/t5/Dashboards-Visualizations/Create-a-generalized-JavaScript-to-use-mul...

_________________________________

 

@michaelrosello, if you can convert from Simple XML to HTML dashboard in Splunk you can use the Splunk Dev Tutorial to add jQuery UI Accordion and on similar lines you can include jQuery Date Picker input.

However, if you need to retain Simple XMl Dashboard, you can definitely try the html date input. Refer to Splunk Blog by Jason Conger for Using HTML5 Input Type

Following is a simple Example which uses Simple XML JS extension to use jQuery to control html date input and Splunk JS stack to use and modify time tokens.

alt text

Explanation for SimpleXML:

  1. html_input_date_control.js Javascript has been included
  2. First dummy search sets the tokFromDate as yesterday and tokToDate as today on dashboard load, to be set as input value on dashboard load. The dates are string date of format YYYY-mm-dd.
  3. Second dummy search is used to get the string date from date inputs and convert them to epoch time to be used by Splunk searches.
  4. Inline <style> has been used to put the From Date and To Date inputs in the same line and have padding between them.

Following is the Simple XML code:

<dashboard script="html_input_date_control.js">
  <label>HTML Date Picker</label>
  <!-- Dumy Search to set From Date and To Date on load-->
  <search>
    <query>| makeresults 
| eval fromDate=strftime(relative_time(now(),"-1d@d"),"%Y-%m-%d") 
| eval toDate=strftime(now(),"%Y-%m-%d")</query>
    <earliest>-1s@s</earliest>
    <latest>now</latest>
    <done>
      <set token="tokFromDate">$result.fromDate$</set>
      <set token="tokToDate">$result.toDate$</set>
    </done>
  </search>
  <!-- Dumy Search to convert String Time to Epoch Time-->
  <search>
    <query>| makeresults 
| eval earliestTime=strptime("$tokFromDate$","%Y-%m-%d") 
| eval latestTime=strptime("$tokToDate$","%Y-%m-%d")</query>
    <earliest>-1s@s</earliest>
    <latest>now</latest>
    <done>
      <set token="tokEarliestTime">$result.earliestTime$</set>
      <set token="tokLatestTime">$result.latestTime$</set>
    </done>
  </search>
  <row>
    <panel>
      <title>Selected String Time - $tokFromDate$ - $tokToDate$</title>
      <html>
        <style>
          .dateContainer{
            display:flex;
          }
          .dateInput{
            padding-right:15px;
          }          
        </style>
        <div class="dateContainer">
          <div class="dateInput">
            <div>From Date:</div>
            <input id="inputFromDate" type="date"/>
          </div>
          <div class="dateInput">
            <div>To Date:</div>
            <input id="inputToDate" type="date"/>
          </div>
        </div>
      </html>
    </panel>
  </row>
  <row>
    <panel>
      <title>Converted Epoch Time - $tokEarliestTime$ $tokLatestTime$</title>
      <chart>
        <title>Splunkd errors timechart by top 5 components</title>
        <search>
          <query>index=_internal sourcetype="splunkd" log_level!="INFO" component="*"
| timechart count by component limit=5 usenull=f useother=f
          </query>
          <earliest>$tokEarliestTime$</earliest>
          <latest>$tokLatestTime$</latest>
        </search>
        <option name="charting.axisTitleX.text">Time</option>
        <option name="charting.axisTitleY.text">Count</option>
        <option name="charting.chart.stackMode">stacked</option>
      </chart>
    </panel>
  </row>
</dashboard>

Following is the JavaScript code for html_input_date_control.js.
It needs to be saved to appserver/static folder i.e. $SPLUNK_HOME/etc/apps/<yourAppName>/appserver/static. If the folder appserver/static does not exist it would need to be manually created.
Since this solution approach require static file, Splunk needs to be restarted/refreshed or bumped. Internet Browser history would need to be cleared as well for the changes to reflect.

 require([
 "jquery",
 "splunkjs/mvc",
 "splunkjs/mvc/simplexml/ready!"
          ], function($,mvc) { 

        var defaultTokenModel = mvc.Components.get("default");
        var submittedTokenModel = mvc.Components.get("submitted");

        // On default model change of token tokFromDate assign the selected value to html date input inputFromDate
        defaultTokenModel.on("change:tokFromDate", function(newValue) {
            var tokFromDate=defaultTokenModel.get("tokFromDate");
            if(tokFromDate!=="undefined"){
                $('#inputFromDate').val(tokFromDate); 
            }
         });

         // On default model change of token tokToDate assign the selected value to html date input inputToDate
        defaultTokenModel.on("change:tokToDate", function(newValue) {
            var tokToDate=defaultTokenModel.get("tokToDate");
            if(tokToDate!=="undefined"){
                $('#inputToDate').val(tokToDate); 
            }
        });

        // On submitted model change of token tokFromDate assign the selected value to html date input inputFromDate
        submittedTokenModel.on("change:tokFromDate", function(newValue) {
            var tokFromDate=defaultTokenModel.get("tokFromDate");
            if(tokFromDate!=="undefined"){
                $('#inputFromDate').val(tokFromDate); 
            }
         });

         // On submitted model change of token tokToDate assign the selected value to html date input inputToDate
        submittedTokenModel.on("change:tokToDate", function(newValue) {
            var tokToDate=defaultTokenModel.get("tokToDate");
            if(tokToDate!=="undefined"){
                $('#inputToDate').val(tokToDate); 
            }
        });

        // On change of html date input inputFromDate, update the token tokFromDate in default and submitted model
        $(document).on("change", "#inputFromDate",function(){
            var dateText=$("#inputFromDate").val();
            defaultTokenModel.set("tokFromDate",dateText);
            submittedTokenModel.set("tokFromDate",dateText);
        });

        // On change of html date input inputToDate, update the token tokToDate in default and submitted model
        $(document).on("change", "#inputToDate",function(){
            var dateText=$("#inputToDate").val();
            defaultTokenModel.set("tokToDate",dateText);
            submittedTokenModel.set("tokToDate",dateText);
        });
});

Please try out and confirm!

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"

View solution in original post

niketn
Legend

[UPDATED ANSWER] Refer to the post for updated answer with generic JS to allow html date input to be added and controlled via SimpleXML without changing the JS (based on the request from@nagar57 ) : https://community.splunk.com/t5/Dashboards-Visualizations/Create-a-generalized-JavaScript-to-use-mul...

_________________________________

 

@michaelrosello, if you can convert from Simple XML to HTML dashboard in Splunk you can use the Splunk Dev Tutorial to add jQuery UI Accordion and on similar lines you can include jQuery Date Picker input.

However, if you need to retain Simple XMl Dashboard, you can definitely try the html date input. Refer to Splunk Blog by Jason Conger for Using HTML5 Input Type

Following is a simple Example which uses Simple XML JS extension to use jQuery to control html date input and Splunk JS stack to use and modify time tokens.

alt text

Explanation for SimpleXML:

  1. html_input_date_control.js Javascript has been included
  2. First dummy search sets the tokFromDate as yesterday and tokToDate as today on dashboard load, to be set as input value on dashboard load. The dates are string date of format YYYY-mm-dd.
  3. Second dummy search is used to get the string date from date inputs and convert them to epoch time to be used by Splunk searches.
  4. Inline <style> has been used to put the From Date and To Date inputs in the same line and have padding between them.

Following is the Simple XML code:

<dashboard script="html_input_date_control.js">
  <label>HTML Date Picker</label>
  <!-- Dumy Search to set From Date and To Date on load-->
  <search>
    <query>| makeresults 
| eval fromDate=strftime(relative_time(now(),"-1d@d"),"%Y-%m-%d") 
| eval toDate=strftime(now(),"%Y-%m-%d")</query>
    <earliest>-1s@s</earliest>
    <latest>now</latest>
    <done>
      <set token="tokFromDate">$result.fromDate$</set>
      <set token="tokToDate">$result.toDate$</set>
    </done>
  </search>
  <!-- Dumy Search to convert String Time to Epoch Time-->
  <search>
    <query>| makeresults 
| eval earliestTime=strptime("$tokFromDate$","%Y-%m-%d") 
| eval latestTime=strptime("$tokToDate$","%Y-%m-%d")</query>
    <earliest>-1s@s</earliest>
    <latest>now</latest>
    <done>
      <set token="tokEarliestTime">$result.earliestTime$</set>
      <set token="tokLatestTime">$result.latestTime$</set>
    </done>
  </search>
  <row>
    <panel>
      <title>Selected String Time - $tokFromDate$ - $tokToDate$</title>
      <html>
        <style>
          .dateContainer{
            display:flex;
          }
          .dateInput{
            padding-right:15px;
          }          
        </style>
        <div class="dateContainer">
          <div class="dateInput">
            <div>From Date:</div>
            <input id="inputFromDate" type="date"/>
          </div>
          <div class="dateInput">
            <div>To Date:</div>
            <input id="inputToDate" type="date"/>
          </div>
        </div>
      </html>
    </panel>
  </row>
  <row>
    <panel>
      <title>Converted Epoch Time - $tokEarliestTime$ $tokLatestTime$</title>
      <chart>
        <title>Splunkd errors timechart by top 5 components</title>
        <search>
          <query>index=_internal sourcetype="splunkd" log_level!="INFO" component="*"
| timechart count by component limit=5 usenull=f useother=f
          </query>
          <earliest>$tokEarliestTime$</earliest>
          <latest>$tokLatestTime$</latest>
        </search>
        <option name="charting.axisTitleX.text">Time</option>
        <option name="charting.axisTitleY.text">Count</option>
        <option name="charting.chart.stackMode">stacked</option>
      </chart>
    </panel>
  </row>
</dashboard>

Following is the JavaScript code for html_input_date_control.js.
It needs to be saved to appserver/static folder i.e. $SPLUNK_HOME/etc/apps/<yourAppName>/appserver/static. If the folder appserver/static does not exist it would need to be manually created.
Since this solution approach require static file, Splunk needs to be restarted/refreshed or bumped. Internet Browser history would need to be cleared as well for the changes to reflect.

 require([
 "jquery",
 "splunkjs/mvc",
 "splunkjs/mvc/simplexml/ready!"
          ], function($,mvc) { 

        var defaultTokenModel = mvc.Components.get("default");
        var submittedTokenModel = mvc.Components.get("submitted");

        // On default model change of token tokFromDate assign the selected value to html date input inputFromDate
        defaultTokenModel.on("change:tokFromDate", function(newValue) {
            var tokFromDate=defaultTokenModel.get("tokFromDate");
            if(tokFromDate!=="undefined"){
                $('#inputFromDate').val(tokFromDate); 
            }
         });

         // On default model change of token tokToDate assign the selected value to html date input inputToDate
        defaultTokenModel.on("change:tokToDate", function(newValue) {
            var tokToDate=defaultTokenModel.get("tokToDate");
            if(tokToDate!=="undefined"){
                $('#inputToDate').val(tokToDate); 
            }
        });

        // On submitted model change of token tokFromDate assign the selected value to html date input inputFromDate
        submittedTokenModel.on("change:tokFromDate", function(newValue) {
            var tokFromDate=defaultTokenModel.get("tokFromDate");
            if(tokFromDate!=="undefined"){
                $('#inputFromDate').val(tokFromDate); 
            }
         });

         // On submitted model change of token tokToDate assign the selected value to html date input inputToDate
        submittedTokenModel.on("change:tokToDate", function(newValue) {
            var tokToDate=defaultTokenModel.get("tokToDate");
            if(tokToDate!=="undefined"){
                $('#inputToDate').val(tokToDate); 
            }
        });

        // On change of html date input inputFromDate, update the token tokFromDate in default and submitted model
        $(document).on("change", "#inputFromDate",function(){
            var dateText=$("#inputFromDate").val();
            defaultTokenModel.set("tokFromDate",dateText);
            submittedTokenModel.set("tokFromDate",dateText);
        });

        // On change of html date input inputToDate, update the token tokToDate in default and submitted model
        $(document).on("change", "#inputToDate",function(){
            var dateText=$("#inputToDate").val();
            defaultTokenModel.set("tokToDate",dateText);
            submittedTokenModel.set("tokToDate",dateText);
        });
});

Please try out and confirm!

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"

rteja9
Path Finder

@niketn  Thanks for the wonderful code snippet. It works good for me. 

But the token is updating on change of date. But I want to see token update only on submit button click.

Can you please help on this?

0 Karma

deodion
Path Finder

Hello, what if I want to use this datepicker as a field, which I will INSERT into database table via DB Connect as field in table?

 

thank you,

0 Karma

niketn
Legend

@deodion Can you please add more details on your use case? Do you want to pass on the selected Date Picker value to DB or do you want to show several Date pickers in Table and then pass on the value to DB based on individual selection?

For the first case it should be straightforward, when you want Dashboard Datepicker value to be sent to DB connect, as you will already have the token that can be used in the SPL query for DBOUTPUT.

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma

deodion
Path Finder

@niketn thank you for quick respond,

Im looking for making basic CRM apps with Splunk as front end, with simple functionality for Insurance sales use case,

like using client records, sales process or new opportunity record, sales record, 

So Im checking how to solve the CRUD (create read update delete) functionality with Splunk,

Im pretty sure this is very doable via DB connect,

Im thinking the majority solution is on Sideview utils app,

Hopefuly achievable without much going deep dive into Splunk Dev world,

and perhaps my guess is correct one or two of my main obstacles are simply around Sideview, abit investment in learning XML, and making sure all data types are supported in the form dashboard so user can not enter unwanted values, one of it date time,

 

 

0 Karma

niketn
Legend

Paging @sideview for help 🙂

But yes you are right either Simple XML JS extension or Sideview Utils. In both cases I would expect value to be fetched and passed using tokens.

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma

sideview
SplunkTrust
SplunkTrust

Technically Canary has a module called "DateTime" which does give you a nice absolute date/time picker.   It ultimately outputs a $foo$ token into the Canary UI that is an epochtime value. 

On the larger implications of building an entire CRUD UI, with the date picker as just one of several fields in there let me say some words about that ----   It is technically possible to do build a full CRUD UI with Canary (with splunk 8 or 7) or Sideview Utils (splunk 7.X and below) as the front end.

I have built several over the years, in arguably 3 different ways.  However this is very advanced and pretty far beyond the sort of docs and examples that Canary (or Sideview Utils) docs will be illustrating and explaining.

The Create side is fairly easy and there are a lot fo ways to skin that cat.   The 'Edit" side is the tricky one historically.      rendering the properties into a table row or into some kind of custom HTML layout is doble with either the Table module's "embedding" features, or with the Multiplexer module.    but there are some corner cases that you need to get right for good user experience.

Anyway,  the coolest way is to use a Paged Multiplexer module for the hard part   We have a commercial product called "Supporting AXL Addon for Cisco CDR Reporting and Analytics"  that has a full crud ui for credentials.    And our main product "Cisco CDR Reporting and Analytics" has several CRUD ui's to administer different things.  Those ones are built leaning more heavily on our "customBehavior" mechanism, meaning most of the fiddly bits are over in javascript.

In short though, if you don't already have a lot of experience creating and troubleshooting views in Canary (or in Sideview Utils),  i would not pick this as your first challenge because it's quite complex and it will involve a lot of moving parts and great familiarity with each of them.

 

nagar57
Communicator

Hi @niketn  I see that this will be applicable only for one date range. If I have to give the input of date range for multiple panels then I have to mention the Date Picker id of every input. This will never work a one generalized solution. Do you have any idea how to create one generalized Javascript which allows user to put N no.of date pickers independent from each other?

0 Karma

thulasikrishnan
Path Finder

@niketnilay this is an excellent answer. you have brilliantly collated scattered info and put it together in a usable way. Just a disclaimer though, there are still orgs that run ancient versions on Splunk (< 6.3) that do not have the done tag in XML. I'm not so much worried about having a default date appearing in the input field. But my problem right now is, in the absence of that default date assignment logic, I can't seem to bind the token with the date selection in the input field.

niketn
Legend

@thulasikrishnan prior to 6.5 the search handler equivalent for <done> was <finalized>. Try with that and confirm.

Do upvote and answer and comments that you found useful 🙂

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma

thulasikrishnan
Path Finder

Ok so this doesn't work on 6.2.x or lesser which do not have <done>or <finalized>. I am trying this in 6.3.0 now. I somehow encounter a strange issue where below snippet
```

   <set token="tokFromDate">$result.fromDate$</set>
   <set token="tokToDate">$result.toDate$</set>

``
doesn't assign the result of the
makeresultsquery but instead assign the value as$result.fromDate$` instead of the value in this result token which is strange!

btw I already upvoted the answer as it is correct.

0 Karma

thulasikrishnan
Path Finder

Alright so this seems to be a known issue addressed in this page:
https://answers.splunk.com/answers/505978/why-is-setting-a-token-from-result-not-working.html

TLDR - $result.field$ token works only when you use <finalized>. Replace <done> with <finalized> in the Accepted Answer code snippet and it works in case you encounter problems with older versions.

0 Karma

rijutha
Explorer

@niketnilay I have just used this date picker in a dashboard i created. I have bumped, debug refreshed and restarted splunk. However I cannot get it to display the default date in the input fields when the page loads. It seemed like it was not loading the js. But when i check the console logs of my browser, i can see it is loading the js. But still the input fields remain empty. Would you have any suggestions to troubleshoot this?

0 Karma

michaelrosello
Path Finder

Yes It worked.I wonder why I haven't seen this in my researching. Thank you!!

0 Karma

niketn
Legend

@michaelrosello, Jason's blog has been there for quite some time now but I dont think I have seen HTML Date picker in Splunk Answers or any blogs. So I thought to spend time solving this 🙂 I am sure others would be interested in this kind of Use Case and can extend to other HTML controls.

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma
Get Updates on the Splunk Community!

.conf24 | Registration Open!

Hello, hello! I come bearing good news: Registration for .conf24 is now open!   conf is Splunk’s rad annual ...

Splunk is officially part of Cisco

Revolutionizing how our customers build resilience across their entire digital footprint.   Splunk ...

Splunk APM & RUM | Planned Maintenance March 26 - March 28, 2024

There will be planned maintenance for Splunk APM and RUM between March 26, 2024 and March 28, 2024 as ...