Eric Brown
Eric Brown

Reputation: 1462

Knockoutjs how to add a required attribute using ternary operator to input

I would ideally like to add a ternary operator to my input to make the input required if a specific shipping carrier is chosen, and optional for all other carriers. Here is what I tried so far:

<input class="input-text" type="text" maxlength="60" name="shipper_number"  attr="id: 'shipper_number_' + method.method_code + '_' + method.carrier_code" data-bind="value: checkoutConfig.quoteData.shipper_number,
                    required: method.carrier_title == 'DHL' ? 'required' : ''" /> //This is the one I tried and it didn't work

I tried adding required field to the data-bind attribute, but it didn't work. I know very little about knockout so I don't even know if I am on the right track with this. Any help is appreciated.

Upvotes: 0

Views: 762

Answers (1)

adiga
adiga

Reputation: 35202

You can use the attr binding. If method.carrier_title is an observable, you need to use () to get the value before comparing it with a string

const viewModel = {
  title: ko.observable('foo'),
  title2: ko.observable('bar')
}

ko.applyBindings(viewModel)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<form>
  Input 1: <input type="text" data-bind='attr:{ required: title() === "foo" }'>
  Input 2: <input type="text" data-bind='attr:{ required: title2() === "notbar"}'>
  <input type="submit">
</form>

Upvotes: 1

Related Questions