Reset Multiple Select Options - javascript

So I am using a find_select() function in javascript, and what I would like to have happen, is when a particular select option is changed, have it reset all other possible select options beyond the first one. Here's the snippet of code for the function as well as the select option that I would like to reset everything else.
function find_select(){
if (document.getElementById("nsp").selected == true){
if (document.getElementById("pre_alerts_yes").selected == true){
document.getElementById('house_form').style.display = 'none';
document.getElementById('nsp_form').style.display = 'block';
document.getElementById('pre_alerts_yes_form').style.display = 'block';
document.getElementById('feedback_form').style.display = 'none';
}
else{
document.getElementById('house_form').style.display = 'none';
document.getElementById('nsp_form').style.display = 'block';
document.getElementById('feedback_form').style.display = 'none';
}
}
else if (document.getElementById("feedback").selected == true)
{
document.getElementById('house_form').style.display = 'none';
document.getElementById('nsp_form').style.display = 'none';
document.getElementById('feedback_form').style.display = 'block';
}
else if (document.getElementById("house").selected == true)
{
document.getElementById('house_form').style.display = 'block';
document.getElementById('nsp_form').style.display = 'none';
document.getElementById('feedback_form').style.display = 'none';
}
else{
document.getElementById('house_form').style.display = 'none';
document.getElementById('nsp_form').style.display = 'none';
document.getElementById('feedback_form').style.display = 'none';
}
}
And the html code:
<label for="input_title">Phone Type:</label>
<select name="phone_type" id="select_form" class="input-block-level" onchange="find_select()">
<option id="blank" value="blank"></option>
<option id="house" value="1">House Phone</option>
<option id="nsp" value="2">Normal Cell (Non Smart Phone)</option>
<option id="feedback" value="3">SmartPhone</option>
</select>
As an example of what happens is this. If a user select "House Phone" another drop down appears based on that selection, and they can then select something within it. But, if the user changes his mind and wants to do say Smart Phone, the selection boxes that opened up for House Phone then disappear and the new selection boxes for Smart Phone appear. But the options they choice for House Phone, that have now disappeared, are still selected and would be posted. I'd like to reset all values based on that html above for a selection and that should then assure that only the right options are posted, with nothing extra. The examples I've found don't appear to be working in conjunction with what I have.
Thanks

you can use this function to reset your select:
function resetSelectElement(selectElement) {
var options = selectElement.options;
// Look for a default selected option
for (var i=0, iLen=options.length; i<iLen; i++) {
if (options[i].defaultSelected) {
selectElement.selectedIndex = i;
return;
}
}
// If no option is the default, select first or none as appropriate
selectElement.selectedIndex = 0; // or -1 for no option selected
}
Now use the function to reset it:
resetSelectElement(document.getElementById('house_form'));
You are done!
Tip: I can see you are using document.getElementById() many times in your code. If you dont want to use jQuery, to select elements by Id, you can create a function like this to use it multiple times:
function GE(el){
return document.getElementById(el);
}
and then you can use it multiple times in your code like:
resetSelectElement(GE('house_form'));
This will save your code and also will help you to make your code beautiful. :)

To clear the selection of the select, you can set the property selectedIndex to 0, like this:
$('#select_form').prop('selectedIndex', 0);
Edit:
You can name the grouping containers (I'm assuming there are divs) accordingly to the first dropdown value, for example use 'div-house' for the first group, and so on.
Also you can mark these divs to have a common class name, for example 'select-group'.
Like this:
<label for="input_title">Phone Type:</label>
<select name="phone_type" id="select_form" class="input-block-level" onchange="find_select()">
<option id="blank" value="blank"></option>
<option id="house" value="1">House Phone</option>
<option id="nsp" value="2">Normal Cell (Non Smart Phone)</option>
<option id="feedback" value="3">SmartPhone</option>
</select>
<div id="div-house" class="select-group">
....
</div>
<div id="div-nsp" class="select-group">
...
</div>
<div id="div-feedback" class="select-group">
...
</div>
Then, you can do it in a simple manner, like this:
$(document).ready(function () {
$(".select-group").hide();
});
function find_select()
{
// Hide all the dynamic divs
$(".select-group").hide();
// Clear the selection of ALL the dropdowns below ALL the "select-group" divs.
$(".select-group").find('option:selected').removeAttr('selected');
var select = $("#select_form");
if (select.val() > 0)
{
// Show the div needed
var idSelected = select.find('option:selected').attr('id');
$("#div-" + idSelected).show();
}
}
Working sample here: http://jsfiddle.net/9pBCX/

Hey Mr. Techie, I'm running out of time but want to share something with you which can give you very clear and concise idea about your controls logic you are trying to achieve. You will need to work around a bit, as these are quite basic cookies I was created back in time. Try to understand and create a logic around this, I hope it will be helpful. Thanks.
Here are two simple examples. You can look at the jquery documentation for the right attributes, which will suit your needs.
[Example 1:] http://jsfiddle.net/Superman/X4ykC/embedded/result/
//enable disable button on decision checkbox.
$(function() {
$('#agree').change(function() {
$('#submit').attr('disabled', !this.checked);
});
});
[Example 2:] http://jsfiddle.net/Superman/XZM5r/embedded/result/
//enable disable controls on checkbox
$(function() {
enable_cb();
$("#group1").click(enable_cb);
});
function enable_cb() {
if (this.checked) {
$("input.group1").removeAttr("disabled");
} else {
$("input.group1").attr("disabled", true);
}
}

So I finally figured it out. Man what a pain! Here's what finally worked for me to get it work like I wanted it to:
// For the drop down switches
$(function(){
$('#phone_type').change(function(){
$('#call_types option[value=""]').attr('selected','selected');
$('#pre_alerts option[value=""]').attr('selected','selected');
$('#pre_alerts_types option[value=""]').attr('selected','selected');
$('#alert_type option[value=""]').attr('selected','selected');
// Because one box is being stupid, we set the display to none
document.getElementById('pre_alerts_yes_form').style.display = 'none';
});
});

Related

Why does my JS function only affect the first element addressed in the HTML structure? (changing display property of class)

my basic structure of the JS function works. However, it only affects the first DIV in the HTML structure that is to be shown and hidden.
The CSS class "map-content" has none as display property. Several containers will receive this class and will therefore initially be hidden. All DIV containers get their own value, which is necessary in my code when changing the display property.
This is my function, which basically works, but only shows and hides the first container (in the HTML structure) with the "map-content" class.
function validate_3() {
var x = document.getElementById("location_select");
var y = x.options[x.selectedIndex].value;
var a = document.querySelector(".map-content");
var b = a.getAttribute('value');
{
if (y == b) {
a.style.display = "block";
} else {
a.style.display = "none";
}
}
}
.map-content {
display: none;
}
<select id="location_select" onchange="validate_3">
<option disabled selected>Select location...</option>
<option value="de_germany">Berlin: Germany</option>
<option value="fr_france">Paris: France</option>
<option value="it_italy">Rome: Italy</option>
</select>
<div class="map-content" value="de_germany">
<h3>This is Berlin</h3>
<p>Berlin is in Germany</p>
</div>
<div class="map-content" value="fr_france">
<h3>This is Paris</h3>
<p>Paris is in France</p>
</div>
<div class="map-content" value="it_italy">
<h3>This is Rome</h3>
<p>Rome is in Italy</p>
</div>
Note on the code snippet: I don't know why, but unlike my test interface, none of the selections work here. Not even the first in the structure as described in the text.
I am happy to get general suggestions for a better structure if there are any.
you are missing a set of parentheses here onchange="validate_3"> , add a set of parentheses like this onchange="validate_3()">, and your first selection should work
To get what you want, make sure you've added the parentheses as shown above.
javascript,
// take this line out of your funtion and change `querySelector` to
//`querySelectorAll`
var a = document.querySelectorAll(".map-content");
function validate_3() {
var x = document.getElementById("location_select");
var y = x.options[x.selectedIndex].value;
//use The forEach() method to executes a provided function once for each
//element.
a.forEach((element) => {
if (y != element.getAttribute("value")) {
(element.classList.add("map-content"))
} else {
element.classList.remove("map-content")
};
});
};
But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

Tampermonkey: Hide Options in Dropdown if they don't contain a string

I am working on a Tampermonkey script to make life a lot easier. So picture this: There's a dropdown supplying 400+ options. However, I only need to use two of them. So all the others can be hidden.
So how do I do this? Currently, I am working with this, but it doesn't really do what I want it to.
var firstCampaignName = "001 - Campaign";
var secondCampaignName = "002 - Campaign";
These are the two options I want to keep. I halfway think I could simplify this by matching them both on " - Campaign" or something. Because the names are nigh-identical. But anyway. So here's the function I'm working with.
$('#dropdown option').each(function(){
if ('#dropdown option'.text() === firstCampaignName || '#brand option'.text() === secondCampaignName)
{
if ($.inArray($(this).text()))
$(this).show();
// If not, hide it
else
$(this).hide();
}
});
It's obvious that I'm doing something wrong. Somewhere in this, I am missing something. So, please, help?
To hide all options from the dropdown except the 2 specific options you can do the following. Note that as mentioned as comment by charlietfl that to hide options is not supported cross browser, so maybe it's an option for you to remove those options instead of hiding them as you mentioned that you don't need them.
var firstCampaignName = "001 - Campaign";
var secondCampaignName = "002 - Campaign";
$('#dropdown option').each(function() {
if ($(this).text() === firstCampaignName || $(this).text() === secondCampaignName) {
$(this).show();
} else {
$(this).hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown">
<option value="1">001 - Campaign</option>
<option value="2">002 - Campaign</option>
<option value="3">003</option>
<option value="4">004</option>
<option value="5">005</option>
</select>

Disabling an option from a selector so it can't be removed

I have a selector that looks like this:
<select id="patientSelect">
<option disabled selected style='display: none;' id="patient0">
Incoming Patients</option>
<option id="patient1"></option>
<option id="patient2"></option>
</select>
Because I kind of wanted a placeholder type text (i.e the first option) for the selector. And with my javascript I wanted it so that if the selected option was patient1 and you clicked a button it would be removed and would go back to showing the disabled 'Incoming Patients' thing. The javascript:
$(".ui-btn").click(function(){
remove();
$('#patientSelect :selected').attr('selected', '0');
$('#patientSelect').change();
});
function remove(){
var x = document.getElementById("patientSelect");
x.remove(x.selectedIndex);
}
Problem is it always removes more than 1 option, so if I got rid of "patient2" and tried to run remove() the list becomes a long blank list. All help is appreciated, please don't be too harsh. :P
Edit
Sorry, basically I want the text 'Incoming Patients' (which is the first option of my selector) to never be removed. No matter how many times 'function remove()' tries to run. It can remove the other options fine, just never the first one.
This may not even be possible, I'm not sure..
If there's another way to get text onto a selector without options that'd be fine too :-)
Maybe something like:
function remove(){
if(option != 1){
var x = document.getElementById("patientSelect");
x.remove(x.selectedIndex);
}
}
Try
var $ps = $('#patientSelect');
$(".ui-btn").click(function () {
var $sel = $ps.find('option:selected')
if ($sel.index() > 0) {
$sel.remove();
$ps.val($ps.find('option:eq(0)').val())
}
});
Demo: Fiddle
You can give this a try.
$(".uibtn").click(function(){
remove();
$('#patientSelect').append("<option disabled selected style='display: none;' id='patient0'>Incoming Patients</option>");
$('#patientSelect').change();
});
function remove(){
var x = document.getElementById("patientSelect");
x.remove(x.selectedIndex);
}
Check this http://jsfiddle.net/7yR5V/

Hiding Drop Down Boxes if Radio Button other than default is Clicked

I swear I'm going to learn more JavaScript...
I have this page (which really an include file in another ASP page, but I copied the correct HTML and made it so it'd load by itself for my testing purposes):
FO Samples
This is how it should show when they first load it. If they choose one of the other radio buttons, it should HIDE the 2 dropdown boxes. Using this code (something I found from someone else's question on here), its working.
<script type="text/javascript">
function ChangeDropdowns(value) {
if (value == "0") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'block';
}
else {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
}
</script>
But I can't figure out how to make it show them again if they go back to the "I wanna pick my own!" radio. The value of SAMPGROUP is the ID from the database of that sample category group. So it won't necessarily be in numerical order, it might skip #'s (if we delete a category or something). Basically, it should show the dropdowns if SAMPGROUP = 0 and not if its anything else!
I tried changing my code to this (95 being the value of SAMPGROUP for the "Autumm" option), but it doesn't seem to have made a difference.
<script type="text/javascript">
function ChangeDropdowns(value) {
if (value == "0") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'block';
} else if (value == "95") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
else {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
}
</script>
Any help would be greatly appreciated!!
Mahalo!
You are not setting the "value" in your onchange event, thus it's never equal to 0. Try changing this:
<input type="radio" name="SAMPGROUP" value="0" OnChange="Javascript:ChangeDropdowns()" checked />
to
<input type="radio" name="SAMPGROUP" value="0" OnChange="Javascript:ChangeDropdowns(0)" checked />
Here is the fiddle.
Good luck.
You may not be passing any value to the parameter "value" on calling the function ChangeDropdowns. Please ensure you pass the value like ChangeDropdowns(0) etc..

How to avoid the need for ctrl-click in a multi-select box using Javascript?

I thought this would be a simple hack, but I've now been searching for hours and can't seen to find the right search term. I want to have an ordinary multiple select box (<select multiple="multiple">) except I don't want the user to have to hold down the control key to make multiple selections.
In other words, I want a left click to toggle the <option> element that's under the cursor without changing any of the others. In other other words, I want something that looks like a combo list box but behaves like a group of check boxes.
Can anybody suggest a simple way to do this in Javascript? Thanks.
Check this fiddle: http://jsfiddle.net/xQqbR/1022/
You basically need to override the mousedown event for each <option> and toggle the selected property there.
$('option').mousedown(function(e) {
e.preventDefault();
$(this).prop('selected', !$(this).prop('selected'));
return false;
});
For simplicity, I've given 'option' as the selector above. You can fine tune it to match <option>s under specific <select> element(s). For ex: $('#mymultiselect option')
Had to solve this problem myself and noticed the bugged behavior a simple interception of the mousedown and setting the attribute would have, so made a override of the select element and it works good.
jsFiddle: http://jsfiddle.net/51p7ocLw/
Note: This code does fix buggy behavior by replacing the select element in the DOM. This is a bit agressive and will break event handlers you might have attached to the element.
window.onmousedown = function (e) {
var el = e.target;
if (el.tagName.toLowerCase() == 'option' && el.parentNode.hasAttribute('multiple')) {
e.preventDefault();
// toggle selection
if (el.hasAttribute('selected')) el.removeAttribute('selected');
else el.setAttribute('selected', '');
// hack to correct buggy behavior
var select = el.parentNode.cloneNode(true);
el.parentNode.parentNode.replaceChild(select, el.parentNode);
}
}
<h4>From</h4>
<div>
<select name="sites-list" size="7" multiple>
<option value="site-1">SITE</option>
<option value="site-2" selected>SITE</option>
<option value="site-3">SITE</option>
<option value="site-4">SITE</option>
<option value="site-5">SITE</option>
<option value="site-6" selected>SITE</option>
<option value="site-7">SITE</option>
<option value="site-8">SITE</option>
<option value="site-9">SITE</option>
</select>
</div>
techfoobar's answer is buggy, it unselects all options if you drag the mouse.
Sergio's answer is interesting, but cloning and removing events-bound to a dropdown is not a nice thing.
Try this answer.
Note: Doesn't work on Firefox, but works perfectly on Safari/Chrome/Opera. (I didn't test it on IE)
EDIT (2020)
After 5 years since my original answer, I think best practice here is to replace the dropdown with checkboxes. Think about it, that's the main reason why checkboxes exist in the first place, and it works nicely with old browsers like IE & modern mobiles without any custom JS to handle all the wacky scenarios.
Necromancing.
The selected answer without jQuery.
Also, it missed setting the focus when an option is clicked, because you have to do this yourself, if you write e.preventDefault...
Forgetting to do focus would affect CSS-styling, e.g. bootstrap, etc.
var options = [].slice.call(document.querySelectorAll("option"));
options.forEach(function (element)
{
// console.log("element", element);
element.addEventListener("mousedown",
function (e)
{
e.preventDefault();
element.parentElement.focus();
this.selected = !this.selected;
return false;
}
, false
);
});
I had same problem today, generally the advice is to use a list of hidden checkboxes and emulate the behavior via css, in this way is more easy to manage but in my case i don't want to modify html.
At the moment i've tested this code only with google chrome, i don't know if works with other browser but it should:
var changed;
$('select[multiple="multiple"]').change(function(e) {
var select = $(this);
var list = select.data('prevstate');
var val = select.val();
if (list == null) {
list = val;
} else if (val.length == 1) {
val = val.pop();
var pos = list.indexOf(val);
if (pos == -1)
list.push(val);
else
list.splice(pos, 1);
} else {
list = val;
}
select.val(list);
select.data('prevstate', list);
changed = true;
}).find('option').click(function() {
if (!changed){
$(this).parent().change();
}
changed = false;
});
Of course suggestions are welcome but I have not found another way
Reusable and Pure JavaScript Solution
const multiSelectWithoutCtrl = ( elemSelector ) => {
let options = document.querySelectorAll(`${elemSelector} option`);
options.forEach(function (element) {
element.addEventListener("mousedown",
function (e) {
e.preventDefault();
element.parentElement.focus();
this.selected = !this.selected;
return false;
}, false );
});
}
multiSelectWithoutCtrl('#mySelectInput') /* Can use ID or Class */
option {
font-size: 20px;
padding: 10px 20px;
}
<select multiple id="mySelectInput" class="form-control">
<option>🍎 Apple</option>
<option>🍌 Banana</option>
<option>🍍 Pineapple</option>
<option>🍉 Watermelon</option>
</select>

Categories

Resources