Take out option from JavaScript - javascript

How to take out option value = 0 using JavaScript from below:
<select>
<option value=0>0</option>
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>

var select = document.getElementsByTagName("select")[0];
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].value === "0") {
select.remove(i);
}
}
See a live example. Annoyingly the value is a string so you have to === compare to the string. And getting the select by tagName assuming it's the only select on the page is prone to failure
using
<select id="foo"> ... </select>
and
var select = document.getElementById("foo");
Would be better.

If you can use jQuery:
$('select > option[value=0]').remove();
Obviously you should use the id of the select instead of select or you will hit all select items on that page.

Related

How to change HTML element without ID using Javascript?

I have a list with 250 countries in a HTML dropdown(for the sake of space I've only included 5 below):
<select name="postalCountry" class="valid">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK">Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
Unfortunately I cannot edit the HTML element themselves, so I was wondering if there is a way to hide all of them except for Alaska (value=AK) using Javascript?
I currently have the following:
var country = document.querySelectorAll('select[name="postalCountry"] option');
var e;
for (e = 0; e < country.length; e++){
country[e].style.display = 'none';
}
country[2].style.display = 'initial';
But that gets a bit messy since I would have to go through a lot of countries to find out the index number of a country at the end of the list.
Any suggestion is greatly appreciated !
If you are only going to style them it's better to just use CSS:
select[name="postalCountry"] option
{
display: none;
}
select[name="postalCountry"] option[value="AK"]
{
display: initial;
}
<select name="postalCountry" class="valid">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK" selected>Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option
Edit: added selected attribute so "Alaska" is selected by default initially.
Perhaps you can use the "value" of each option like follows
var country = document.querySelectorAll('select[name="postalCountry"] option');
for (var e = 0; e < country.length; e++){
if(country[e].value == "AK"){
country[e].style.display = 'initial';
document.getElementById("country_select").value = country[e].value;
} else {
country[e].style.display = 'none';
}
}
<select name="postalCountry" id="country_select" class="valid">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK">Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
</select>
Use JavaScript to make Alaska the first element of the select element, and set the select's value to "AK":
var sel = document.querySelector('select[name="postalCountry"]');
optAK = document.querySelector('option[value="AK"]');
sel.prepend(optAK);
sel.value = 'AK';
In CSS, hide all but the first option:
select[name="postalCountry"] option:not(:first-child) {
display: none;
}
That will overcome a bug in Chrome which shows the first option even if it's hidden.
Snippet:
var sel = document.querySelector('select[name="postalCountry"]');
optAK = document.querySelector('option[value="AK"]');
sel.prepend(optAK);
sel.value = 'AK';
select[name="postalCountry"] option:not(:first-child) {
display: none;
}
<select name="postalCountry" class="valid">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK">Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
</select>
Before we start: the aceppted answer is right and works well.
Here's an alternative approach showing the use of ES2015 spread operator (...) to iterate through a NodeList as an Array. This way we can use find method to target the right <option> without the use of formal loops and conditions.
Remeber that it only works in browsers that supports the spread operator (anything but IE). Also, note that it's a kind of syntax sugar which can be considered better or worst based on personal preferences but being a little slower than the traditional iterational approach, so use with sense.
let options = [...document.querySelectorAll('#country_select option')]
options.forEach(e => e.style.display = 'none')
let selected = options.find(e => e.value === 'AK')
selected.style.display = 'initial'
selected.selected = true
<select id="country_select">
<option value="AF">Afghanistan</option>
<option value="AX">Aland Islands</option>
<option value="AK">Alaska</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
</select>

JavaScript - how to remove `options` by its `value`

I have a dropdown menu with products similiar like this
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananes</option>
<option value="3" >Apples</option>
</select>
I need to remove options by its value. How to do that ?
Pure JavaScript please.
EDIT : I know that I need to use element.removeChild(child) method. But how to reference child by its value. Thats my point.
EDIT 2 : I use the script of zdrohn below and it works. Because I have several fruits dropdowns with the same collection I need to iterate trough all dropdowns and delete it from all dropdowns. This is my code now :
<script type='text/javascript'>
var id = 3;
var el= document.getElementsByClassName("fruits");
for (i=0;i<el.length;i++) {
for(var n = 0; n < el[i].length; n++) {
if(el[i][n].value == id) {
el[i][n].remove();
}
}
</script>
Though it works I wonder about that I do not need to use the parent.removeChild() method. How comes ?
P.S. I wonder that peole vote this question down. As the response shows their are several solutions. Though not all are sufficiantly explained.
Here is a snippet to play with.
The code removes the option with value = 3
window.onload = function() {
var optionToDelete = document.querySelector("select.fruits > option[value='3']");
optionToDelete.parentNode.removeChild(optionToDelete);
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
EDIT: Based on the updated question - I have several fruits drop-downs.
We could make use of querySelectorAll to select all matching elements and forEach to apply the desired logic on each element in the selected list.
window.onload = function() {
var optionsToDelete = document.querySelectorAll("select.fruits > option[value='3']");
optionsToDelete.forEach(function(element, index, array) {
element.parentNode.removeChild(element);
});
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
<select class="fruits">
<option value="1">Seville oranges</option>
<option value="2">Burro Bananes</option>
<option value="3">Baldwin Apples</option>
</select>
<select class="fruits">
<option value="1">Bergamot oranges</option>
<option value="2">Red Bananes</option>
<option value="3">Gravenstein Apples</option>
</select>
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananas</option>
<option value="3" >Apples</option>
</select>
<script type='text/javascript'>
var valueToRemove = 1;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
</script>
Edit:
<select class="fruits" >
<option value="1">Oranges</option>
<option value="2">Bananas</option>
<option value="3">Apples</option>
</select>
<br>
<label>Input value to delete</label><input type='text' id='delete_value'>
<button onclick='remove(document.getElementById("delete_value").value)'>Delete</button>
<script type='text/javascript'>
function remove(item) {
var valueToRemove = item;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
}
</script>
You can select the desired option by using document.querySelector() and a selector of this form
A more complete list of selectors can be found here
Example
var element = document.evaluate( '//option[#value="1"]' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
element.parentNode.removeChild(element)

Make multiple select menus jump to the first option

I've got 2 select menus. Example below.
How do I make both select menus jump to the first option when a button is clicked?
<select class="personlist">
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<select class="personlist">
<option value="Ten">Ten</option>
<option value="Eleven">Eleven</option>
</select>
I came across similar posts while googling. But was not able to get it right.
document.getElementsByClassName('personlist').value=[0];
getElementsByClassName returns an HTMLCollection object which is an array like object so you need to iterate over it and set the value
function reset() {
var els = document.getElementsByClassName('personlist');
for (var i = 0; i < els.length; i++) {
els[i].options[0].selected = true;
}
}
<select class="personlist">
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<select class="personlist">
<option value="Ten">Ten</option>
<option value="Eleven">Eleven</option>
</select>
<button onclick="reset()">d</button>
If you JQuery, you can use :
$('#select-a').click(function() {
$('select.personlist').each(function() {
$(this).find('option').first().prop('selected', true)
});
});

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

select first drop down to be the same value as the other drop down

I would like to select all drop down to be the same as the value selected from the primary dropdown. I got it to work if there is one select selected from the primary dropdown, but will not work if there are two selects, I have added some code below for your information.
HTML:
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown();">
<option value="" selected>Select Name</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>
<select id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>
<select id="Qualifications" name="Qualifications">
<option value="select">select</option>
<option value="Pass">Pass</option>
<option value="Fail">Fail</option>
</select>
JavaScript:
function setDropDown() {
var index_name=document.QualificationForm.ForceSelection.selectedIndex;
document.QualificationForm.Qualifications.selectedIndex=index_name;
}
Try this
function setDropDown() {
var index_name =
document.getElementsByName('ForceSelection')[0].selectedIndex;
var others = document.getElementsByName('Qualifications');
for (i = 0; i < others.length; i++)
others[i].selectedIndex = index_name;
}
You could possibly use the following, though currently untested:
function setDropDown(el){
if (!el) {
return false;
}
else {
var index = el.selectedIndex,
selects = document.getElementsByName('qualifications');
for (var i=0, len=selects.length; i<len; i++){
selects[i].selectedIndex = index;
}
}
}
This requires that you pass the #ForceSelection select element into the function, and so is called like:
<select name="ForceSelection" id="ForceSelection" onChange="javascript:return setDropDown(this);">
<!-- other stuff -->
</select>
The selectedIndex of this passed-in element will be applied to the other select elements with the name of qualifications.
Also, please allow me to reiterate: an id must be unique within the document in order to be valid HTML.

Categories

Resources