I am trying to use the code below so website users have the option to select which database they'd like to search from a list of drop-down menu options. The code works just fine, but users are able to submit a search when the drop-down menu is set to the default selection which results in an error. I only want users to be able to submit a search if they select Option 1, Option 2, etc. from the drop-down menu.
Is there a way to accomplish this? Thanks in advance!
<script type="text/javascript">
function dosearch() {
var sf=document.searchform;
var submitto = sf.sengines.options[sf.sengines.selectedIndex].value + escape(sf.searchterms.value);
window.location.href = submitto;
return false;
}
</script>
<form name="searchform" onSubmit="return dosearch();">
Search:
<select name="sengines">
<option value="" disabled selected>Select an option by category</option>
<option value="">Option 1</option>
<option value="">Option 2</option>
<option value="">Option 3</option>
<option value="">Option 4</option>
</select>
For:
<input type="text" name="searchterms">
<input type="submit" name="SearchSubmit" value="Search">
</form>
First, you should assign different values to each dropdown options. Right now, all options have the same value "", so you can not differentiate among selected options.
<option value="option_0" disabled selected>Select an option by category</option>
<option value="option_1">Option 1</option>
<option value="option_2">Option 2</option>
<option value="option_3">Option 3</option>
<option value="option_4">Option 4</option>
In dosearch() function, check if the selected option is different than option_0. If it is, then perform the search. If it is not, alert the user that he should select the option from dropdown first.
function dosearch() {
const sf = document.searchform;
const selected_option = sf.sengines.options[sf.sengines.selectedIndex].value;
if (selected_option === "option_0") {
alert('Choose an option from dropdown first.')
} else {
const submitto = sf.sengines.options[sf.sengines.selectedIndex].value + escape(sf.searchterms.value);
window.location.href = submitto;
return false;
}
}
Working example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With