Rob Bowman
Rob Bowman

Reputation: 8741

Not able to click table head element

I have tried to use the knockout filter and sort functionality from the following jsfiddle: http://jsfiddle.net/rrahlf/EZUEF/6/

The sorting is working great but my table headings are not "clickable". Could anyone please say why?

Here's my index.cshtml

@model PagedList.IPagedList<TVS.ESB.BamPortal.Website.Models.LookupViewModel>
@using System.Web.Script.Serialization
@{
    ViewBag.Title = "Cross Ref";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>@ViewBag.Title</h2>
@{  string data = new JavaScriptSerializer().Serialize(Model); }

<div id="CrossRefDiv">

    <p>Number of rows <span data-bind="text: lookups().length"> </span></p>

    <div data-bind="foreach: filters">
        <input type="button" data-bind="click: $parent.setActiveFilter, value: title" />
    </div>

    <table class="table table-striped">
        <thead>
            <tr data-bind="foreach: headers">
                <th data-bind="click: $parent.sort, text: title"></th>
            </tr>
        </thead>
        <tbody data-bind="template: { name: 'rowTemplate', foreach: filteredLookups }"></tbody>
    </table>

    <form data-bind="submit: save">
        <button data-bind="click: addRow">Add Row</button>
        <button data-bind="enable: lookups().length > 0" type="submit">Submit</button>
    </form>

    <script type="text/html" id="rowTemplate">
        <tr>
            <td><input data-bind="value: SourceSystem" /></td>
            <td><input data-bind="value: SourceField" /></td>
            <td><input data-bind="value: SourceValue" /></td>
            <td><input data-bind="value: TargetSystem" /></td>
            <td><input data-bind="value: TargetValue" /></td>
            <td><a href="#" data-bind="click: function() { vm.removeRow($data) }">Delete</a></td>
        </tr>
    </script>

</div>

@section Scripts {
    <script src="~/KnockoutVM/CrossRef.js"></script>

    <script type="text/javascript">
        var vm = new ViewModel(@Html.Raw(data));
        ko.applyBindings(vm, document.getElementById("CrossRefDiv"));
    </script>
}

And my CrossRef.js:

function ViewModel(data) {
    var self = this;

    //remove 1st element from array because this holds filter data which the filter Partial view 
    //will have already dealth with
    data.splice(0, 1);
    self.lookups = ko.observableArray(data);

    //start of filter & sort
    self.headers = [
        { title: 'Source System', sortPropertyName: 'sourceSystem', asc: true, active: false },
        { title: 'Source Field', sortPropertyName: 'sourceField', asc: true, active: false },
        { title: 'Source Value', sortPropertyName: 'sourceValue', asc: true, active: false },
        { title: 'Target System', sortPropertyName: 'targetSystem', asc: true, active: false },
        { title: 'Target Value', sortPropertyName: 'targetValue', asc: true, active: false }
];
    self.filters = [
        { title: 'Show All', filter: null },
        { title: 'SCIP', filter: function (item) { return item.sourceSystem == 'SCIP'; } },
        { title: 'CCE', filter: function (item) { return item.sourceSystem == 'CCE'; } }
    ];

    self.activeSort = ko.observable(function () { return 0; }); //set the default sort
    self.sort = function (header, event) {
        //if this header was just clicked a second time
        if (header.active) {
            header.asc = !header.asc; //toggle the direction of the sort
        }
        //make sure all other headers are set to inactive
        ko.utils.arrayForEach(self.headers, function (item) { item.active = false; });
        //the header that was just clicked is now active
        header.active = true;//our now-active header

        var prop = header.sortPropertyName;
        var ascSort = function (a, b) { return a[prop] < b[prop] ? -1 : a[prop] > b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
        var descSort = function (a, b) { return a[prop] > b[prop] ? -1 : a[prop] < b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
        var sortFunc = header.asc ? ascSort : descSort;

        //store the new active sort function
        self.activeSort(sortFunc);
    };

    self.activeFilter = ko.observable(self.filters[0].filter);//set a default filter    
    self.setActiveFilter = function (model, event) {
        self.activeFilter(model.filter);
    };

    self.filteredLookups = ko.computed(function () {
        var result;
        if (self.activeFilter()) {
            result = ko.utils.arrayFilter(self.lookups(), self.activeFilter());
        } else {
            result = self.lookups();
        }
        return result.sort(self.activeSort());
    });
    //end of filter & sort

    self.removeRow = function (row) {
        this.lookups.remove(row);
    }

    self.addRow = function () {
        this.lookups.push({ SourceSystem: "", SourceField: "", SourceValue: "", TargetSystem: "", TargetField: "", TargetValue: "" });
    }

    self.save = function () {
        var data = ko.toJS(this.lookups);


        $.ajax({
            type: "POST",
            url: location.href,
            data: ko.toJSON(data),
            contentType: 'application/json',
            async: true
        });
    }



}

Upvotes: 0

Views: 63

Answers (1)

Adrian
Adrian

Reputation: 1587

I'm not quite sure if this is what you mean with "clickable", but here is a modified fiddle from the one you gave which adds a class to the current clicked table header (current clicked class is bold then others are normal).

Fiddle here.

What i did here is in the css made the th font weight to normal, and add a class called current which gives bold font weight.

th{        
   cursor:pointer; 
   font-weight: normal;   
}    
.current{ 
    font-weight: bold;
}

Then made the active property of header item as an observable.

self.headers = [
  {title:'First Name',sortPropertyName:'firstName', asc: true, active: ko.observable(false)},
  {title:'Last Name',sortPropertyName:'lastName', asc: true, active: ko.observable(false)},
  {title:'Age',sortPropertyName:'age', asc: true, active: ko.observable(false)}
];

Then modified sort function so that active will be treated as an observable.

self.sort = function(header, event){
    //if this header was just clicked a second time
    if(header.active()) {
        header.asc = !header.asc; //toggle the direction of the sort
    }
    //make sure all other headers are set to inactive
    ko.utils.arrayForEach(self.headers, function(item){ item.active(false); } );
    //the header that was just clicked is now active
    header.active(true);//our now-active header

    var prop = header.sortPropertyName;
    var ascSort = function(a,b){ return a[prop] < b[prop] ? -1 : a[prop] > b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
    var descSort = function(a,b){ return a[prop] > b[prop] ? -1 : a[prop] < b[prop] ? 1 : a[prop] == b[prop] ? 0 : 0; };
    var sortFunc = header.asc ? ascSort : descSort;

    //store the new active sort function
    self.activeSort(sortFunc);
};

Lastly added a css binding in the th.

 <th data-bind="click: $parent.sort, text: title, css: {current: active}"></th>

You can also add an identifier in your table header if it is in ascending or descending, just same steps, add a css class and make the asc an observable.

Upvotes: 1

Related Questions