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.

Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51
Maria
  • 760
  • 2
  • 9
  • 22

4 Answers4

5

You can simply add this one

$("field1").prop('required',false);
HD..
  • 1,456
  • 3
  • 28
  • 48
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');
      }
    }
});
Himanshu Upadhyay
  • 6,558
  • 1
  • 20
  • 33
  • 1
    Yeap that worked, just had to to change && to || cause I just wanted one of these fields... Cheers – Maria Sep 21 '17 at 09:45
1

Pseudo code to do this:

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

Hope this helps!

Tavish Aggarwal
  • 1,020
  • 3
  • 22
  • 51
1

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

Akshit Ahuja
  • 337
  • 2
  • 15