Ihor Deyneka
Ihor Deyneka

Reputation: 1409

Knockout Validation preventing click handler for the first time

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

Upvotes: 2

Views: 3104

Answers (2)

Emmanuel
Emmanuel

Reputation: 8632

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>

Upvotes: 0

Anders
Anders

Reputation: 17554

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

Upvotes: 2

Related Questions