Add the values of the button input to a observable array with the help of Knockout

Currently, I am embarking on a task where I must carefully select the values of various buttons and then utilize two-way data binding to display them accordingly. The initial code snippet that I am working with is presented as follows:

<table class="table">
    <tr>
        <td><input type="button" value="1" data-bind="click: addNumber"></td>
        <td><input type="button" value="2" data-bind="click: addNumber"</td>
        <td><input type="button" value="3" data-bind="click: addNumber"></td>
        <td><input type="button" value="4" data-bind="click: addNumber"></td>
        <td><input type="button" value="5" data-bind="click: addNumber"></td>
        <td><input type="button" value="6" data-bind="click: addNumber"></td>
        <td><input type="button" value="7" data-bind="click: addNumber"></td>
        <td><input type="button" value="8" data-bind="click: addNumber"></td>
        <td><input type="button" value="9" data-bind="click: addNumber"></td>
        <td><input type="button" value="10" data-bind="click: addNumber"></td>
    </tr>
</table>

Furthermore, my view model has been set up like this:

function viewModel(){
        var self = this;

        self.column = ko.observableArray();

        self.addNumber = function() {
            self.column.push(...);
            console.log(self.column());
        }  
    }

ko.applyBindings(new viewModel());

The main challenge I am facing at the moment involves crafting the addNumber function so that upon clicking a button, its respective value seamlessly integrates into the column array.

Answer №1

When using a click binding in a function, the contextual data is passed as arguments. Since you are rendering a list of numbers, it would be more appropriate to use foreach as well. You can try something like this:

function viewModel(){
  var self = this;
  
  self.nrs = ko.observableArray([1,2,3,4,5,6,7,8,9,10]);

  self.column = ko.observableArray();

  self.addNumber = function(data) {
    self.column.push(data);
    console.log(self.column());
  }  
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

Column: <strong data-bind="text: column"></strong>.

<table class="table">
  <tbody data-bind="foreach: nrs">
    <tr>
      <td><input type="button" data-bind="value: $data, click: $parent.addNumber"></td>
    </tr>
  </tbody>
</table>

If you prefer to stick to your original code, that's also possible. In that case, you need to specify the argument for knockout to pass by using an anonymous function, like so:

<td>
  <input type="button" value="1" data-bind="click: function() { addNumber(1); }">
</td>

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

The implementation of reflux involves creating a shared component, where the data from the final component will overwrite all existing data

Dear friends, I have been facing a problem for a week that I need your help with. I have used React and Reflux to build a common component. I have used props to set different values for each component, but unfortunately, it is not working as expected. T ...

Tips for transferring information from controller JavaScript to view JavaScript within AngularJS

Currently, I am working on an angularJS application where I retrieve data from a REST service within the controller. The retrieved data is then passed to the view using $scope. However, I encountered an issue when trying to use this data in my in-page Java ...

Executing PHP code and then triggering an Ajax callback

Looking to implement an alert message using the sweetalert plugin. I have a page that displays 10 products on the index page, each with a link (or form) containing data to send to a PHP script. For example: script.php?id=x&b=x&c=z The HTML includ ...

Struggling to set up a Node three.js website on a server, looking for guidance on the process

I am encountering an issue with uploading my files to the public_html folder on the server. The application consists of an HTML file, a three.js JavaScript file, and other supporting files. To run the application, I need to type "npm i" and then "npm run d ...

Is there a way to use a button to delete items stored in localStorage?

I am trying to create a button that will clear the local storage for a user using localStorage.clear();, but it is not working as expected. Unfortunately, if you check out the demo, you'll see that it doesn't work properly. Here's the demo ...

How can you use JavaScript to swap out a character in various elements sharing the same class?

My webpage contains multiple paragraphs with the same class name. I need to remove a specific character from all of them. My attempt at using jQuery is as follows: var str = $(".foo").html; var res = str.split(" ").join(""); $(".foo").html = res; ...

D3.js dynamically adjusts the font size of node text based on the quantity of node text present within the setup

In my family of nodes, there is one parent with 10 children. In the future, this number may increase to 50 or even more... I would like the font size of the text node to automatically decrease as the number of nodes increases. XXX.append('text' ...

Refreshing jQuery dataTable following AJAX completion

I encountered an issue when trying to reload my dataTable after performing a simple delete Ajax process. Initially, the dataTable is initialized and functions correctly as required upon page load. However, upon deleting a specific entry (row) using a butto ...

Unable to upload file to firebase storage - encountering technical issues

After following the documentation on firebase storage, I still can't seem to get my file upload to work properly. Using react, my goal is to successfully upload a file to firebase storage. However, I keep encountering an error message: TypeError: th ...

Guide on using Fetch API to send a request to a PHP file using the POST method

Hey everyone, I've recently started delving into the world of PHP and I encountered an issue while attempting to send a post request from my JavaScript file to my PHP file using the Fetch API. Upon making the request in my console, I received the foll ...

Set a maximum height for an image without changing its width dimension

I am facing an issue with an image displayed in a table. The image is a graph of profiling information that can be quite tall (one vertical pixel represents data from one source, while one horizontal pixel equals one unit of time). I would like to set a ma ...

Creating head tags that are less bouncy

After running my code, I noticed that the headlines didn't transition smoothly - they seemed to jump rather than flow seamlessly. To address this issue, I attempted to incorporate fadeIn and fadeOut functions which did improve the smoothness slightly. ...

Unable to show message upon form submission with ajax

I'm attempting to use AJAX to submit a form in CodeIgniter. The form values are being saved in the database, but the response set in the controller isn't displaying in the console.log or alert within the AJAX code. Form Code <form class=" ...

Tips on using the ref attribute in Vue.js to focus on an input element

In my Vue.js component for 2FA, I have implemented the following structure: <template> <div :class="onwhite ? 'on-white' : ''"> <input :id="`n1`" ref="n1" v-model=&quo ...

Unable to extract properties from event.body

I'm encountering an issue where I am unable to destructure from event.body. exports.handler = async (event, context) => { const { items } = event.body; const allItems = await getProducts(); return { statusCode: 200, bod ...

Struggling with generating forms using AJAX, Javascript, and HTML depending on the selection made from a drop-down menu

I am in need of a simple web form for work submissions within my organization. These submissions will fit into 4 Categories, each requiring unique information. Currently, I have a basic form set up with fields such as Requested Name, Requested Date, Acquis ...

Ways to adjust the height of an element using the ::before selector in javascript

Within the realm of styling, there exists an element adorned with the .bg class. Its aesthetic instructions are described as follows: .bg { width:100%; } .bg:before { position: absolute; content: ''; background: rgba(0,0,0,0.5) ...

"Utilize JavaScript to detect both the loading and unloading events on a webpage

I attempted to capture the window.open onload and onunload events. The issue arises when I use URLs from other domains. For example: When the URL is for the same page, both events trigger as desired. window.open("/") View PLUNKER with same page URL .. ...

Troubleshooting: Issues with JQuery and setTimeout() functionality

While using JQuery to monitor key presses for an HTML game, I encountered an issue where adding the jquery code to my gameloop resulted in an error message stating that keydown was not defined. <html> <head> //...Included JS files ...

Stop Bootstrap form controls from displaying a focus glow when clicked

A virtual directory has been created where users have the ability to change file and directory names. Users can only edit names by double-clicking: <input type="text" class="form-control border-0 p-0 mb-1" ...