BobbyJones BobbyJones - 4 months ago 11
HTML Question

Using Javascript to check form elements and enabling/disabling the search button

I need your help,

Using javascript, how could I add some sort of data form validation that would be two-fold:

1st Event, [OnKeyUp] attached to all of the input boxes

2nd Event, [OnChange] attached to all of the select boxes

Typical User Scenarios

If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }

If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }

<!DOCTYPE html>

<html>

<head></head>

<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>

</html>

Answer

var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
    validate();
});
$('input').keyup(function(){
    validate();
});
function validate(){  
   if(($(veggie).val()!='' || $(number).val()!='') &&
       $(car).val()=='' && $(fruits).val()==''){
           $('#search').prop('disabled',false);
   }else if($(veggie).val()=='' && $(number).val()=='' &&
          ($(car).val()!='' || $(fruits).val()!='')){
           $('#search').prop('disabled',false);
   }else{
     $('#search').prop('disabled',true);
   }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
 <select id="car">
  <option value=""></option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<br><br>
Fruits
 <select id="fruits">
  <option value=""></option>
  <option value="apple">apple</option>
  <option value="banana">banana</option>
  <option value="pear">pear</option>
  <option value="strawberry">strawberry</option>
  <option value="mango">mango</option>
  <option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>

Comments