I want to enable a button when two text fields have length > 0: How do I refer to these text fields lengths to express this? Seems simple, but its not obvious to me how to refer to the component's and their text (length). I basically want to use FRP to enable/disable button for form submission. These would be "sibling" components I suppose.
问题:
回答1:
If two-way binding is an option, you could do something along these lines:
<input value='{{foo}}'>
<input value='{{bar}}'>
<button disabled='{{ !foo || !bar }}'>submit</button>
This works because the empty string (''
) is falsy in JavaScript, so !foo || !bar
is only false
when both foo
and bar
are non-empty.
回答2:
@Rich Harris: It seems that the problem with the <button disabled="{{ !(''+foo) || !(''+bar) }}">submit</button>
trick is that the button is enabled at the start, because both foo
and bar
are initially undefined
and ''+undefined
gives the string 'undefined'
. The technique also becomes unwieldy if you have several fields with various validation requirements.
As you may know, Angular has a $invalid
that you can apply to a form, e.g., <button ng-disabled="myForm.$invalid">submit</button>
where myForm
is the form's name
attribute. In Ractive, I guess one could write an isvalid
function and then use <button disabled="{{ !isvalid() }}">submit</button>
but that only works for one form (or is there some way to "attach" it to a particular element?).