Pratik Bothra
Pratik Bothra

Reputation: 2694

Enable form field dependent on another form field's value?

I have a form in which I want to enable SKU (remove disabled), only if Product Id has some value. If Product id's empty I want SKU to remain disabled.

Should I be associate the onChange event with Product Id?

<div class="advancedSearchFormField">
      <span class="advancedSearchFormlabel">Product Id</span>
      <%= text_area_tag('filters[product_id]',filter_params['product_id'],:rows=>10) %>
</div>

<div class="advancedSearchFormField">
      <span class="advancedSearchFormlabel">SKU</span>
      <%= text_area_tag('filters[sku]',filter_params['sku'],:rows=>10, :disabled => true) %>
 </div>

Upvotes: 1

Views: 2260

Answers (1)

alexP
alexP

Reputation: 3765

Yes, you should use addEventListener with your product_id-Element. You can do it this way:

(function () {
    var product_id = document.getElementById('product_id');
    product_id.addEventListener('blur', triggerInput, false);
    product_id.addEventListener('keyup', triggerInput, false);
})();

function triggerInput() {
    var sku = document.getElementById('sku');
    sku.disabled = (this.value !== "" ? '' : 'disabled');
}

Here is the DEMO

Upvotes: 2

Related Questions