2013-03-26 83 views
1

我想在用户按钮点击时显示错误消息(以防用户打开页面并直接点击按钮)。 但只有用户编辑字段时可见状态才能工作 如何触发方法以更改可见状态?按钮点击击倒更改范围可见状态

<body> 
    <input type="text" data-bind="value: can" id="txtcan" />       
         <span ID="lblCANerror" data-bind="visible:(viewModel.can()=='')" class="error">Mesasage 1</span>      
              <input type="text" data-bind="value: login" id="txtusername" /> 
         <span ID="lblUsernameError" data-bind="visible:(viewModel.login()=='')" class="error">Mesasage 2</span> 

         <input type="password" data-bind="value: password" name="txtpassword" /> 
         <span ID="lblPasswordError" data-bind="visible:(viewModel.password()=='')" class="error">Mesasage 3</span> 

         <button ID="lnkLogin" data-bind="click: ClickBtn"> Click</button>     

</body> 

<script type='text/javascript'> 
var ViewModel = function() { 
     this.can = ko.observable(); 
     this.login = ko.observable(); 
     this.password = ko.observable(); 
     this.isValidForm = ko.computed(function() { 
      return ($.trim(this.can) != "") && ($.trim(this.login) != "") && ($.trim(this.password) != ""); 
     }, this); 
    this.ClickBtn = function(data, e) 
    { 
     if (!this.isValidForm()) 
      { 

      e.stopImmediatePropagation(); 
      }; 
    }; 
    }; 

    var viewModel = new ViewModel(); 
    ko.applyBindings(viewModel); 



</script> 
    <style type='text/css'> 
    .error 
{ 
    color: #FF0000;  
} 
    </style> 

我不想写来写手动变化幅度可见状态(如IF)(当时span.show)代码,是否可以只使用knockoutjs FW? 我试过用JQuery订阅事件,但结果是一样的。

$().ready(function() { 
     $("#lnkLogin").click(function (event) { 
      if (!viewModel.isValidForm()) {     
       event.preventDefault(); 
      };  
     }) 
    }); 

谢谢。

回答

1

删除不需要的用户定义错误。

选项1(推荐)

1)导入ko validation js

2.)延伸验证

this.can = ko.observable().extend({required:true}); 

3.)设定的初始显示的验证错误味精==假

4.)设定值== true将显示错误

Check this fiddle how to show validation error msg when button click

选项2

1)添加另一个观察的

this.showError = ko.observable(false); 

2)修改条件点击

data-bind="visible:(can()=='' && showError())" 

3)变更

$().ready(function() { 
    $("#lnkLogin").click(function (event) { 

     //check contions here 
     if(!true){ 
      viewModel.showError(true); // to show error msg 
      } 

     if (!viewModel.isValidForm()) {     
      event.preventDefault(); 
     };  
    }) 
}); 
+0

是的,这是正确的方式我同意。但如何在我的情况下做到这一点? – 2013-03-26 08:59:56

+0

@ a3code答案能解决您的问题吗? – nav0611 2013-03-26 09:30:27

+0

我很确定它会。但由于某种原因,我需要尝试在我的情况下解决它。 – 2013-03-26 09:32:06