3

I have this search bar:

enter image description here

I dont want user to make a full search because there are like 40000 records on database and it will take a while.

So I split that in 2 options and I have the first field as required,

<select required name="field1" id="destination" tabindex="-1" class="select2-hidden-accessible" aria-hidden="true"> <option name="country" value="">Field</option> <option name="country" value="%">Any destination</option> </select>

But I need to remove that required field if they choose Field 2 or Field 3.

So I think best practice is to do something like onchange and remove that required with something like this .removeAttribute("required")?

Whats the easiest way to do that? Vanilla or JQuery? I am a beginner on JavaScript so any feedback would be helpful.

4

4 Answers 4

5

You can do like this using jquery: (Assuming that field2 and field3 are id of those dropdown fields.)

$(document).ready(function(){
    var field2 = '';
    var field3 = '';
    $('#field2').on('change',function(){
        field = $(this).val();
        removeRequired();
    });
    $('#field3').on('change',function(){
        field3 = $(this).val();
        removeRequired();
    });
    function removeRequired(){
      if(field2 != '' && field3 != '')
      {
          $('#destination').removeAttr('required');
      }
    }
});
1
  • 1
    Yeap that worked, just had to to change && to || cause I just wanted one of these fields... Cheers
    – Maria
    Sep 21, 2017 at 9:45
5

You can simply add this one

$("field1").prop('required',false);
1

Pseudo code to do this:

if(field2.value || field3.value) {
     $("field1").removeAttr("required");
}

Hope this helps!

1

You can either use jquery removeAttr function or use javascript removeAttribute function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.