2
votes

It seems that knockout validation plugin somehow prevents from executing click handlers. Here is my simplified code.

HTML:

<div>
    <input type="text" data-bind="value: code" />
    <button data-bind="click: execute">VALIDATE</button>
</div

Javascript:

<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        var ViewModel = function () {
            var self = this;
            this.code = ko.observable();
            this.code.extend({ required: true });
            this.execute = function () {
                if (self.code.isValid()) {
                    alert("SUCCEED");
                }
                else {
                    self.code.valueHasMutated(); //just to show error message
                    alert("FAILED");
                }
            };
        };

        ko.applyBindings(new ViewModel());
    });
</script>

My scenario:

  1. Load page
  2. Click VALIDATE - error message appears and alert shows FAILED
  3. Enter any text into input and immediately click VALIDATE - error message disappears, but no alert shown.
  4. Click VALIDATE again - only now alert can be seen with SUCCEED text.

How can this be fixed so the VALIDATE button will work correctly from the first click?

Thanks, Ihor

2

2 Answers

2
votes

3) You never click the button :D

What happens is that when you lose focus from the field it validates the field and the text is removed making the button change position and your click misses the button

http://jsfiddle.net/s2bbd/

This one works like you suspect http://jsfiddle.net/s2bbd/1/

Stackoverflow wont let me post this without code
0
votes

Another way to validate before click is to use the mouseover to blur the current element.

<button data-bind="click: execute" onmouseover="document.activeElement.blur();">VALIDATE</button>