Dynamic select element - javascript

I have this select element with multiple option inside it:
<select class="form-control" name="genere1">
<option value="Alternative / Indie">Alternative / Indie</option>
<option value="Classical Music">Classical Music</option>
<option value="Country">Country</option>
<option value="Easy Listening">Easy Listening</option>
<option value="Electronic / Dance">Electronic / Dance</option>
<option value="Hip Hop / Rap">Hip Hop / Rap</option>
<option value="Jazz">Jazz</option>
<option value="Latin / Reggaeton">Latin / Reggaeton</option>
<option value="Other">Other</option>
<option value="Pop">Pop</option>
<option value="Reggae / Dancehall">Reggae / Dancehall</option>
<option value="Rock">Rock</option>
<option value="Spiritual">Spiritual</option>
</select>
for every option element you see up here i have another select element. Basically, I have a series of music genres listed in a select element and, under it, the subgenres related to every single one of the "master genres".
What I would like to do is make the subgenres visible only when the relative genre is selected. For example, if the user selects "Pop", I would like to show them the related select field containing the Pop subgenres.
My HTML markup is actually generated by a WordPress plugin and I am not able to edit it, unfortunately. This being said, I can't declare custom values inside my HTML because they are automatically generated by the plugin. I am actually looking for a simple solution, something like: if 'master genre' is 'rock', then display 'rock' input subgenres. How could I do something like this?

You could link two selects and display corresponding subgenres using .dataset.option. I'm afraid you won't get around a little JavaScript here.
Here's a working example for your particular use-case:
const genre = document.querySelector("#genre");
const subgenre = document.querySelector("#subgenre");
const subOptions = subgenre.querySelectorAll("option");
const setValue = (newValue) => {
subgenre.innerText = null;
for (let i = 0; i < subOptions.length; i++)
subOptions[i].dataset.option === newValue &&
subgenre.appendChild(subOptions[i]);
};
setValue(genre.value);
<select id="genre" onchange="setValue(this.value)">
<option value="Metal">Metal</option>
<option value="Rock">Rock</option>
</select>
<select id="subgenre">
<option value="Metal" data-option="Metal">Thrash Metal</option>
<option value="Metal" data-option="Metal">Death Metal</option>
<option value="Metal" data-option="Metal">Black Metal</option>
<option value="Rock" data-option="Rock">Classic Rock</option>
<option value="Rock" data-option="Rock">Hard Rock</option>
</select>

Related

Selection from dropdown lists based on index rather than value

I have this 'select' dropdown list on the website:
<select id="customQuestion0" class="form-control maxCharLimit" data-bind="'css':{'inputError': verificationFailed}, 'attr':{'id':'customQuestion' + $index(), tabindex:tabIdx},hasFocus:isSelected, options: answers, optionsText:'answer', optionsCaption:$parent.chooseOneText, value:selectedAnswer, optionsValue:'answerKey'" id="customQuestion0" tabindex="13">
<option value="">Choose One...</option>
<option value="253133968">Doulos Email / Website</option>
<option value="253133969">Cadence Email/Website</option>
<option value="253133970">A colleague / friend</option>
<option value="253133971">Other professional network (eg LinkedIn, Twitter)</option>
</select>
In the Tampermonkey script I can select e.g. option Duolos Email / Website with:
var formCustomQuestion1 = document.getElementById('customQuestion0')
formCustomQuestion0.value = '253133968'
But unfortunately this value 253133968 can change. Is there any way to be able to simply select item #1 in the script (starting the numbering at 0), disregarding the value?
It is working simply with:
formCustomQuestion0.selectedIndex = '1'

Get a select box by name and set another select box by same name?

I am building a fairly complex form-- I need to copy some data between one and another and I am using jQuery to do this. The only road block I am running into is setting the state.
I have two drop downs, one us using the full state name as the value and the other is using the state abbreviation as the value. The names are the same-
so on form 1 it looks like
<option value="Illinois">Illinois</option>
and form 2 it looks like
<option value="IL">Illinois</option>
Each form has its own unique css selector. How can I set the selected value of form 2 to match what is in form 1 using jQuery?
I do not have any control over the forms, just need to manipulate the input. Have tried using a name selector in jQuery, but I'm not having any luck.
Thank you.
You can do something like this
<select id="fullName">
<option value="Maryland" data-abbr="MD">Maryland</option>
<option value="Illinois" data-abbr="IL">Illinois</option>
<option value="Delaware" data-abbr="DE">Delaware</option>
</select>
<select id="abbr">
<option value="MD">Maryland</option>
<option value="IL">Illinois</option>
<option value="DE">Delaware</option>
</select>
And your jQuery
$('body').on('change', '#fullName', function(){
var abbr = $(this).find('option:selected').data('abbr');
$('#abbr').val(abbr);
});
Try this
<form id="form1" name="form1">
<select name="states" onchange="changeselect(this)">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
</form>
<form id="form2" name="form2">
<select name="states">
<option value="opt1">option1</option>
<option value="opt2">option2</option>
<option value="opt3">option3</option>
<option value="opt4">option4</option>
<option value="opt5">option5</option>
</select>
</form>
function changeselect(elem)
{
var value1 = $(elem).val();
$('#form2 select option').removeAttr('selected');
$('#form2').find('select option').each(function(){
var value2 = $(this).html();
if(value1 == value2)
{
var selected = $(this).attr('value');
$('#form2 select').val(selected);
}
});
}
If you create 2 arrays which exactly correspond with one another:
var StateNames = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
var StateAbbreviations = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
You can:
get the value from the first option list;
find that value's index in the first array; (hint: use indexOf)
use the same index to find out what the corresponding abbreviation is in the second array;
use the returned abbreviation to locate the correct option in the second option list

Hide and display HTML elements based on what was chosen in a dropdown

My website is created in ASP classic - VBScript (not my choice and is a language I've not had experience with before this). I'm trying to create a webpage where in it: A dropdown menu reveals an additional dropdown based on what was selected in the first one. I'm trying to use a javascript function to achieve this.
Example:
In the first dropdown the user chooses ice cream or crisps.
Based on what the user selects another dropdown gives the choice of flavour.
Ice cream: vanilla, chocolate, mint.
Crisps: ready salted, cheese & onion, salt & vinegar.
This is what my code currently looks like:
HTML
<select id="food" onchange="fctCheck(this.value)">
<option value="">Choose an item</option>
<option value="icecream">Ice cream</option>
<option value="crisps">Crisps</option>
</select>
<select id="icecream" style="display:none">
<option value="vanilla">Vanilla</option>
<option value="chocolate">Chocolate</option>
<option value="mint">Mint</option>
</select>
<select id="crisps" style="display:none">
<option value="readysalted">Ready Salted</option>
<option value="cheeseandonion">Cheese and Onion</option>
<option value="saltandvinegar">Salt and Vinegar</option>
</select>
.
javascript
function fctCheck(food)
{
if (food == "")
{document.getElementById(food).style.display = "none";}
else
{document.getElementById(food).style.display = "block";}
}
as mentioned by st3inn this.value is absolutely fine - there is just the typo by document.getElement==>B<==yId.
But your code has the disadvantage, that a user could select both options and so both sub-selections would be visible.
You could avoid this by first hiding all sub-selections before showing the one for the selected item. This could be done that way (via the addiotional name-attribute, or, if you choose to work with jQuery you could do something more sophisticated instead):
Example (with comments) on JSFiddle
Javascript:
function fctCheck(food) {
var elems = document.getElementsByName("subselector");
for (var i = 0; i < elems.length; i++) {
elems.item(i).style.display = "none";
}
document.getElementById(food).style.display = "block";
}
HTML:
<select id="food"onchange="fctCheck(this.value);">
<option value="">Choose an item</option>
<option value="icecream">Ice cream</option>
<option value="crisps">Crisps</option>
</select>
<select id="icecream" name="subselector" style="display:none">
<option value="vanilla">Vanilla</option>
<option value="chocolate">Chocolate</option>
<option value="mint">Mint</option>
</select>
<select id="crisps" name="subselector" style="display:none">
<option value="readysalted">Ready Salted</option>
<option value="cheeseandonion">Cheese and Onion</option>
<option value="saltandvinegar">Salt and Vinegar</option>
</select>
Cheers,
Florian
You need to check for option value instead:
fctCheck(this.options[ this.options.selectedIndex ].value)
this.options is collection of <option> elements inside your current <select>, and this.options.selectedIndex is integer value that show what option currently selected.
BTW you have an typo in your code:
document.getElementbyId
should be
document.getElementById
See jsFiddle demo
You just have a typo.
function fctCheck(food)
{
if (food == "") {
document.getElementById(food).style.display = "none";}
} else {
document.getElementById(food).style.display = "block";
}
}
should work.
this.value
is equivalent to
this.options[this.options.selectedIndex].value

Using onchange event handler to alter second select list

Have a form field asking for a product, these are various sizes, the second form field asks for the quantity.
The stock quantity of each product is shown in the first select, I want the second select to be a maximum of the stock available so customers cannot order more than I have available.
This is the first select (also linked to show custom pictures) Site is ASP
<select name="barcode" id="imageselect">
<option value>Please Select .....</option>
<option value="322974">6.6lbs 100m - £21.00 ( 2 in stock )</option>
<option value="322975">8.2lbs 100m - £21.00 ( 3 in stock )</option>
<option value="322976"disabled=disabled>10.4lbs 100m - £21.00 - Out of stock</option>
<option value="323656">13.7lbs 100ms - £21.00 ( 4 in stock )</option>
</select>
This is the second select:
<select name="quantity">
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
Have tried using onchange event but with no joy.
The UK Autotrader has a very good example of this working with their car makes / models.
This should do what you want...
NB: I've used a shot cut by adding a 'stock' attribute to your options, just to avoid parsing the string.
<option value="322974">6.6lbs 100m - £21.00 ( 2 in stock )</option>
If you want to avoid this, the example below also shows you how to get the text to parse for the stock attribute.
$("#imageselect").change(function(event){
var $this = $(this),
value = $this.val();
var $option = $("option[value="+value+"]", $this),
text = $option.text(), // you could parse this to get stock OR
stock = parseInt($option.attr('stock')); // short-cut: use stock attr
// only show the first n options:
var $opts = $("select[name=quantity] option");
$opts.hide().slice(0, stock).show();
});
The second select will show the maximum stock. So what you need to do is store the values in the database, fetch max value and as you are using asp , call the page with ajax which will be shown here as a select option

Using JQuery "select option:first-child" just for an element with a given id?

This code looks at if dropdownlist with 'townid' has an option of Central and then puts Central after the first option at all dropdownlists.
var central = $('#townid option:contains("Central")');
if(central){
central.insertAfter('select option:first-child');
}
My problem is that:
How can I add it just after dropdownlist that has id of townid? I mean something like:
var central = $('#townid option:contains("Central")');
if(central){
central.insertAfter('#townid select option:first-child');
}
For example:
<select id=townid>
<option value="5000">AL</option>
<option value="5001">NY</option>
<option value="5002">LA</option>
<option value="5003">NY</option>
<option value="5204">Central</option>
<option value="5024">FA</option>
</select>
<select id="someid">
<option value="3002">Brooklyn</option>
<option value="6001">Manhattan</option>
</select>
After that process they should be seem like:
<select id=townid>
<option value="5000">AL</option>
<option value="5204">Central</option>
<option value="5001">NY</option>
<option value="5002">LA</option>
<option value="5003">NY</option>
<option value="5024">FA</option>
</select>
<select id="someid">
<option value="3002">Brooklyn</option>
<option value="6001">Manhattan</option>
</select>
How can I add it just after dropdownlist that has id of townid?
Okay, I’m gonna assume your HTML looks something like this:
<select id="townid">
<option>
…
</option>
</select>
In that case, you could use:
$('#townid option:contains("Central")').appendTo('#townid option');
If there are multiple option elements inside #townid and you only want to select the first, just change the selector:
$('#townid option:contains("Central")').appendTo('#townid option:first');
In your example, don’t use if (central), use if (central.length) instead.
You just messed up the selector, because #townid IS the select tag.
var central = $('#townid option:contains("Central")');
if(central.length === 1){
central.insertAfter('#townid option:first-child');
}

Categories

Resources