s

knockout viewmodel two way binding input text to javascript variable edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 03 February 2021 | 1228

In my asp .net MVC application I am using knockout js for data binding. I have an input and a search button, then the user clicks on the search button I want to copy the text typed in the input element to a javascript variable. The problem was that I was getting an empty string. This was the code I was using.

<input class="form-control" data-bind="text: searchstring">
<button class="btn btn-style" onclick="search();">search</button>

var viewModel = {
  searchstring: ko.observable(),
}

function search()
{
  console.log(viewModel.searchstring());
}


Solution

The error was caused because I was using the wrong binding. I had to change the data-bind from text to view

<input class="form-control" data-bind="value: searchstring">