Disabling search functionality for drop-down menu default selection - javascript

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>

Step 1
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>
Step 2
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

Related

Hide an option element if a matching value is selected

One day I had a problem with PHP and a super guy resolved my problem, this time I learn JavaScript, and I'm really stuck on a project.
Here is the fiddle: https://jsfiddle.net/xasal/8c0kdqm4/5/
As you see, I have 2 selectors, on the left, the user see his characters, at the right, he can chose to switch his "race", the problem is I want JavaScript to run something when the guy selects his character at the left to compare with the right one and automatically delete the option if it's for the same race.. I made the functions for all to disappear, the only problem is the compare value... and when I think my code is nice I have issues in the dev console of unexpected end or syntax
Uncaught SyntaxError: Unexpected end of input
Sorry if it's kinda easy for you I'm really new :x
<select id="charSelect" name="charSelection">
<option value="Knight" selected="selected"><span id="charName">Gooffy</span> - <span class="charJob" onclick="detectChanges()">Knight</span> - lv.<span id="charLvl">175</span></option>
<option value="NightShadow"><span>Soul</span> - <span class="charJob" onclick="detectChanges()">NightShadow</span> - lv.<span>175</span></option>
<option value="Rogue"><span>Veli</span> - <span class="charJob" onclick="detectChanges()">Rogue</span> - lv.<span>175</span></option>
</select>
</section>
<input type="submit" value="Change my class to">
<section class="rightSelect">
<select class="jobSelect" name="jobSelection">
<option value="titan" id="titan" class="charJobChange" selected="selected">Titan</option>
<option value="knight" id="knight" class="charJobChange">Knight</option>
<option value="healer" id="healer" class="charJobChange">Healer</option>
<option value="mage" id="mage" class="charJobChange">Mage</option>
<option value="rogue" id="rogue" class="charJobChange">Rogue</option>
<option value="sorcerer" id="sorcerer" class="charJobChange">Sorcerer</option>
<option value="nightshadow" id="nightshadow" class="charJobChange">NightShadow</option>
</select>
function removeNS() { // example with Hide NS = nightshadow
$('#nightshadow').hide();
console.log("loaded");
}
function selectedCh(){
if($("#leftSelect select").find("option:selected").val() == "NightShadow") {
removeNS();
}
selectedCh();
Try this instead.
I called the function in onchange="selectedCh()" of left select box.
function selectedCh(){
// to get selected option in left select box in lowercase
var selectedtitem = $(".leftSelect select").find("option:selected").val().toLowerCase();
// to get total number of options in right select box
var oplen = $(".rightSelect select option").length;
// enable all option in right select box
$(".rightSelect select option").show();
// Loop for checking the selected option equals to any option in right select box
for(i=1;i<=oplen;i++){
if($(".rightSelect select option:nth-child("+i+")").val() == selectedtitem){
// to hide if equals in right select box option
$(".rightSelect select option:nth-child("+i+")").hide();
}
}
}
// to check first run the code
selectedCh();
Working demo
function selectedCh(){
var selectedtitem = $(".leftSelect select").find("option:selected").val().toLowerCase();
var oplen = $(".rightSelect select option").length;
$(".rightSelect select option").show();
for(i=1;i<=oplen;i++){
if($(".rightSelect select option:nth-child("+i+")").val() == selectedtitem){
$(".rightSelect select option:nth-child("+i+")").hide();
}
}
}
selectedCh();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="leftSelect">
<select id="charSelect" name="charSelection" onchange="selectedCh()">
<option value="Knight" selected="selected"><span id="charName">Gooffy</span> - <span class="charJob" onclick="detectChanges()">Knight</span> - lv.<span id="charLvl">175</span></option>
<option value="NightShadow"><span>Soul</span> - <span class="charJob">NightShadow</span> - lv.<span>175</span></option>
<option value="Rogue"><span>Veli</span> - <span class="charJob" >Rogue</span> - lv.<span>175</span></option>
</select>
</section>
<section class="rightSelect">
<select class="jobSelect" name="jobSelection">
<option value="titan" id="titan" class="charJobChange" selected="selected">Titan</option>
<option value="knight" id="knight" class="charJobChange">Knight</option>
<option value="healer" id="healer" class="charJobChange">Healer</option>
<option value="mage" id="mage" class="charJobChange">Mage</option>
<option value="rogue" id="rogue" class="charJobChange">Rogue</option>
<option value="sorcerer" id="sorcerer" class="charJobChange">Sorcerer</option>
<option value="nightshadow" id="nightshadow" class="charJobChange">NightShadow</option>
</select>
</section>
Hide option if value == 'option 3'
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectName">
<option value="option 1">Option 1</option>
<option value="option 2">Option 2</option>
<option value="option 3">Option 3 (hide on chnage)</option>
<option value="option 4">Option 4</option>
<option value="option 5">Option 5</option>
</select>
<script>
$('#selectName').on('change', function () {
if ($(this).val() == 'option 3') {
$('option[value="option 3"]',this).hide();
} else {
$('option[value="option 3"]',this).show();
}
}).trigger('change');;
</script>
Just use a query selector for find the matching option and hide it. Here is a minimal example:
var charSelect = document.querySelector('select[name="charSelection"]');
var jobSelect = document.querySelector('select[name="jobSelection"]');
charSelect.addEventListener('change', function(){
// Unhide any hidden options
jobSelect.querySelectorAll('option').forEach(opt=>opt.style.display = null);
// Hide the option that matches the above selected one
var value = this.value.toLowerCase();
jobSelect.querySelector(`option[value="${value}"]`).style.display = "none";
});
<select name="charSelection">
<option value="Knight" selected="selected">Knight</option>
<option value="NightShadow">NightShadow</option>
<option value="Rogue">Rogue</option>
</select>
<select name="jobSelection">
<option value="titan" selected="selected">Titan</option>
<option value="knight">Knight</option>
<option value="healer">Healer</option>
<option value="mage">Mage</option>
<option value="rogue">Rogue</option>
<option value="sorcerer">Sorcerer</option>
<option value="nightshadow">NightShadow</option>
</select>

preventDefault() not working on a particular option select

I have this <select> list that takes different options and reroutes based on the one clicked. The html code is:
<select id="pageSelect" name="Choose Page" onchange="location = this.value">
<option value='' disabled selected hidden>Choose Page</option>
<option value='/page-1'>Page 1</option>
<option value='/page-2'>Page 2</option>
<option value="allPages" >Custom Page</option>
</select>
The rerouting of the first 2 pages work as expected. However, the third option is going to be handled using a custom Javascript function instead of being handled by the onchange function declared at the <select> element.
The custom function for the last <option> is:
$('#pageSelect').change(function(event) {
event.preventDefault()
var pagesvalueselect = $(this).val();
if(pagesvalueselect=="allPages"){
$('#siteSaleModal').modal("show"); //Open Modal
}
});
The function works and when a user clicks on the last option, it triggers the modal to pop up but it still redirects the user to another page based on value="allPages" even though I am using the preventDefault() function.
The preventDefault() call only stops the current change event handler. The one you've assigned via the onchange attribute will still run regardless as it's entirely separate.
To fix this, and improve your code, remove the onchange attribute (as they are outdated and now considered bad practice) and combine them in to one unobtrusive event handler.
$('#pageSelect').change(function(event) {
event.preventDefault()
var pagesvalueselect = $(this).val();
if (pagesvalueselect == "allPages") {
console.log('open modal...');
//$('#siteSaleModal').modal("show"); //Open Modal
} else {
console.log('redirecting to ' + pagesvalueselect + '...');
//window.location.assign(pagesvalueselect);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="pageSelect" name="Choose Page">
<option value="" disabled="true" selected="true" hidden>Choose Page</option>
<option value="/page-1">Page 1</option>
<option value="/page-2">Page 2</option>
<option value="allPages">Custom Page</option>
</select>
Your code code works fine without event.preventDefault() and onchange attribute.
<select id="pageSelect" name="Choose Page">
<option value='' disabled selected hidden>Choose Page</option>
<option value='/page-1'>Page 1</option>
<option value='/page-2'>Page 2</option>
<option value="allPages" >Custom Page</option>
</select>
$('#pageSelect').change(function(event) {
var pagesvalueselect = $(this).val();
if(pagesvalueselect=="allPages"){
$('#siteSaleModal').modal("show"); //Open Modal
} else {
location = pagesvalueselect;
}
});
Codepen

Auto check saved data in jQuery Multiselect

I am using this jQuery Multiselect plugin https://github.com/nobleclem/jQuery-MultiSelect to convert all my select boxes that have the multiple attribute enabled in to drop down boxes with check boxes.
I load the options in the select box from a database.
Upon the form submission I can save the multiple selected data, but when I retreive data back from the database I cannot display the saved data back in the multi select box by checking matching check boxes.
The multiselect plugin has a loadOptions method, but using that method I have to generate all option data with option name, option value and the check status, and set it to the multiselect plugin. How can I easily do this if I have an array of data which must be checked/selected in the multiple select plugin?
HTML
<select name="abc" id="abc" multiple title="Test Number?">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
<option value="4">Test 4</option>
<option value="5">Test 5</option>
</select>
JS (I have more than one multiple select boxes and initiate them as shown below)
$.each($("select[multiple]"), function (key, selectbox) {
$("#" + selectbox.id).multiselect({
texts: {placeholder: $("#" + selectbox.id).attr("title")}
});
});
My saved data array is [1,3,4]
I need to set these saved data to the select box and check the check boxes without going through the loadOptions method.
You could use jQuery .filter() function on your select options to preselect those wanted before initializing the multiselect plugin.
Here,
$('option',this).filter((_,e) => saved_data.includes(+e.value)).prop('selected',true);
Preselects every option, before the .multiselect() call.
let saved_data = [1, 3, 4];
$('select[multiple]').each(function() {
$('option', this).filter((_, e) => saved_data.includes(+e.value)).prop('selected', true);
$(this).multiselect({
texts: {
placeholder: $(this).attr("title")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://springstubbe.us/projects/demos/jquery-multiselect/scripts/index.js?1523890673"></script>
<link rel="stylesheet" href="https://springstubbe.us/projects/demos/jquery-multiselect/styles/index.css?1518818712">
<select name="abc" id="abc" multiple title="Test Number?">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
<option value="4">Test 4</option>
<option value="5">Test 5</option>
</select>

Don't allow to select other option if selected specific value with select2

As you can see i have select box with the select2 (multiple) select feature, with some option like
<option value="All"> All </option>
<option value="test#email.com"> User 1</option>
<option value="test2#email.com"> User 2 </option>
<option value="Test3#rmail.com"> User 3 </option>
is that possible that if i choose the option All from the select box then select box dose't not allow me to choose the other option from the given options until and unless i remove it.
I want to restrict the user to select either choose All or select the multiple users from the options.
i am ready to use jQuery or javascript to achieve this.
Working fiddle.
You could set the value of select to All when the option All is presented :
$("#my-select").select2();
$("#my-select").on('change', function(){
var selected = $(this).val();
if(selected != null)
{
if(selected.indexOf('All')>=0){
$(this).val('All').select2();
}
}
})
Hope this helps.
$("#my-select").select2();
$("#my-select").on('change', function(){
var selected = $(this).val();
if(selected != null)
{
if(selected.indexOf('All')>=0){
$(this).val('All').select2();
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css" rel="stylesheet"/>
<select multiple id="my-select" style="width:300px">
<option value="All"> All </option>
<option value="test#email.com"> User 1</option>
<option value="test2#email.com"> User 2 </option>
<option value="Test3#rmail.com"> User 3 </option>
</select>

HIding or Showing Dropdown Options Based On Another Dropdown

I have 16 fields that need to be sorted by state. Originally, I made it so that there was four different divs because there's four different states people can choose from.
However, I ran into the issue of emails not going to the right people because the 16 fields are agents that people can choose and those agents need to have an email sent to them if they're chosen.
I keep finding multiple solutions for showing and hiding different divs but how do I hide or show options in a single sub-drop down menu?
Parent Dropdown Menu
State 1
State 2
State 3
State 4
Agent Dropdown Menu
Agent 1
Agent 2
Agent 3
Etc (all the way to agent 16)
How can I make it so that when a user selects State 1, it only shows a few options from the agent dropdown menu? The only solutions I can find are ones that have you split the sub-menu into different divs. We're using Contact Form 7 and the only thing people can see are the names but the emails are attached and those agents have to get an email when someone selects them.
HTML:
<select onchange="changeValues()" id="main-dd">
<option value="0">State 1</option>
<option value="1">State 2</option>
<option value="2">State 3</option>
<option value="3">State 4</option>
</select>
<select id="agent-dd"></select>
Javascript:
var AgentDDValues = [
['Agent 1','Agent 2'],
['Agent 3'],
['Agent 4'],['Agent 5'],
['Agent 6'],['Agent 7'],['Agent 8']
];
function changeValues(){
var e = document.getElementById("main-dd");
var selVal = e.options[e.selectedIndex].value;
$("#agent-dd").empty();
for(var i=0;i<AgentDDValues[selVal].length;i++){
$("#agent-dd").append('<option>'+AgentDDValues[selVal][i]+'</option>');
}
}
You can trigger off the change state in a select dropdown and hide options in the second one
HTML
<select id="s1">
<option disabled selected>pick an option</option>
<option data-id="1">option 1</option>
<option data-id="2">option 2</option>
</select>
<select id="s2">
<option class="1">sub option 1</option>
<option class="1">sub option 2</option>
<option class="1">sub option 3</option>
<option class="1">sub option 4</option>
<option class="2">sub option 5</option>
<option class="2">sub option 6</option>
<option class="2">sub option 7</option>
<option class="2">sub option 8</option>
</select>
Javascript/Jquery
$("#s1").on("change", function(){
var id = $("#s1 :selected").data("id");
if(id == 1){
$(".1").show();
$(".2").hide();
}
if(id == 2){
$(".1").hide();
$(".2").show();
}
});
Have a look at this fiddle I created
UPDATE:
In response to your comments you can add classes via Jquery like this:
var count = 0;
$("#s2 option").each(function(){
if(count < 4){
$(this).addClass("1");
}
else $(this).addClass("2");
count++;
});
This just uses a simple counter to add a "1" class to the first half of the options and then switch over to a "2" class for the second half.

Categories

Resources