Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable button when input field is not empty

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.

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() });

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.

like image 350
SpringLearner Avatar asked Jan 22 '26 23:01

SpringLearner


2 Answers

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);

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

like image 199
Oliver Weichhold Avatar answered Jan 24 '26 13:01

Oliver Weichhold


You could use JQuery to solve this, by doing the following:

HTML Markup:

<button id="my" type="button" disabled="true">My Button</button>
<input id="hi" type="text" name="hi" />

JQuery Script:

if (allFields == valid) {
    $('#my').prop('disabled', false);
}

That should make your life a whole lot easier. Let me know if not.

like image 38
Stan Cromlish Avatar answered Jan 24 '26 14:01

Stan Cromlish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!