3

How can I conditionally set a required attribute in an input ?

<input type="text" required />

The required attribute has not value. Just by being present will be taken as required. So required="false" will make some scripts fail.

I was not able to find anything like it in the docs. The closer I got was the disabled binding.

Alvaro
  • 37,936
  • 23
  • 138
  • 304

1 Answers1

7

Knockout is smart enough to remove attributes whose bound value is false when they are bound with the attr binding. Inspect the input below. It will switch between required="true" and required not appearing.

vm = {r: ko.observable(false)}
ko.applyBindings(vm);
setInterval(() => vm.r(!vm.r()), 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input data-bind="attr: {required: r}" />
Kyeotic
  • 19,153
  • 10
  • 64
  • 125
Roy J
  • 37,999
  • 5
  • 58
  • 88