Choosing specific rows in a kogrid by clicking on a button within a column

My kogrid includes a single column with a view button for each row. I would like to show a popup containing the values of the selected row when the View button is clicked. How can I retrieve the values of the selected row in order to pass them into the popup?

Answer №1

To populate the modal with a selected value, you can extract the row data and assign it as the context of the modal. Below is an example code snippet that retrieves the row data and sets it as the modal's context.

function viewModel() {
  this.currentRowValues = ko.observableArray([]);
  this.gridData = ko.observableArray([{
    name: "Moroni",
    age: 50
  }, {
    name: "Tiancum",
    age: 43
  }, {
    name: "Jacob",
    age: 27
  }, {
    name: "Nephi",
    age: 29
  }, {
    name: "Enos",
    age: 34
  }]);

  // Define button template for detail modal
  this.detailBtnTemplate = '<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#myModal" data-bind="click: $parent.$userViewModel.setModelContext.bind($parent.$userViewModel,$parent)">Detail </button>'

  this.reconciliationGridOptions = {
    data: this.gridData,
    selectedItems: this.currentRowValues,
    afterSelectionChange: function(selectedRow) {

      return true;
    },
    columnDefs: [{
      field: 'name',
      displayName: 'Name'
    }, {
      displayName: 'Action',
      cellTemplate: '<button data-bind="click: $parent.$userViewModel.log.bind($parent.$userViewModel,$parent)">Log</button>'
    }, {
      displayName: 'Detail',
      cellTemplate: this.detailBtnTemplate
    }]
  };

  this.message = "binded context";
  this.modalContext = ko.observable();
};
viewModel.prototype.save = function() {
  alert(ko.toJSON(this.currentRowValues()));
};

//Function that will be binded with the row
viewModel.prototype.log = function(rowData) {
  console.log("row data: ", rowData);
  console.log("entity data: ", rowData.entity);
  //Showing the context binded
  alert(this.message);
};
viewModel.prototype.setModelContext = function(rowData) {
  console.log("entity data: ", rowData.entity);
  this.modalContext({name:ko.observable(rowData.entity.name),age: ko.observable(rowData.entity.age)});
};


ko.applyBindings(new viewModel());
.gridStyle {
  border: 1px solid rgb(212, 212, 212);
  width: 400px;
  height: 300px;
}
.selectedItems {
  border: solid black 1px;
  padding: 10px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdn.lukej.me/kogrid/2.0.6/KoGrid.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdn.lukej.me/kogrid/2.0.6/koGrid.debug.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<div class="gridStyle" id="reconciliationGrid" data-bind="koGrid: reconciliationGridOptions"></div>

<button data-bind="click: save">Save Example</button>
<br/>
<div class="selectedItems" data-bind="foreach: currentRowValues">
  <span data-bind="text:ko.toJSON($data)"></span>
</div>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-bind="with: modalContext">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Detail Person</h4>
      </div>
      <div class="modal-body">
        <label for="name">Name</label>
        <input id="name" type="text" data-bind="value: name" />
        <label for="age">Age</label>
        <input id="age" type="number" data-bind="value: age" />
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to access an element within a function triggered by an event listener

Is there a way to dynamically add a class to an element with a specific class when it is clicked? Specifically, I want to target elements with the "date" class and give them an additional class upon click. $(".date").on("click", function() { // Code t ...

Using TypedArray as a parameter in a Cordova plugin

I've been working on a plugin specifically for Cordova 3.3. Within my JavaScript code, I'm in the process of downloading a PDF file which is being stored as a uInt8Array. download: function ( ) { var xhr = new XMLHttpRequest(); ...

Unlocking the AngularJS variable within the template script

My controller code: $scope.totals = totals; In the template, I am able to successfully inject HTML using this code: {{totals}} However, my goal is to access the totals variable in a script within the template. Here's what I attempted: <script& ...

Enhancing the functionality of localStorage

I am attempting to append a value to a key within the HTML5 localStorage. Take a look at my code below: var splice_string = []; splice_string += "Test value"; var original = JSON.parse(localStorage.getItem('product_1')); origina ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

Challenges with resizing windows in jQuery

I'm currently working on optimizing my jQuery code and everything seems to be running smoothly so far: jQuery $(document).ready(function(){ $(".fadeinbg").click(function(){ $("#content").fadeIn(); }); var height = $(window).height() ...

What could be causing my Wikipedia opensearch AJAX request to not return successfully?

I've been attempting various methods to no avail when trying to execute the success block. The ajax request keeps returning an error despite having the correct URL. My current error message reads "undefined". Any suggestions on alternative approaches ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Enhance my code to eliminate repetitive elements

Check out this unique plant array: export const uniquePlants = [ { name: 'monstera', category: 'classique', id: '1ed' }, { name: 'ficus lyrata&ap ...

How to eliminate an item from an array using index in JavaScript with jQuery

In order to remove a specific array added in an object by index, I would like the functionality where when a user clicks on a button, it removes the corresponding array. Here's what I have in mind: HTML: <button>1</button> <button>2 ...

Convert image buffer to string using Mongoose getter?

I have developed a basic node backend application modeled after eBay. I am now working on creating a react frontend app to complement it. Within the app, users can list items for sale and include a photo with their listing. The item information is stored ...

Executing a function when clearing an autocomplete textfield in Material-UI

Currently, I am working with a material-ui autocomplete text field in order to filter a list. My goal is to have the list repopulate back to its original form when the user deletes the text and presses the enter key. After my research, it seems like the ...

The backend function of an aspx page is failing to execute when triggered by a $.ajax request

Currently, I am facing an issue with a web form IndexPage.aspx. The script in this front-end code makes an ajax call to a code-behind function. Take a look at the code snippet below: $.ajax({ type: "POST", url: &apos ...

Switching up the image using a dropdown selection menu

I am struggling with updating an image based on the selection made in a dropdown menu. I am quite new to javascript, so I believe there might be a simple issue that I am overlooking. Here is my attempt at doing this: JS: <script type="text/javascript" ...

Tips for deactivating the highlight on a previously selected menu item when clicking on the next menu option in Angular.js

In my pages, I have a menu where the landing page menu is initially highlighted. However, when I move to the next menu, the previous landing page highlight remains instead of being removed while swapping the menu. I am using Angular.js and angular ui-route ...

Issue "A system error of type 'System.IO.IOException' that was not properly addressed was encountered in mscorlib.dll"

I encountered a specific error message and need help resolving it: An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll Additional information: The process cannot access the file because it is being used by another pro ...

Is it possible to delay the loading of a page using location.href?

Trying to determine when a page has finished loading using location.href. Currently, my code is set up like this and I want certain events to occur once the page is fully loaded. I attempted using $.get but encountered issues with my existing implementatio ...

Creating multiple unique custom attributes for a specialized HTML element

Creating getter/setter methods for a custom attribute on a custom HTML element is quite simple: customElements.define('custom-el', class extends HTMLElement { static get observedAttributes() { return ['customAttr'] ...

Update the label on a webpage using Selenium's JavaScriptExecutor

We are currently working on a Japanese web application and are experimenting with a unique method to convert Japanese labels into English. Here is the approach we are using (though unsure if it's correct): Approach (using Selenium): Open the webpag ...

Is it possible to add a click event to a table row that contains an input checkbox, without interfering with the ability to click the checkbox itself?

I have a table: <table> <tr> <td>Something</td> <td>Something Else</td> <td><input type='checkbox' value='clickme' id='yes'></td> </tr> When a user ...