Search code examples
jqueryhtmlformsattributesrequired

How can I add the 'required' attribute to input on change of textarea?


I need to add the required attribute to an html select (toDept) under the condition that a textarea (orderComments) has text typed in it. Below is my code... What am I missing? Do I need to run my jquery on a change event or something?

    $(document).ready(function() {
          if ($('#textareaId').val() != '') {
            $("#selectId").attr('required', true);
          }
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="textareaId"></textarea>

<select id="selectId">
  <option value=""></option>
  <option value="opt1">opt1</option>
</select>

Thanks for your time!


Solution

  • You need to run the code when the textarea changes:

    var textarea = $('#textareaId');
    var select = $('#selectId');
    
    var addOrRemoveRequiredAttribute = function () {
        if (textarea.val().length) {
            select.attr('required', true);
        }
        else {
            select.attr('required', false);
        }
    };
    
    // Run now
    addOrRemoveRequiredAttribute();
    
    // And when textarea changes
    textarea.on('change', addOrRemoveRequiredAttribute);