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

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)

Related

Compare select values and show alert if they match

I have 4 dropdowns from which you have to select an option.
What I am trying to do is show an alert if you chose the same option more than once. Its purpose is to keep the score for a game so a person shouldn't be able to play as 2.
At the moment the dropdown looks like this:
<select id="users_1" aria-labelledby="dropdownMenu1">
<option>Select player</option>
<?php foreach($users as $user) : ?>
<option value="<?=$user['id_user']?>"><?=$user['nume']?></option>
<?php endforeach; ?>
</select>
And what I've tried to do in JQuery is this:
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
And I also tried to compare them like this:
$("#users_2").change(function() {
if($(this).val() == $("#users_1").val()) {
alert($(this).val());
}
});
None seems to work and I have no clue why. I've checked and the actual values are taken from the view but the if clause cannot compare them apparently.
Thank you for any help! Much appreciated!
Get your values, don't set them
Change this…
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
…to this…
$("#users_2").change(function() {
var a = $("#users_1").val();
var b = $(this).val(); // equivalent to $("#users_2").val()
if(a === b) { // Use strict comparison operator as a best practice
alert(a + ' matches ' + b);
}
});
Make it dynamic
You can take it a step farther by listening to a set of elements and making your handler dynamic:
// Listen to set of all select elements.
$('select').on('change', function(e) {
// Serialize form values.
var vals = $('#select_player').serializeArray();
// Convert to simple array of just values.
vals = $.map(vals, function (val, i) {
return val.value;
});
// Remove current selection from array…
vals.splice(vals.indexOf($(this).val()), 1);
// …then check to see if it's value was already there.
if(vals.indexOf($(this).val()) !== -1) { // If value is found,
// …reset current select element to default option,
$(this).val('default');
// …and alert user with a relevant message.
alert('You cannot select this player more than once.');
};
});
label {
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="select_player" name="select_player">
<label>Player 1:
<select id="users_1" name="users_1">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 2:
<select id="users_2" name="users_2">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 3:
<select id="users_3" name="users_3">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 4:
<select id="users_4" name="users_4">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
</form>
I used the same class on all the dropdowns and then use only one event handler.
$('.dropdown').on('change', function (event) {
var selectedValue = $(event.currentTarget).val();
var matchedDropdowns = $('.dropdown').filter(function (index) {
return $(this).val() === selectedValue;
});
if (matchedDropdowns.length > 1) {
alert("Alert Alert!")
}
})
In the event handlers I can get the selected value, filter all the dropdowns that match that value and if I get more than 1 dropdown I will just show the alert.
You can check it on fiddle.

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)
});
});

Getting values from an HTMLCollection to a string

I am attempting to grab the selected values of a multi-select dropdown and convert them into a single string for later manipulation. At the moment I have the following code:
function newComic()
{
var elem = document.querySelector("#genreList").selectedOptions;
var arr = [].slice.call(elem);
var genres = arr.join(', ');
window.alert(genres);
}
<select id="genreList" multiple="multiple" name="addGenre[]" style="width: 150px;font-size: 10pt;">
<option value="Action">Action</option>
<option value="Comedy">Comedy</option>
<option value="Fantasy">Fantasy</option>
<option value="Horror">Horror</option>
<option value="Mystery">Mystery</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Period">Period</option>
<option value="Romance">Romance</option>
<option value="Sci-Fi">Sci-Fi</option>
<option value="Thriller">Thriller</option>
</select></p>
<p><input type="button" onclick="newComic()" value="Add Comic" id="btnAddComic" style="font-size: 10pt; width: 150px; height:40px;"></p>
The alert window is currently outputting the following:
[object HTMLOptionElement, object HTMLOptionElement, ...]
where '...' represents any further hypothetical options.
What I need is for 'genres' to output as, for example, 'Action, Romance, Thriller' instead.
Thanks in advance for any help.
When you join the array, it is calling the "toString" of each element. In this case, they are DOM elements and return their type. You can use map first to create a new array of strings containing the value of each option:
http://jsfiddle.net/Lfx6r5sm/
var genres = arr.map(function(el){
return el.value;
}).join(', ');
You could iterate through the selected items like so:
<script type="text/javascript">
function newComic(){
var elem = document.querySelector("#genreList").selectedOptions;
var arr = [];
for(var x=0; x<elem.length; x++){
// for the TEXT value
//arr.push(elem[x].text);
// for the value
arr.push(elem[x].value);
}
var genres = arr.join(', ');
window.alert(genres);
}
</script>
You need to iterate through HTMLCollection like this
<script>
function newComic()
{
var elem = document.querySelector("#genreList").selectedOptions;
console.log(elem);
for (var i = 0; i < elem.length; i++) {
console.log(elem[i].attributes[0].nodeValue); //second console output
}
}
</script>
I think jquery is best suited for this task.
HTML
<select id="genreList" multiple="multiple" name="addGenre[]" style="width: 150px;font-size: 10pt;">
<option value="Action">Action</option>
<option value="Comedy">Comedy</option>
<option value="Fantasy">Fantasy</option>
<option value="Horror">Horror</option>
<option value="Mystery">Mystery</option>
<option value="Non-Fiction">Non-Fiction</option>
<option value="Period">Period</option>
<option value="Romance">Romance</option>
<option value="Sci-Fi">Sci-Fi</option>
<option value="Thriller">Thriller</option>
</select>
<p><input type="button" value="Add Comic" id="btnAddComic" style="font-size: 10pt; width: 150px; height:40px;"></p>
jQuery
$("#btnAddComic").click(function(){
var inz = $( "#genreList option:selected" ).map(function(){
return $(this).text();
}).get().join(',');
alert(inz);
});
SEE THE FIDDLE
http://jsfiddle.net/inzamamtahir/1bm45gu7/2/

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.

Take out option from 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.

Categories

Resources