I have a HTML select with 3 options as following -
<select id="list">
<option value="environment" selected>Environment Facing (default)</option>
<option value="user">User Facing</option>
<option value="member">Member Facing</option>
</select>
what I want to do is to toggle between these values with a button. is that possible? How can I toggle like if first option is selected and if I click button second option get selected and if second is selected after clicking again third gets selected. is there any way I can do it.
One approach could be getting the available values into an array, and finding the currently selected value's index in that array, increase it by one and see if you get a value. If you get undefined (which is what you get if you try to access an array element at a non-existing index), you instead go with the arrays's first element.
const list = document.getElementById('list');
const values = [...list.options].map(({value}) => value);
document.getElementById("button").addEventListener("click", function() {
const currentValue = list.value;
list.value = values[values.indexOf(currentValue)+1] ?? values[0];
});
<select id="list">
<option value="environment" selected>Environment Facing (default)</option>
<option value="user">User Facing</option>
<option value="member">Member Facing</option>
</select>
<button id="button" type="button">Toggle</button>
Increment the selectedIndex of the select, wrapping around when you get to the end.
document.getElementById("button").addEventListener("click", function() {
let list = document.getElementById("list");
let selected = list.selectedIndex;
selected = (selected + 1) % list.length;
list.selectedIndex = selected;
});
document.getElementById("show").addEventListener("click", function() {
let list = document.getElementById("list");
console.log(`Selected = ${list.value}`);
});
<select id="list">
<option value="environment" selected>Environment Facing (default)</option>
<option value="user">User Facing</option>
<option value="member">Member Facing</option>
</select>
<button id="button" type="button">Toggle</button>
<button id="show" type="button">Show selected</button>
Related
I want to be able to reset <select> tags by themselves instead of making them reset with the entire form. This is what I have so far:
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
And the JS:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
for (let i = 0; i < selectedOptions.length; i++) {
selectedOptions[i].selected = false;
}
}
When I first tried this, it seemed to work. However, only when one option is selected. I've noticed that when there is more than one option currently selected, it seems to break.
Starting with three options, and clicking the Reset button results in this, for some reason:
Every option gets deselected apart from one. Why does this happen?
Clicking the Reset button again deselects the one still selected option though.
You can set the selectedIndex attribute to -1 to indicate that no element is selected.
function resetS() {
const multipleSelect = document.getElementById('s');
multipleSelect.selectedIndex = -1;
}
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
The list of selected <option> elements is a "live" list. When you change the selected flag on one of the elements, the list changes; that is, the <option> you changed disappears from the list, so the length gets 1 shorter. An indexed for loop will therefore skip elements.
The way to deal with that (well, one way) is to use a while loop as follows:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
while (selectedOptions.length) {
selectedOptions[0].selected = false;
}
}
edit — or you could use the method suggested in Tom's answer, which is simpler.
I have a form with two select fields. The first select field will list items, the second select field will start empty but be populated by selecting an item from the first and pressing the add button. You would also be able to do the same. You can select an item from the second select field and hit the remove to add it back to the first select field. In the end, I want all the values of the second select field to be in a hidden form box separated by commas.
I've come across examples of this with javascript in the past, but now that I need them I can't seem to find them. Does anyone know of any sources that could show me how to accomplish something like this? At first, I was thinking of doing it using ajax but I would rather do it without loading another page. Any help in pointing me in the right direction would be greatly appreciated! Thanks in advance!
<form name="SelectItem">
<select name="SelectItem">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button>Add =></button>
<button><= Remove</button>
<select name="SelectedItems">
<option value=""></option>
</select>
</form>
You can use jquery append() to do it:
$(document).ready(function(){
$('.add').click(function(){
$('#select1').find('option:selected').appendTo('#select2');
});
$('.remove').click(function(){
$('#select2').find('option:selected').appendTo('#select1');
});
});
Working pen
You can use the add() and remove() methods on the select element:
const select1 = document.getElementById('select1')
const select2 = document.getElementById('select2')
const addItem = () => {
event.preventDefault();
if(select1.length === 0) return;
let itemIndex = select1.selectedIndex;
let item = select1.options[itemIndex];
select1.remove(itemIndex)
select2.add(item);
}
const removeItem = () => {
event.preventDefault();
if(select2.length === 0) return;
let itemIndex = select2.selectedIndex;
let item = select2.options[itemIndex];
select2.remove(itemIndex)
select1.add(item);
}
document.getElementById('addButton').addEventListener('click', addItem);
document.getElementById('removeButton').addEventListener('click', removeItem);
<form name="SelectItem">
<select name="SelectItem" id="select1">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button id="addButton">Add =></button>
<button id="removeButton"><= Remove</button>
<select name="SelectedItems" id="select2">
</select>
</form>
Below is one relatively simple approach you can take that takes advantage of event delegation technique:
const inSelectEl = document.querySelector('#in-item-list');
const outSelectEl = document.querySelector('#out-item-list');
const optionQuantity = inSelectEl.options.length;
const onClick = e => {
if (e.target.tagName !== 'BUTTON') {
return;
}
let a, b;
if (e.target.id === 'add') {
a = inSelectEl;
b = outSelectEl;
} else {
a = outSelectEl;
b = inSelectEl;
}
const selectedOption = a.options[a.selectedIndex];
b.options[b.options.length] = selectedOption;
}
document.querySelector('#container').addEventListener('click', onClick);
<!-- Added container to enable event delegation -->
<div id="container">
<select name="SelectItem" id="in-item-list">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button id="add">Add =></button>
<button id="remove"><= Remove</button>
<select name="SelectedItems" id="out-item-list" />
</div>
Currently I have a function I created that removes some options from a select menu based on a value passed from another select. I want to revert back to normal each time the function is called (add all the original options back)
HTML
<select id="Current-Tier" onchange="removetier();" class="form-control boosting-select">
<option value="100">Bronze</option>
<option value="200">Silver</option>
<option value="300">Gold</option>
<option value="400">Platinum</option>
<option value="500">Diamond</option>
</select>
<select id="Desired-Tier" class="form-control boosting-select">
<option value="100">Bronze</option>
<option value="200">Silver</option>
<option value="300">Gold</option>
<option value="400">Platinum</option>
<option value="500">Diamond</option>
</select>
JS
function removetier(){
var currentTierValue = document.getElementById("Current-Tier");
var current = currentTierValue.options[currentTierValue.selectedIndex].value;
var desiredDivisionValue = document.getElementById("Desired-Tier");
for(var i=0;i<desiredDivisionValue.length;i++){
if(desiredDivisionValue[i].value < current){
desiredDivisionValue.remove(desiredDivisionValue[i]);
}
}
Update_Desired_Rank_image();
}
Have you considered adding the hidden attribute rather than deleting them?
Then the next time you receive a request, you can go through the list programmatically and remove the hidden attribute from each option.
An example of the hidden label, BTW, is
<select id="Desired-Tier" class="form-control boosting-select">
<option value="100">Bronze</option>
<option value="200">Silver</option>
<option value="300">Gold</option>
<option value="400">Platinum</option>
<option value="500" hidden>Diamond</option>
</select>
If you run it you will see that Diamond is hidden. This way you always have access to all your options.
You can easily iterate over the select input and either store the removed items in an array or leverage the hidden attribute on the option tag:
Fiddle: https://jsfiddle.net/gLwwmh82/2/
HTML
<select id="mySelect">
<option value="">Select...</option>
<option value="test1">Test1</option>
<option value="test2">Test2</option>
<option value="test3">Test3</option>
<option value="test4">Test4</option>
<option value="test5">Test5</option>
<option value="test6">Test6</option>
</select>
<button id="btnRemove" onclick="remove()">Remove Half of Entries</button>
<button id="btnReset" onclick="reset()">Reset</button>
JS
function reset() {
var select = document.getElementById('mySelect');
var options = select.querySelectorAll('option');
for (var i = 0; i < options.length; i++) {
options[i].removeAttribute('hidden');
}
}
function remove() {
var select = document.getElementById('mySelect');
select.value = "";
var entries = select.querySelectorAll('option');
for (var i = 1; i < 5; i++) {
// Wrap the below line in your logic to know what to delete/not to delete
entries[i].setAttribute('hidden', true);
}
}
I need to create multiple identical dropdown lists, with only the first visible and when filled, the next one shows.
I found some examples and made it so that the second only shows after the first is filled, but I am unable to create a code that works for all lists (without replicating everything). I'm not a programmer, but I can see examples and kinda adapt them.
Can anyone help me?
This is what I used:
var elem = document.getElementById("q1");
elem.onchange = function(){
var hiddenDiv = document.getElementById("q2");
hiddenDiv.style.display = (this.value == "") ? "none":"block";
this.disabled = 'disabled';
};
https://jsfiddle.net/mbus6w11/6/
This is what I am proposing:
Have each select element in a div and give each of them an ID,
Add an onChange function to all of your select elements (you can leave the last one out)
In your script, set the visibility of second and third div as false,
In the onChange function, set visibility of the next select element true.
Here is the code:
<div id = "first">
<select onchange="myFunction1()">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
</div>
<div id = "second">
<select onchange="myFunction2()">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
</div>
<div id = "third">
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
</div>
Javascript:
document.getElementById("second").style.visibility = "hidden";
document.getElementById("third").style.visibility = "hidden";
function myFunction1() {
document.getElementById("second").style.visibility = "visible";
}
function myFunction2() {
document.getElementById("third").style.visibility = "visible";
}
I have a select box and add more button. when I click add more button it's creating another select using clone.In first select box I select one option value from select box means that value should be removed from next created select box.At the same time which selected value in select box that current value shown on current select box. Select box value is being loaded dynamically.
Eg:
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
Is it what you're looking for ?
I would recommend you to play and manipulate with index(), that won't bother your dynamic values.
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
$('button').click(function(){
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value="">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Clone</button>
You can try like this.
$("#yourId").val(" ")//if your value has white spec else use like below line
$("#YourId").val("")//What ever you want to be selected, place your value in .val()
I hope this will help you, if you need anything please ask!
$("button").on("click", function() {
$("#section_1")
.clone()
.attr("id", "section_2")
.on("change", function() {
var sec2Val = $(this).val();
var delOption = $("#section_1 > option[value=" + sec2Val + "]").detach();
optionHolder.push(delOption);
})
.insertAfter($("#section_1"));
$(this).attr("disabled", "disabled");
});
var optionHolder = [];
$("#section_1").on("change", function() {
var sec1Val = $(this).val();
if ($("#section_2")) {
var delOption = $("#section_2 > option[value=" + sec1Val + "]").detach();
optionHolder.push(delOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Add more</button>