Dashboards & Visualizations

How to have a checkbox, check all the rows in the table?

Explorer

Hi all ,
My requirement is to have a dashboard for bulk alarm enable /disable. means I can select multiple alarms and click a button which will disable/enable the alarms. for that to have check boxes in table i used "https://answers.splunk.com/answers/587089/multiselect-table-rows.html " and created a dashboard like this

alt text

Now I need a checkbox which will select all other check boxes. I want to have that checkbox in table header in third column that is in place of "checkbox" in my picture. Also I would like to refresh page when submit button is clicked , so that user will understand that action completed.. Can some one please help me to achieve this.

my.js

require([
    'underscore',
    'jquery',
    'splunkjs/mvc',
    'splunkjs/mvc/tableview',
    'splunkjs/mvc/simplexml/ready!'
], function(_, $, mvc, TableView) {

    var tokens = mvc.Components.get("default");
    var selected_values_array = [];
    var submittedTokens = mvc.Components.get('submitted');

        var CustomRangeRenderer = TableView.BaseCellRenderer.extend({
        canRender: function(cell) {
            return _(['checkbox']).contains(cell.field);
        },
        render: function($th, cell) {
            var a = $('<div>').attr({"id":"chk-sourcetype"+cell.value,"value":cell.value}).addClass('checkbox').click(function() {

                if($(this).attr('class')==="checkbox")
                {
                    selected_values_array.push($(this).attr('value'));
                    $(this).removeClass();
                    $(this).addClass("checkbox checked");
                }
                else {
                    $(this).removeClass();
                    $(this).addClass("checkbox");
                    var i = selected_values_array.indexOf($(this).attr('value'));
                    if(i != -1) {
                        selected_values_array.splice(i, 1);
                    }

                }
                console.log(selected_values_array);
            }).appendTo($th);
        }
    });

    var CustomRangeRenderer = TableView.BaseCellRenderer.extend({
        canRender: function(cell) {
            return _(['checkbox']).contains(cell.field);
        },
        render: function($td, cell) {
            var a = $('<div>').attr({"id":"chk-sourcetype"+cell.value,"value":cell.value}).addClass('checkbox').click(function() {

                if($(this).attr('class')==="checkbox")
                {
                    selected_values_array.push($(this).attr('value'));
                    $(this).removeClass();
                    $(this).addClass("checkbox checked");
                }
                else {
                    $(this).removeClass();
                    $(this).addClass("checkbox");
                    var i = selected_values_array.indexOf($(this).attr('value'));
                    if(i != -1) {
                        selected_values_array.splice(i, 1);
                    }

                }
                console.log(selected_values_array);
            }).appendTo($td);
        }
    });


    var tableIDs = ["myTable"];
    for (i=0;i<tableIDs.length;i++) {
        var sh = mvc.Components.get(tableIDs[i]);
        if(typeof(sh)!="undefined") {
            sh.getVisualization(function(tableView) {

                tableView.table.addCellRenderer(new CustomRangeRenderer());
                tableView.table.render();
            });
        }
    }

        ;

    $(document).ready(function () {
        $("#mybutton").on("click", function (e) {
            e.preventDefault();
            console.log("in");              
            tokens.set("mytoken", selected_values_array.join());
            submittedTokens.set(tokens.toJSON());
            console.log("refresh");

        });
    });
});

mydashboard.xml

<form script="my.js" stylesheet="my.css">
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="filter1">
      <label>label</label>
      <default></default>
    </input>
  </fieldset>
  <row>
    <panel>
      <table id="myTable">
        <title>My Table</title>
        <search id="mysearch1">
          <query>|rest /servicesNS/-/-/saved/searches |rename eai:acl.app as app|where app="asp" and title  like "%$filter1$%"|dedup title|rename disabled as Enabled|replace 0 with Yes , 1 with No in Enabled|rename title as sourcetype|table sourcetype,Enabled| eval checkbox=sourcetype</query>
          <earliest>-15m</earliest>
          <latest>now</latest>
        </search>
        <option name="count">10</option>
        <option name="drilldown">row</option>
        <drilldown>
          <condition field="*"></condition>
        </drilldown>
      </table>
    </panel>
  </row>
  <row>
     <html>
       <div>
         <input type="button" id="mybutton" value="My Button" />
       </div>
     </html>
   </row>
  <row>
    <panel>
      <table>
        <title>My Selected Value</title>
        <search id="mysearch">
          <query>|enablecustom enable "$mytoken$"</query>
          <earliest>-15m</earliest>
          <latest>now</latest>
        </search>
        <option name="count">10</option>
        <option name="drilldown">none</option>
      </table>
    </panel>
  </row>
</form>

Please help me.
Thanks in advance.

0 Karma
1 Solution

SplunkTrust
SplunkTrust

@vasanthi77

I did some enhancement with this code. Can you please try it?

multiselect_table.js

require([
        'underscore',
        'jquery',
        'splunkjs/mvc',
        'splunkjs/mvc/tableview',
        'splunkjs/mvc/simplexml/ready!'
    ], function (_, $, mvc, TableView) {
    // Access the "default" token model
    var tokens = mvc.Components.get("default");
    var selected_values_array = [];
    var isSelectAll = false;
    var searchAValues = [];
    var searchAFields = [];
    var fieldKey = "CheckBox";
    var fieldDataStoreKey="data-sort-key="+fieldKey;
    var submittedTokens = mvc.Components.get('submitted');
    console.log("This is Multi-select table JS test Kamlesh");
    // Custom renderer for applying checkbox.
    var CustomRenderer = TableView.BaseCellRenderer.extend({
            canRender: function (cell) {
                return _([fieldKey]).contains(cell.field);
            },
            render: function ($td, cell) {
                // all_values_array.push(cell.value);
                var cls = "checkbox";
                if(isSelectAll) {
                    cls = "checkbox checked";
                }
                var a = $('<div>').attr({
                    "id": "chk-sourcetype_" + cell.value,
                    "value": cell.value
                }).addClass(cls).click(function () {
                    if ($(this).attr('class') === "checkbox") {
                        selected_values_array.push($(this).attr('value'));
                        $(this).removeClass();
                        $(this).addClass("checkbox checked");
                    } else {
                        $(this).removeClass();
                        $(this).addClass("checkbox");
                        var i = selected_values_array.indexOf($(this).attr('value'));
                        if (i != -1) {
                            selected_values_array.splice(i, 1);
                        }
                    }
                    console.log(selected_values_array);
                }).appendTo($td);
            }
        });

    //List of table ID
    var sh = mvc.Components.get("myTable");
    if (typeof(sh) != "undefined") {
        sh.getVisualization(function (tableView) {
            // Add custom cell renderer and force re-render
            tableView.table.addCellRenderer(new CustomRenderer());
            tableView.table.render();
            tableView.on('rendered', function(view) {
                setCheckAllCheckBox();
            });
            // setCheckAllCheckBox();
        });
    }

    var SearchA = mvc.Components.get("SearchA");
    var SearchAResults = SearchA.data("results");
    SearchAResults.on("data", function () {
        resultArray = SearchAResults.data().rows;
        searchAFields = SearchAResults.data().fields;
        var keyIndex=searchAFields.indexOf(fieldKey);
        searchAValues = [];
        $.each(resultArray, function (index, value) { 
            searchAValues[index]=value[keyIndex];
        })
    });

    SearchA.on('search:start', function (properties) {
        console.log("kamlesh",properties);
        isSelectAll = false;
        tokens.unset("mytoken");
        tokens.set("mytoken", "");
        submittedTokens.set(tokens.toJSON());
    });
    SearchA.on('search:done', function (properties) {
        console.log("kamlesh",properties);
    });

    // Disabling button while search is running
    var SearchB = mvc.Components.get('SearchB');
    SearchB.on('search:start', function (properties) {
        $("#mybutton").attr('disabled', true);
    });

    SearchB.on('search:done', function (properties) {
        $("#mybutton").attr('disabled', false);
    });
    var sto;
    function setCheckAllCheckBox()
    {
        // console.log("In setCheckAllCheckBox");
        var a = $("["+fieldDataStoreKey+"]");
        // console.log(a);
        a.html("");
        var cls = "checkbox";
        if(isSelectAll) {
            cls = "checkbox checked";
        }
        var temp = $('<div>').attr({
            "id": "chk-sourcetype-All",
            "value": "All"
        }).addClass(cls).click(function () {
            if ($(this).attr('class') === "checkbox") {
                $(this).removeClass();
                $(this).addClass("checkbox checked");
                isSelectAll = true;
            } else {
                $(this).removeClass();
                $(this).addClass("checkbox");
                isSelectAll = false;
            }
            checkUnCheckAllCheckboxes();
        }).appendTo(a);
        $("["+fieldDataStoreKey+"]").parent().removeAttr("class");
        $("["+fieldDataStoreKey+"]").removeAttr("data-sort-key");
    }
    function checkUnCheckAllCheckboxes(){
        console.log($('[id^="chk-sourcetype_"]'));
        var cls = "checkbox";
        selected_values_array = [];
        if(isSelectAll) {
            cls = "checkbox checked";
            $.each(searchAValues, function (index, value) { 
                selected_values_array.push(value);
            })
        }
        $('[id^="chk-sourcetype_"]').removeClass();
        $('[id^="chk-sourcetype_"]').addClass(cls);
    }

    $(document).ready(function () {
        //setting up tokens with selected value.
        $("#mybutton").on("click", function (e) {
            e.preventDefault();
            console.log(selected_values_array);
            tokens.set("mytoken", selected_values_array.join());
            submittedTokens.set(tokens.toJSON());
            $("#mybutton").attr('disabled', true);
        });
        // setCheckAllCheckBox();
        setTimeout(function(){
            setCheckAllCheckBox();
            console.log("In Wait");
        },2000);
    });
});

multiselect_table.css

/* The standalone checkbox square*/
 .checkbox {
   width:20px;
   height:20px;
   border: 1px solid #000;
   display: inline-block;
 }

 /* This is what simulates a checkmark icon */
 .checkbox.checked:after {
   content: '';
   display: block;
   width: 4px;
   height: 7px;

   /* "Center" the checkmark */
   position:relative;
   top:4px;
   left:7px;

   border: solid #000;
   border-width: 0 2px 2px 0;
   transform: rotate(45deg);
 }

multiselect_table.xml

<form script="multiselect_table.js" stylesheet="multiselect_table.css">
  <label>Multi-Select Table Rows Example</label>
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="tknSourcetype" searchWhenChanged="true">
      <label>tknSourcetype</label>
      <default>*</default>
    </input>
  </fieldset>
  <row>
    <panel>
      <!-- This Panel is for instruction purpose only-->
      <html>
    <h1>This is an example for multi select table rows.</h1>
    <h2>Steps:</h2>
    <ui>
    <li>Select rows from Panel A by clicking on checkboxes.</li>
    <li>Click on "Submit" button</li>
    <li>You will get selected values in Panel B.</li>
    </ui>
    &lt;br/&gt;
    <h3>This is how you can achieve your requirements. See below files for implementation code.</h3>
    <code>multiselect_table.js</code>
        &lt;br/&gt;
    <code>multiselect_table.css</code>
        &lt;br/&gt;
    <code>multiselect_table.xml</code>
        &lt;br/&gt;
    </html>
    </panel>
  </row>
  <row>
    <panel>
      <table id="myTable">
        <title>Panel A</title>
        <search id="SearchA">
          <query>index=_internal sourcetype="*$tknSourcetype$*" | stats count by sourcetype | eval CheckBox=sourcetype | table CheckBox sourcetype count</query>
          <earliest>-15m</earliest>
          <latest>now</latest>
        </search>
        <option name="count">10</option>
        <option name="drilldown">row</option>
        <option name="refresh.display">progressbar</option>
        <drilldown>
          <condition field="*"></condition>
        </drilldown>
      </table>
    </panel>
    <panel>
      <html>
       <div>
         <input type="button" id="mybutton" value="Submit"/>
       </div>
     </html>
    </panel>
    <panel>
      <table>
        <title>Panel B</title>
        <search id="SearchB">
          <query>| makeresults | eval SelectedRowValue="$mytoken$" | makemv delim="," SelectedRowValue | stats count by SelectedRowValue | table SelectedRowValue</query>
          <earliest>-15m</earliest>
          <latest>now</latest>
        </search>
        <option name="count">10</option>
        <option name="drilldown">none</option>
      </table>
    </panel>
  </row>
</form>

Thanks

View solution in original post

SplunkTrust
SplunkTrust

@vasanthi77

I did some enhancement with this code. Can you please try it?

multiselect_table.js

require([
        'underscore',
        'jquery',
        'splunkjs/mvc',
        'splunkjs/mvc/tableview',
        'splunkjs/mvc/simplexml/ready!'
    ], function (_, $, mvc, TableView) {
    // Access the "default" token model
    var tokens = mvc.Components.get("default");
    var selected_values_array = [];
    var isSelectAll = false;
    var searchAValues = [];
    var searchAFields = [];
    var fieldKey = "CheckBox";
    var fieldDataStoreKey="data-sort-key="+fieldKey;
    var submittedTokens = mvc.Components.get('submitted');
    console.log("This is Multi-select table JS test Kamlesh");
    // Custom renderer for applying checkbox.
    var CustomRenderer = TableView.BaseCellRenderer.extend({
            canRender: function (cell) {
                return _([fieldKey]).contains(cell.field);
            },
            render: function ($td, cell) {
                // all_values_array.push(cell.value);
                var cls = "checkbox";
                if(isSelectAll) {
                    cls = "checkbox checked";
                }
                var a = $('<div>').attr({
                    "id": "chk-sourcetype_" + cell.value,
                    "value": cell.value
                }).addClass(cls).click(function () {
                    if ($(this).attr('class') === "checkbox") {
                        selected_values_array.push($(this).attr('value'));
                        $(this).removeClass();
                        $(this).addClass("checkbox checked");
                    } else {
                        $(this).removeClass();
                        $(this).addClass("checkbox");
                        var i = selected_values_array.indexOf($(this).attr('value'));
                        if (i != -1) {
                            selected_values_array.splice(i, 1);
                        }
                    }
                    console.log(selected_values_array);
                }).appendTo($td);
            }
        });

    //List of table ID
    var sh = mvc.Components.get("myTable");
    if (typeof(sh) != "undefined") {
        sh.getVisualization(function (tableView) {
            // Add custom cell renderer and force re-render
            tableView.table.addCellRenderer(new CustomRenderer());
            tableView.table.render();
            tableView.on('rendered', function(view) {
                setCheckAllCheckBox();
            });
            // setCheckAllCheckBox();
        });
    }

    var SearchA = mvc.Components.get("SearchA");
    var SearchAResults = SearchA.data("results");
    SearchAResults.on("data", function () {
        resultArray = SearchAResults.data().rows;
        searchAFields = SearchAResults.data().fields;
        var keyIndex=searchAFields.indexOf(fieldKey);
        searchAValues = [];
        $.each(resultArray, function (index, value) { 
            searchAValues[index]=value[keyIndex];
        })
    });

    SearchA.on('search:start', function (properties) {
        console.log("kamlesh",properties);
        isSelectAll = false;
        tokens.unset("mytoken");
        tokens.set("mytoken", "");
        submittedTokens.set(tokens.toJSON());
    });
    SearchA.on('search:done', function (properties) {
        console.log("kamlesh",properties);
    });

    // Disabling button while search is running
    var SearchB = mvc.Components.get('SearchB');
    SearchB.on('search:start', function (properties) {
        $("#mybutton").attr('disabled', true);
    });

    SearchB.on('search:done', function (properties) {
        $("#mybutton").attr('disabled', false);
    });
    var sto;
    function setCheckAllCheckBox()
    {
        // console.log("In setCheckAllCheckBox");
        var a = $("["+fieldDataStoreKey+"]");
        // console.log(a);
        a.html("");
        var cls = "checkbox";
        if(isSelectAll) {
            cls = "checkbox checked";
        }
        var temp = $('<div>').attr({
            "id": "chk-sourcetype-All",
            "value": "All"
        }).addClass(cls).click(function () {
            if ($(this).attr('class') === "checkbox") {
                $(this).removeClass();
                $(this).addClass("checkbox checked");
                isSelectAll = true;
            } else {
                $(this).removeClass();
                $(this).addClass("checkbox");
                isSelectAll = false;
            }
            checkUnCheckAllCheckboxes();
        }).appendTo(a);
        $("["+fieldDataStoreKey+"]").parent().removeAttr("class");
        $("["+fieldDataStoreKey+"]").removeAttr("data-sort-key");
    }
    function checkUnCheckAllCheckboxes(){
        console.log($('[id^="chk-sourcetype_"]'));
        var cls = "checkbox";
        selected_values_array = [];
        if(isSelectAll) {
            cls = "checkbox checked";
            $.each(searchAValues, function (index, value) { 
                selected_values_array.push(value);
            })
        }
        $('[id^="chk-sourcetype_"]').removeClass();
        $('[id^="chk-sourcetype_"]').addClass(cls);
    }

    $(document).ready(function () {
        //setting up tokens with selected value.
        $("#mybutton").on("click", function (e) {
            e.preventDefault();
            console.log(selected_values_array);
            tokens.set("mytoken", selected_values_array.join());
            submittedTokens.set(tokens.toJSON());
            $("#mybutton").attr('disabled', true);
        });
        // setCheckAllCheckBox();
        setTimeout(function(){
            setCheckAllCheckBox();
            console.log("In Wait");
        },2000);
    });
});

multiselect_table.css

/* The standalone checkbox square*/
 .checkbox {
   width:20px;
   height:20px;
   border: 1px solid #000;
   display: inline-block;
 }

 /* This is what simulates a checkmark icon */
 .checkbox.checked:after {
   content: '';
   display: block;
   width: 4px;
   height: 7px;

   /* "Center" the checkmark */
   position:relative;
   top:4px;
   left:7px;

   border: solid #000;
   border-width: 0 2px 2px 0;
   transform: rotate(45deg);
 }

multiselect_table.xml

<form script="multiselect_table.js" stylesheet="multiselect_table.css">
  <label>Multi-Select Table Rows Example</label>
  <fieldset submitButton="false" autoRun="true">
    <input type="text" token="tknSourcetype" searchWhenChanged="true">
      <label>tknSourcetype</label>
      <default>*</default>
    </input>
  </fieldset>
  <row>
    <panel>
      <!-- This Panel is for instruction purpose only-->
      <html>
    <h1>This is an example for multi select table rows.</h1>
    <h2>Steps:</h2>
    <ui>
    <li>Select rows from Panel A by clicking on checkboxes.</li>
    <li>Click on "Submit" button</li>
    <li>You will get selected values in Panel B.</li>
    </ui>
    &lt;br/&gt;
    <h3>This is how you can achieve your requirements. See below files for implementation code.</h3>
    <code>multiselect_table.js</code>
        &lt;br/&gt;
    <code>multiselect_table.css</code>
        &lt;br/&gt;
    <code>multiselect_table.xml</code>
        &lt;br/&gt;
    </html>
    </panel>
  </row>
  <row>
    <panel>
      <table id="myTable">
        <title>Panel A</title>
        <search id="SearchA">
          <query>index=_internal sourcetype="*$tknSourcetype$*" | stats count by sourcetype | eval CheckBox=sourcetype | table CheckBox sourcetype count</query>
          <earliest>-15m</earliest>
          <latest>now</latest>
        </search>
        <option name="count">10</option>
        <option name="drilldown">row</option>
        <option name="refresh.display">progressbar</option>
        <drilldown>
          <condition field="*"></condition>
        </drilldown>
      </table>
    </panel>
    <panel>
      <html>
       <div>
         <input type="button" id="mybutton" value="Submit"/>
       </div>
     </html>
    </panel>
    <panel>
      <table>
        <title>Panel B</title>
        <search id="SearchB">
          <query>| makeresults | eval SelectedRowValue="$mytoken$" | makemv delim="," SelectedRowValue | stats count by SelectedRowValue | table SelectedRowValue</query>
          <earliest>-15m</earliest>
          <latest>now</latest>
        </search>
        <option name="count">10</option>
        <option name="drilldown">none</option>
      </table>
    </panel>
  </row>
</form>

Thanks

View solution in original post

SplunkTrust
SplunkTrust

@vasanthi77

Can you please update on this question?

Explorer

@kamlesh_vaghela i already up voted for your comment. how to accept this as answer ? 😐

0 Karma

SplunkTrust
SplunkTrust

@vasanthi77

By clicking "Accept” directly below the answer 🙂

https://docs.splunk.com/Documentation/Splunkbase/splunkbase/Answers/Questions#Resolving_your_post

0 Karma

Explorer

done 🙂 Thanks @kamlesh_vaghela

0 Karma

Loves-to-Learn Lots

Hi @kamlesh_vaghela @vasanthi77 ,

 

I used the same multiselect_table.js and multiselect_table.css in splunk to get select all checkbox. But the select all checkbox is coming and disappearing after loading. Please help me on this

Thanks,

Archana

Tags (1)
0 Karma

SplunkTrust
SplunkTrust

@Archana944 

I'm assuming you have used js from accepted post. Can you please add setTimeout and try again?

 

 // Add custom cell renderer and force re-render
tableView.table.addCellRenderer(new CustomRenderer());
tableView.table.render();
tableView.on('rendered', function(view) {
	setTimeout(function(){
    	setCheckAllCheckBox();
    },500);
});

 

0 Karma

Loves-to-Learn Lots

Hi @kamlesh_vaghela ,

Now the select all checkbox is appearing. But it is not checking all checkboxes. Please find my codes below.

my.js

require([
'underscore',
'jquery',
'splunkjs/mvc',
'splunkjs/mvc/tableview',
'splunkjs/mvc/simplexml/ready!',
'splunkjs/mvc/searchmanager'
], function(_, $, mvc, TableView) {
// Access the "default" token model
var tokens = mvc.Components.get("default");
var selected_values_array = [];
var query_array = [];
var query;
var fieldKey = "CheckBox";
var fieldDataStoreKey="data-sort-key="+fieldKey;
var isSelectAll = false;
var submittedTokens = mvc.Components.get('submitted');
var mySearchManager = "";
var SearchManager = require('splunkjs/mvc/searchmanager');
var CustomRangeRenderer = TableView.BaseCellRenderer.extend({
canRender: function(cell) {
return _([fieldKey]).contains(cell.field);
},
render: function($td, cell) {
var cls = "checkbox";
if(isSelectAll) {
cls = "checkbox checked";
}
var a = $('<div>').attr({"id":"chk-sourcetype"+cell.value,"value":cell.value}).addClass(cls).click(function() {
// console.log("checked",$(this).attr('class'));
// console.log("checked",$(this).attr('value'));
if($(this).attr('class')==="checkbox")
{
selected_values_array.push($(this).attr('value'));
$(this).removeClass();
$(this).addClass("checkbox checked");
}
else {
$(this).removeClass();
$(this).addClass("checkbox");
var i = selected_values_array.indexOf($(this).attr('value'));
if(i != -1) {
selected_values_array.splice(i, 1);
}
// Change the value of a token $mytoken$
}
con
});

//List of table IDs
var tableIDs = ["myTable"];
for (i=0;i<tableIDs.length;i++) {
var sh = mvc.Components.get(tableIDs[i]);
if(typeof(sh)!="undefined") {
sh.getVisualization(function(tableView) {
// Add custom cell renderer and force re-render
tableView.table.addCellRenderer(new CustomRangeRenderer());
tableView.table.render();
tableView.on('rendered', function(view) {
setTimeout(function(){
setCheckAllCheckBox();
},500);
});
});
}
}
var SearchA = mvc.Components.get("SearchA");
var SearchAResults = SearchA.data("results");
SearchAResults.on("data", function () {
resultArray = SearchAResults.data().rows;
searchAFields = SearchAResults.data().fields;
var keyIndex=searchAFields.indexOf(fieldKey);
searchAValues = [];
$.each(resultArray, function (index, value) {
searchAValues[index]=value[keyIndex];
})
});

function setCheckAllCheckBox()
{
// console.log("In setCheckAllCheckBox");
var a = $("["+fieldDataStoreKey+"]");
// console.log(a);
a.html("");
var cls = "checkbox";
if(isSelectAll) {
cls = "checkbox checked";
}
var temp = $('<div>').attr({
"id": "chk-sourcetype",
"value": "All"
}).addClass(cls).click(function () {
if ($(this).attr('class') === "checkbox") {
$(this).removeClass();
$(this).addClass("checkbox checked");
isSelectAll = true;
} else {
$(this).removeClass();
$(this).addClass("checkbox");
isSelectAll = false;
}
checkUnCheckAllCheckboxes();
}).appendTo(a);
$("["+fieldDataStoreKey+"]").parent().removeAttr("class");
$("["+fieldDataStoreKey+"]").removeAttr("data-sort-key");
}
function checkUnCheckAllCheckboxes(){
console.log($('[id^="chk-sourcetype_"]'));
var cls = "checkbox";
selected_values_array = [];
if(isSelectAll) {
cls = "checkbox checked";
$.each(searchAValues, function (index, value) {
selected_values_array.push(value);
})
}
$('[id^="chk-sourcetype_"]').removeClass();
$('[id^="chk-sourcetype_"]').addClass(cls);
}

$(document).ready(function () {
$("#resubmit").on("click", function (e) {
e.preventDefault();
console.log("selectedarray"+selected_values_array);
for (q=0;q<selected_values_array.length;q++) {
var checkbox_query="| makeresults | eval Search_Query=\""+selected_values_array[q]+"\" | fields - _time | outputlookup append=true IIB_Dashboard_lookup.csv"
console.log(checkbox_query)
var epoch = (new Date).getTime();
mySearchManager = new SearchManager({
id : "lookup_search" + epoch,
earliest_time : "-24h",
latest_time : "now",
autostart : true,
search : checkbox_query,
preview : true,
cache : false
});
};
mvc.Components.get("SearchA").startSearch();
query=[];
for (u=0;u<selected_values_array.length;u++) {
query[u]="\""+selected_values_array[u]+",RESUBMIT\""
}
console.log(query.join(" "))
search_query(query.join(" "));
selected_values_array=[];
console.log(selected_values_array);
});
$("#archive").on("click", function (e) {
e.preventDefault();
console.log("selectedarray"+selected_values_array);
for (q=0;q<selected_values_array.length;q++) {
var checkbox_query="| makeresults | eval Search_Query=\""+selected_values_array[q]+"\" | fields - _time | outputlookup append=true IIB_Dashboard_lookup.csv"
console.log(checkbox_query)
var epoch = (new Date).getTime();
mySearchManager = new SearchManager({
id : "lookup_search" + epoch,
earliest_time : "-24h",
latest_time : "now",
autostart : true,
search : checkbox_query,
preview : true,
cache : false
});
};
mvc.Components.get("SearchA").startSearch();
query=[];
for (u=0;u<selected_values_array.length;u++) {
query[u]="\""+selected_values_array[u]+",ARCHIVE\""
}
console.log(query.join(" "))
search_query(query.join(" "));
selected_values_array=[];
console.log(selected_values_array);
});
function search_query (query) {
//var SearchManager = require('splunkjs/mvc/searchmanager');
var epoch = (new Date).getTime();
mySearchManager = new SearchManager({
id : "Soap_test" + epoch,
earliest_time : "-24h",
latest_time : "now",
autostart : true,
search : "| soap1 "+query,
preview : true,
cache : false
});
var confirmationMessage = mySearchManager.on('search:done', function(properties) {
console.log("DONE!\nSearch job properties:", properties.content.eventCount);
return "Job Completed";
});
console.log(confirmationMessage);
var myResults = mySearchManager.data("results");
console.log(myResults);
myResults.on("data", function () {
resultArray_rows = myResults.data().rows;
console.log(resultArray_rows)
tokens.set("mytoken1", resultArray_rows.join());
submittedTokens.set(tokens.toJSON());
console.log(tokens);
});
};
});
})

0 Karma

SplunkTrust
SplunkTrust

@Archana944 

 

I did some correction in your javascript. Can you please try this?

 

require([
'underscore',
'jquery',
'splunkjs/mvc',
'splunkjs/mvc/tableview',
'splunkjs/mvc/simplexml/ready!',
], function(_, $, mvc, TableView) {
    // Access the "default" token model
    var tokens = mvc.Components.get("default");
    var selected_values_array = [];
    var query_array = [];
    var query;
    var fieldKey = "CheckBox";
    var fieldDataStoreKey = "data-sort-key=" + fieldKey;
    var isSelectAll = false;
    var submittedTokens = mvc.Components.get('submitted');
    var mySearchManager = "";
    var SearchManager = require('splunkjs/mvc/searchmanager');
    var CustomRangeRenderer = TableView.BaseCellRenderer.extend({
        canRender: function(cell) {
            console.log("IN render",cell.field);
            return _([fieldKey]).contains(cell.field);
        },
        render: function($td, cell) {
            console.log("checked",cell.value);
            var cls = "checkbox";
            if (isSelectAll) {
                cls = "checkbox checked";
            }
            var a = $('<div>').attr({
                "id": "chk-sourcetype" + cell.value,
                "value": cell.value
            }).addClass(cls).click(function() {
                if ($(this).attr('class') === "checkbox") {
                    selected_values_array.push($(this).attr('value'));
                    $(this).removeClass();
                    $(this).addClass("checkbox checked");
                } else {
                    $(this).removeClass();
                    $(this).addClass("checkbox");
                    var i = selected_values_array.indexOf($(this).attr('value'));
                    if (i != -1) {
                        selected_values_array.splice(i, 1);
                    }
                    // Change the value of a token $mytoken$
                }
            }).appendTo($td);
        }});

        //List of table IDs
        var tableIDs = ["myTable"];
        for (i = 0; i < tableIDs.length; i++) {
            var sh = mvc.Components.get(tableIDs[i]);
            if (typeof(sh) != "undefined") {
                sh.getVisualization(function(tableView) {
                    // Add custom cell renderer and force re-render
                    tableView.table.addCellRenderer(new CustomRangeRenderer());
                    tableView.table.render();
                    tableView.on('rendered', function(view) {
                        setTimeout(function() {
                            setCheckAllCheckBox();
                        }, 500);
                    });
                });
            }
        }
        var SearchA = mvc.Components.get("SearchA");
        var SearchAResults = SearchA.data("results");
        SearchAResults.on("data", function() {
            resultArray = SearchAResults.data().rows;
            searchAFields = SearchAResults.data().fields;
            var keyIndex = searchAFields.indexOf(fieldKey);
            searchAValues = [];
            $.each(resultArray, function(index, value) {
                searchAValues[index] = value[keyIndex];
            })
        });

        function setCheckAllCheckBox() {
            // console.log("In setCheckAllCheckBox");
            var a = $("[" + fieldDataStoreKey + "]");
            // console.log(a);
            a.html("");
            var cls = "checkbox";
            if (isSelectAll) {
                cls = "checkbox checked";
            }
            var temp = $('<div>').attr({
                "id": "chk-sourcetype",
                "value": "All"
            }).addClass(cls).click(function() {
                if ($(this).attr('class') === "checkbox") {
                    $(this).removeClass();
                    $(this).addClass("checkbox checked");
                    isSelectAll = true;
                } else {
                    $(this).removeClass();
                    $(this).addClass("checkbox");
                    isSelectAll = false;
                }
                checkUnCheckAllCheckboxes();
            }).appendTo(a);
            $("[" + fieldDataStoreKey + "]").parent().removeAttr("class");
            $("[" + fieldDataStoreKey + "]").removeAttr("data-sort-key");
        }

        function checkUnCheckAllCheckboxes() {
            console.log($('[id^="chk-sourcetype_"]'));
            var cls = "checkbox";
            selected_values_array = [];
            if (isSelectAll) {
                cls = "checkbox checked";
                $.each(searchAValues, function(index, value) {
                    selected_values_array.push(value);
                })
            }
            $('[id^="chk-sourcetype_"]').removeClass();
            $('[id^="chk-sourcetype_"]').addClass(cls);
        }

        $(document).ready(function() {
            $("#resubmit").on("click", function(e) {
                e.preventDefault();
                console.log("selectedarray" + selected_values_array);
                for (q = 0; q < selected_values_array.length; q++) {
                    var checkbox_query = "| makeresults | eval Search_Query=\"" + selected_values_array[q] + "\" | fields - _time | outputlookup append=true IIB_Dashboard_lookup.csv"
                    console.log(checkbox_query)
                    var epoch = (new Date).getTime();
                    mySearchManager = new SearchManager({
                        id: "lookup_search" + epoch,
                        earliest_time: "-24h",
                        latest_time: "now",
                        autostart: true,
                        search: checkbox_query,
                        preview: true,
                        cache: false
                    });
                }
                mvc.Components.get("SearchA").startSearch();
                query = [];
                for (u = 0; u < selected_values_array.length; u++) {
                    query[u] = "\"" + selected_values_array[u] + ",RESUBMIT\""
                }
                console.log(query.join(" "))
                search_query(query.join(" "));
                selected_values_array = [];
                console.log(selected_values_array);
            });
            $("#archive").on("click", function(e) {
                e.preventDefault();
                console.log("selectedarray" + selected_values_array);
                for (q = 0; q < selected_values_array.length; q++) {
                    var checkbox_query = "| makeresults | eval Search_Query=\"" + selected_values_array[q] + "\" | fields - _time | outputlookup append=true IIB_Dashboard_lookup.csv"
                    console.log(checkbox_query)
                    var epoch = (new Date).getTime();
                    mySearchManager = new SearchManager({
                        id: "lookup_search" + epoch,
                        earliest_time: "-24h",
                        latest_time: "now",
                        autostart: true,
                        search: checkbox_query,
                        preview: true,
                        cache: false
                    });
                };
                mvc.Components.get("SearchA").startSearch();
                query = [];
                for (u = 0; u < selected_values_array.length; u++) {
                    query[u] = "\"" + selected_values_array[u] + ",ARCHIVE\""
                }
                console.log(query.join(" "))
                search_query(query.join(" "));
                selected_values_array = [];
                console.log(selected_values_array);
            });

            function search_query(query) {
                //var SearchManager = require('splunkjs/mvc/searchmanager');
                var epoch = (new Date).getTime();
                mySearchManager = new SearchManager({
                    id: "Soap_test" + epoch,
                    earliest_time: "-24h",
                    latest_time: "now",
                    autostart: true,
                    search: "| soap1 " + query,
                    preview: true,
                    cache: false
                });
                var confirmationMessage = mySearchManager.on('search:done', function(properties) {
                    console.log("DONE!\nSearch job properties:", properties.content.eventCount);
                    return "Job Completed";
                });
                console.log(confirmationMessage);
                var myResults = mySearchManager.data("results");
                console.log(myResults);
                myResults.on("data", function() {
                    resultArray_rows = myResults.data().rows;
                    console.log(resultArray_rows)
                    tokens.set("mytoken1", resultArray_rows.join());
                    submittedTokens.set(tokens.toJSON());
                    console.log(tokens);
                });
            }
        });
    });
0 Karma

Explorer

Thanks @kamleshverma its working,
Sorry to bug you again , but one thing is,
when we check it is getting to array but even when i uncheck it is still not deleting from array.
I have added below code fr that , bt this is nt working for uncheckall option

  SearchB.on('search:done', function(properties) {
               SearchA.startSearch();
               selected_values_array = [];
               tokens.set("mytoken", selected_values_array.join());
    });

Can u pls help me here.

0 Karma

SplunkTrust
SplunkTrust

@vasanthi77

Thanks for enhancing more & more it :). I really appreciate your involvement. Please check my updated javascript code and try it.

0 Karma

Explorer

@kamlesh_vaghela Thanks its working as i expected. sorry fr responding late
Thank you so much once again 🙂

0 Karma

SplunkTrust
SplunkTrust

Glad to help you @vasanthi77

Can you please upvote my any comment which helps you for the learning purpose & accept this answer to close this question??

0 Karma

Explorer

@kamlesh_vaghela Thank you so much for your answer.
Its working as expected.
Can u please let me know where can i learn java scripting for splunk? I want to write all these on my own 😐

Thanks once again

0 Karma

Explorer

@kamlesh_vaghela one thing , I have added a filter to the form to get only some sourcetypes

     <dashboard script="multiselect_table.js" stylesheet="multiselect_table.css">
        <label>Multi-Select Table Rows Example</label>
        <fieldset submitButton="false" autoRun="true">
         <input type="text" token="filter1">
          <label></label>
          <default></default>
         </input>
        </fieldset>
        <row>
          <panel>
            <table id="myTable">
              <title>Panel A</title>
              <search id="SearchA">
                <query>index=_internal |search sourcetype="%$filter1$%"| stats count by sourcetype | eval CheckBox=sourcetype | table CheckBox sourcetype count</query>
                <earliest>-15m</earliest>
                <latest>now</latest>
              </search>
              <option name="count">10</option>
              <option name="drilldown">row</option>
              <drilldown>
                <condition field="*"></condition>
              </drilldown>
            </table>
          </panel>

but when i select check box to check all , All soucretypes are coming as result , I want only filtered one in the result, Can pls u tell me how to do this one

0 Karma

SplunkTrust
SplunkTrust

@vasanthi77

I have updated my answer with respect to your concern. Can you please try and let me know?