如何在输入字段不为空时启用按钮 [英] How to enable button when input field is not empty

查看:28
本文介绍了如何在输入字段不为空时启用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,其中有一个表单,如果所有字段都已填写,则只会启用提交按钮,否则提交按钮将处于禁用状态.

I have a requirement in which there is a form and if all the fields are filled then only submit button will be enabled else the submit button will be in disabled state.

这个小提琴适用于 1 个输入字段:

This fiddle works fine for 1 input field:

<button data-bind="enable: my">My Button</button>
<input type="text" name="hi" data-bind="value:my" />

ko.applyBindings({ my: ko.observable() });

但是,我不知道如何为 多个 输入字段执行此操作,例如 这个小提琴.如果有大约 10 个输入字段,那么当且仅当所有字段都被填写时如何启用提交按钮.

However, I don't know how to do this for multiple input fields like as in this fiddle. If there are some 10 input fields then how to enable the submit button if and only if all the fields are filled up.

推荐答案

HTML

<button data-bind="enable: isFormValid">My Button</button>
<input type="text" data-bind="value: text1, valueUpdate: 'keyup'" />
<input type="text" data-bind="value: text2, valueUpdate: 'keyup'" />
<input type="text" data-bind="value: text3, valueUpdate: 'keyup'" />
<input type="text" data-bind="value: text4, valueUpdate: 'keyup'" />

JS:

var vm = {
    text1: ko.observable(""),
    text2: ko.observable(""),
    text3: ko.observable(""),
    text4: ko.observable("")
}

vm.isFormValid = ko.computed(function() {
    return this.text1() && this.text2() && this.text3() && this.text4();
}, vm);

ko.applyBindings(vm);

查看更新的 JSFiddle.解决 viewmodel 属性间依赖关系的关键是 Knockout 的计算 observables.

See updated JSFiddle. The key to solving viewmodel inter-property dependencies is Knockout's computed observables.

这篇关于如何在输入字段不为空时启用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆