Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Required attribute after select

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.

like image 907
Maria Avatar asked Nov 19 '25 07:11

Maria


2 Answers

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');
      }
    }
});
like image 52
Himanshu Upadhyay Avatar answered Nov 20 '25 21:11

Himanshu Upadhyay


You can simply add this one

$("field1").prop('required',false);
like image 20
HD.. Avatar answered Nov 20 '25 22:11

HD..



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!