Un-/hiding options of a Select depending on value of another Select - javascript

Disclaimer: This seems to have been asked in similar form several times already but none of the solutions has worked for me. Additionally most of the solutions appear to be 4+ years old (up to 12+), who knows what changed in that time, I certainly don't.
The Problem: I want to hide all options in a select and only "unhide" them depending on what is chosen in another select.
I have two selects:
<select id="pool" name="pool" onchange="cause_mod()">
<option value="none" selected disabled hidden>Pool</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
and:
<select id="cause" name="cause">
<option value="none" selected hidden="true">cause/option>
<option value="sale" hidden="true">sale</option>
<option value="withdraw" id="withdraw" hidden>withdraw</option>
<option value="deposit" style="display: none">deposit</option>
</select>
The three different variances are to show what i have already tried on the select-side.
I shan't post every variation of the javascript code as it simply would be too much. I will post three variations that i tried with the three variations in the second select:
function cause_mod(){
var pool = document.getElementById("pool");
var cause = document.getElementById("cause");
var deposit = document.querySelectorAll('option[value="deposit"]');
if(pool.value === "1"){
cause.options[1].setAttribute("hidden", true)
document.getElementById("withdraw").removeAttribute("hidden")
deposit.style.display = "";
}
else if(pool.value === "2"){
pretty much the opposite
}
}
I wonder if there is any convenient method (although at this point I'll take inconvenient as well) to "grab" individual options from a select in order to .dosomething with it.

The hidden attribute shouldn't be set to the JavaScript Boolean true, it should just be present or set to the string "hidden":
const sel = document.querySelector("select");
sel.options[1].setAttribute("hidden", "hidden");
<select>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
Now, if you have an option that should not have any value, set it to: value="", not value="none" because none is a string and therefore will become the value of the element.
Also, setting the CSS style.display property to an empty string is not acceptable as this attribute should be set to a valid CSS display value.
Additionally, querySelectorAll() returns a node list, which is an array-like object. Node lists don't have a value property. In your case, if you are looking for a single element on your page, use querySelector(), which will return the first element that matches the selector you supply or undefined if no match can be found. When there is a match, you can then access its DOM properties, like value.
Lastly, you should move your pool, cause and deposit variable declarations out of your function so that they are reinitialized each time the function is called, this is a wasted of resources to scan for the same elements that you already scanned for earlier.

Related

Wildcard character for jquery filter

I'm using the below script to filter my table
<script>
$(document).ready(function() {
$('#citylist').change(function() {
var value = $('#citylist').val();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().indexOf(value) > -1)
});
});
});
</script>
This is the sample design I'm going to use
<select class="form-control" id="citylist">
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
The functions works fine without any conflicts.
I want to clear the filter in one select option. So, I want to know is there any wildcard character like % in sql to use as the value for option to do this task ?
I already tried using * and % for the values of option.
Any help would be appreciated
If you want to reset the filter (which is what I think you mean by "clear the filter in one select option") you can add an option to your drop-down, where the value is an empty string.
For example:
<select class="form-control" id="citylist">
<option value="">-- please select --</option>
<option value="Edinburgh">Edinburgh</option>
<option value="Tokyo">Tokyo</option>
<option value="San Francisco">San Francisco</option>
<option value="London">London</option>
</select>
However, the logic in the $('#citylist').change(...) function is a bit odd - it will only find records which are in the displayed page (so if you are using paging, it will not find matching records in other pages) and it will hide the heading row of your table. This is because you are searching in the DOM not in the DataTables data.
Perhaps this is what you actually want, but it is not how you generally perform filtering in DataTables.
In case you want to search in the more usual way, here is an example:
$(document).ready(function() {
var table = $('#myTable').DataTable( {
-- your usual table initialization goes here --
} );
$('#citylist').change(function() {
var value = $('#citylist').val();
table.columns(2).search( value, false, false ).draw();
} );
} );
This assumes you have a table where the City column is the third column in the table (table.columns(2) - the first column has an index of zero).
The booleans in search( value, false, false ) represent whether you want to use a regular expression (false) and whether you want to use smart-searching (also false).
You can read the documentation for search() for a full explanation.
You can also see an example here where the drop-down search is based on using a regular expression. This is not needed in your specific example (because you are matching on the entire city name).

JavaScript/HTML - Keeping numeric values from select dropdown list selected

I am keeping the values of my option HTML tags selected using this code:
document.getElementById('select_itens_op').onchange = function() {
sessionStorage.setItem('pagina', document.getElementById('select_itens_op').value);
};
if (sessionStorage.getItem('pagina')) {
document.getElementById('select_itens_op').options[sessionStorage.getItem('pagina')].selected = true;
}
It was working just fine, but in one of my tags I came across with a problem. The option tags have numeric values and when I reload the page, what it's being kept is the option related to the index of the value stored in the sessionStorage.
Example:
<select name="select_itens_op" id="select_itens_op" ">
<option value="">Página</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="8">8</option>
<option value="10">10</option>
</select>
If I select the option with value 2, this value will be stored into the sessionStorage, but when I refresh the page the option selected will be the one with value 4, since it is the position 2 of the list. If I select 4 the value stored will be 4 and the option returned would be 10, and so on.
If I use string values it works great, provided I add ids to these tags, but I need these numeric values. I already made my research and I didn't find a proper answer.
What is the best way to solve this?
Go for SelectElement.value directly:
const el_op = document.getElementById('select_itens_op');
// Set on init
if (sessionStorage.pagina) el_op.value = sessionStorage.pagina;
// Store on change
el_op.addEventListener('change', () => sessionStorage.pagina = el_op.value );

Selecting first option of multiple select elements by Prototype JS

I want to select first option of all the select dropdowns having class required-entry in a page with Prototype JS. I have searched through SO questions and found many relevant questions but not what I exactly needed.
Thanks
It's been quite a while since I've done any Prototype.js. So this may not be the best way to go about it, but it should work.
let's say you have a page with:
<select class='required-entry'>
<option value='a'>AAA</option>
<option value='b'>BBB</option>
<option​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​ value='c'>CCC</option>
</select>
<select class='required-entry'>
<option value='x'>XXX</option>
<option value='y'>YYY</option>
<option value='z'>ZZZ</option>
</select>​
You can grab the first option for each select by doing:
var firstOptions = [];
$$('.required-entry').each(function(sel, i) {
firstOptions.push($(sel).getElementsBySelector('option')[0]);
});
// firstOptions is now an array containing the first options
Now, I couldn't tell from your question if you wanted to retrieve the first options, or set the select value so that the first option is literally selected. Here's the later:
$$('.required-entry').each(function(sel, i) {
sel.selectedIndex = 0;
});

Use javascript to change second select list based on first select list option

I have two drop-down lists populated from an array of same dates stored in a database. I want to use javascript or jquery to change the second drop-down list based on the selection from the first list. So an example would be if the user selects 03/03/2012 in the first, start date list, then I'd like the second list to only show or allow future dates within the array. 3/3, 3/2 and 3/1 would either be greyed out or removed and 3/4, 3/5 would remain as selectable options. Can anyone help with the javascript coding or make another recommendation?
<select id='start_date' name='data[sDate]' title='Use the drop list'>
<option value="" selected="selected"> </option>
<option value="03/05/2012">03/05/2012</option>
<option value="03/04/2012">03/04/2012</option>
<option value="03/03/2012">03/03/2012</option>
<option value="03/02/2012">03/02/2012</option>
<option value="03/01/2012">03/01/2012</option>
</select>
<select id='end_date' name='data[eDate]' title='Use the drop list'>
<option value="" selected="selected"> </option>
<option value="03/05/2012">03/05/2012</option>
<option value="03/04/2012">03/04/2012</option>
<option value="03/03/2012">03/03/2012</option>
<option value="03/02/2012">03/02/2012</option>
<option value="03/01/2012">03/01/2012</option>
</select>
With your actual example, if the two lists are exactly the same then it's pretty simple if you work with index(). Look http://jsfiddle.net/elclanrs/7YrqY/
$('#start_date').change(function(){
var $selected = $(this).find('option:selected');
$('#end_date')
.find('option')
.prop('disabled', false)
.eq($selected.index()-1)
.nextAll()
.prop('disabled', true);
});
Here's a few different solutions, including server side. This is a common scenario and I'm sure you could find more examples on this site if you searched a bit more.
http://css-tricks.com/dynamic-dropdowns/
using jQuery
$(function(){ //when the page is loaded
$("#start_date").change(function(){ //register a anonymous function that will be called when the element with id=start_date changes his values
var start = $(this).val(); //gets the value of the element
$("#end_date option").each(function(i){//for each option of end_date
if(new Date($(this).val()).getTime() < new Date(start).getTime()){ //if the date of the element is before the start
$(this).hide(); //hide the element
}else{
$(this).show(); //shows the element
}
});
});
});
Ive not tested but is something like that

JS/Jquery: how to check whether dropdown has selected values?

I've googled and tried a number of ways to do this but none work for me so far. What I am looking for is quite simple: I want to be able to tell whether a dropdown has a selected value or not. The problem is that selectedIndex, :selected, val(), etc. do return results for the following case:
<select>
<option value="123">123</option>
<option value="234">234</option>
</select>
Obviously the browser will display this dropdown with the 123 option being selected but it will be selected only because there are no other options, in reality this dropdown doesn't have a selected value because there is no "selected" property. So basically I am trying to find how to tell apart the above dropdown from this one
<select>
<option selected value="123">123</option>
<option value="234">234</option>
</select>
var hasValue = ($('select > [selected]').length > 0);
Alternatively,
var hasValue = $('select').has('[selected]');
Quick solution:
<select>
<option selected></option>
<option value="123">123</option>
<option value="234">234</option>
</select>
Then see if you have a .val()
The approved answer doesn't seem to work for me.
Here is how I do it to check if all select options are selected:
if($('select option:selected').length > 0) {
/* Do your stuff here */
}
As far as I can tell, there is no functional distinction between your two examples. Essentially, the browser automatically selects the first option.
See, for example, the result of
$('option:selected')
on your first example.
If you really want to prevent this happening, you have two options. The first is to introduce a new, empty element into the select, per Jason's answer. The other option is to deselect the automatically selected value:
$(document).load(function(){
$('option:selected').attr('selected', false);
});
This clears the selection. Any result of $('select').val() that isn't an empty string will therefore be a change by the user.

Categories

Resources