Question

I have a table like below. the user is supposed to type the address info into the third column. If it's empty, then I added a styling

 <tbody data-bind="foreach: people">
      <tr>
          <td data-bind="text: id"></td>
          <td data-bind="text: name"></td>
           <td><input type="text" style="width:100%"  data-bind="css:{warningStyle: address.length == 0 }, value: address"/></td>

          </tr>                                   
 </tbody>

To test it, Here's my code about people in js

people = ko.observableArray([{id:'1', name:'a1', address:'aaa'},{id:'2', name:'a2', address:''}])

When I first load the page, it works as supposed. the 1st person has no styling applied and the 2nd person has the styling (because the address is empty).

Now it I type some address for the 2nd person, it still has the css style applied. My question is why? Shouldn't it has the css style removed becasue the address is not empty anymore? How do I fix this?

Was it helpful?

Solution

That happened because address property is not observable. You can fix it using mapping plugin or without it in next way

var data = [{id:'1', name:'a1', address:'aaa'},{id:'2', name:'a2', address:''}];

function Item(id, name, address) {
    this.name = ko.observable(name);
    this.id = ko.observable(id);
    this.address = ko.observable(address);
}

//do some basic mapping (without mapping plugin)
var mappedData = ko.utils.arrayMap(data, function(item) {
    return new Item(item.id, item.name, item.address);
});

ko.applyBindings(mappedData);

JSFIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top