BobbyJones BobbyJones - 4 months ago 5
HTML Question

Enabling the Search button when the user types or makes a selection

I'd like to write some sort of function that would allow functionality to be added to enable the "Search" button when the user has either:


  • made a selection in either of the select boxes

  • or has typed a value into one of the input boxes on the page



Vice-versa, if either of the select or input boxes are empty, then disable the search button.

I apologize in advance and would like to say that I am newcomer to JavaScript and I am not sure where to begin, other examples on the web are confusing to me and do not seem to fit my needs.

Here is the HTML Markup:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
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" disabled>
</body>
</html>

Answer

You should use the jQuery change() function, like this:

$("select#fruits").change(function(){
   $('input[type="button"]').removeClass("disabled");
});

Give your input the disabled class which disables the button like:

.disabled{
     pointer-events: none;
}

The upper code removes this class when someone is selecting something at your select input.

UPDATE:

$("select#fruits").change(function(){
    $("input[type="button"]").removeAttr("disabled");
});

This removes the "disabled" attribute for your button.

Comments