Javascript select individual option - javascript

I have been trying lately to make a function that on change on the select box it return only the selected option value.
My markup looks like this:
<select id='rangeSelector'>
<option value='custom'>Custom</option>
<option value='7 days'>7 days</option>
<option value='14 days'>14 days</option>
<option value='WTD'>WTD</option>
<option value='MTD'>MTD</option>
<option value='QTD'>QTD</option>
<option value='YTD'>YTD</option>
</select>
and the javascript function:
var rangeSelector = document.getElementById('rangeSelector');
rangeSelector.addEventListener('change', function(e) {
var x = rangeSelector.children;
for (var i = 0; i < x.length; i++) {
var newX = x[i].value;
console.log(newX);
}
}, false);
What I am trying to do is when I click on 7 days to return only 7 days.

Don't read the <option>s. Read the <select>.
document.getElementById('rangeSelector').value
Other interesting bits include .selectedIndex and .selectedOptions.
(Of course, as Abhitalks notes in the comments, in your handler, the element getting will already done for you.)

var rangeSelector = document.getElementById('rangeSelector');
rangeSelector.addEventListener('change', function(e) {
console.log(rangeSelector.value);
}, true);
You do not need for loop for that, after firing event "change" rangeSelector.value already have value of chosen element.
so if you wanna add "active" to selected option you can do same:
var rangeSelector = document.getElementById('rangeSelector');
rangeSelector.addEventListener('change', function(e) {
var x = rangeSelector.children;
var y = rangeSelector.selectedIndex;
x[y].className = x[y].className + " active";
console.log(rangeSelector.value);
}, true);
but you should remove "active" class from all non-active, by looping them:)
var rangeSelector = document.getElementById('rangeSelector');
rangeSelector.addEventListener('change', function(e) {
var x = rangeSelector.children;
var y = rangeSelector.selectedIndex;
for (var i = 0; i < x.length; i++) {
x[i].className = ""; //or x[i].removeAttribute("class");`
}
x[y].className = x[y].className + " active";
console.log(rangeSelector.value);
}, true);

You could use jQuery for this, example:
$("#rangeSelector").on("change", function() {
var rangeSelect = document.getElementById("rangeSelector");
var value = selectJaar.options[rangeSelect.selectedIndex].value;
return value;
});
This first gets the dropdown, then get the selected value, and return it.

Try simply using this.value:
document.getElementById('rangeSelector').addEventListener('change', function(e) {
alert(this.value);
});
<select id='rangeSelector'>
<option value='custom'>Custom</option>
<option value='7 days'>7 days</option>
<option value='14 days'>14 days</option>
<option value='WTD'>WTD</option>
<option value='MTD'>MTD</option>
<option value='QTD'>QTD</option>
<option value='YTD'>YTD</option>
</select>

Related

Unable to click on select option dynamically

Why am I not able dynamically click on each #cars option?
let carscount = $('#cars > option').length;
console.log(carscount);
var x = carscount;
var interval = 1000;
for (var i = 0; i < x; i++) {
let counter = 1;
setTimeout(function () {
$('#cars').click();
$('#cars > option:eq('+counter+')').click();
counter++;
}, i * interval)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Programatically clicking UI controls is not best practise as cross browser / cross device support will vary. If you want to programatically pre-select an option just do myList.value = "audi"
If i got your point you can use this way to change the select's value .. using .each() to loop through the options then use setTimeout() in the .each() and to get the selected value you can add change event for the select
var interval = 1000;
$('#cars > option').each(function(i){
var ThisVal = $(this).val();
setTimeout(function () {
$('#cars').val(ThisVal).change();
}, i * interval)
});
$('#cars').on('change' , function(){
console.log(this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
And with your code you need to make some changes to let it work
let carscount = $('#cars > option').length - 1;
console.log(carscount);
var x = carscount;
var interval = 1000;
let counter = 0;
for (var i = 0; i < x; i++) {
setTimeout(function () {
$('#cars').val($('#cars > option:eq('+counter+')').val()).change();
counter++;
}, i * interval)
}
$('#cars').on('change' , function(){
console.log(this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Note: because :eq() index starts from 0 and .length starts from 1
.. you need to - 1 the .length

Add new option to dropdown if none of the existing one match certain string exist using javascript

I have this drop down that I compare with an array. If a value in the array matches the text of one of the options in the dropdown, then it is selected:
JS -Step One:
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns ('topicSelect',topicArray);
Dropdown
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option selected="" value=""></option>
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS - Step Two:
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
for (var d = 0; d < array.length; d++) {
for (var i = 0; i < select[0].options.length; i += 1) {
if (select[0].options[i].text === array[d]) {
select[0].options[i].selected = true;
}
}
}
}
Here comes my issue: The the code showed above works just fine, but I would like to be able to add a new option if an option with the same array value doesn't exist. In the example shown above, there are two values ('Apple' and 'Tomatoes") values in the array. When I iterate through the array and the dropdown, the 'Apple' option is selected, but, how can I then add a new 'Tomatoes' options, and then select it also? Thanks in advance, please let me know if more details are needed.
I would like to be able to add a new option if an option with the same array value doesn't exist..
you can clone an option node modify it and append it to parent node,
in the snippet I added a dedicated function;
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
outer:
for (var d = 0; d < array.length; d++) {
for (var i = 0; i < select[0].options.length; i += 1) {
if (select[0].options[i].text === array[d]) {
select[0].options[i].selected = true;
continue outer;
}
//if you haven't matched and are in last loop
if ( i === select[0].options.length - 1) {
addOpt(array[d], select[0].options[i])
}
}
}
}
function addOpt(x,clone){
var node = clone.cloneNode();
node.selected= true;
node.value= node.innerHTML= x;
clone.parentNode.appendChild(node)
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns ('topicSelect',topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option selected="" value=""></option>
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
One approach, using ES6 syntax is the following:
function populateExistingDropDowns(dd, array) {
// using 'let' rather than 'var' to declare variables,
// using document.querySelector(), rather than
// getElementsByClassName(), because d.qS has support
// in IE8 (whereas it does not support
// getElementsByClassName()); however here we get the
// first element that matches the selector:
let dropdown = document.querySelector('.' + dd),
// retrieving the collection of option elements,
// HTMLSelectElement.options, and converting that
// collection into an Array using Array.from():
options = Array.from(dropdown.options);
// iterating over each of the topics in the passed-in
// array, using Array.prototype.forEach():
array.forEach(function(topic) {
// filtering the array of <option> elements to keep
// only those whose text property is equal to the
// current topic (from the array):
let opts = options.filter(opt => topic === opt.text);
// if the opts Array has a truthy non-zero length:
if (opts.length) {
// we iterate over the returned filtered Array
// and, using Arrow function syntax, set each
// node's selected property to true:
opts.forEach(opt => opt.selected = true);
} else {
// otherwise, if the current topic returned no
// <option> elements, we find the <optgroup>
// holding the 'Crops' and append a new Child
// using Node.appendChild(), and the new Option()
// constructor to set the option-text, option-value
// default-selected property and selected property:
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
function populateExistingDropDowns(dd, array) {
let dropdown = document.querySelector('.' + dd),
options = Array.from(dropdown.options);
array.forEach(function(topic) {
let opts = options.filter(opt => topic === opt.text);
if (opts.length) {
opts.forEach(opt => opt.selected = true);
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS Fiddle demo.
To recompose the above, using ES5:
function populateExistingDropDowns(dd, array) {
// using 'var' to declare variables:
var dropdown = document.querySelector('.' + dd),
// using Array.prototype.slice(), with
// Function.prototype.call(), to convert the collection
// of <option> element-nodes into an Array:
options = Array.prototype.slice.call(dropdown.options, 0);
array.forEach(function(topic) {
// using the anonymous functions available to the
// Array methods, rather than Arrow functions,
// but doing exactly the same as the above:
var opts = options.filter(function(opt) {
return topic === opt.text
});
if (opts.length) {
opts.forEach(function(opt) {
opt.selected = true;
});
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
function populateExistingDropDowns(dd, array) {
var dropdown = document.querySelector('.' + dd),
options = Array.prototype.slice.call(dropdown.options, 0);
array.forEach(function(topic) {
var opts = options.filter(function(opt) {
return topic === opt.text
});
if (opts.length) {
opts.forEach(function(opt) {
opt.selected = true;
});
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS Fiddle demo.
References:
Array.from().
Array.prototype.filter().
Array.prototype.forEach().
Arrow functions.
document.querySelector().
HTMLOptionElement.
HTMLSelectElement.
let statement.
Node.appendChild().
Option() Constructor.
var statement.
Thank you all that responded to my question. I ended up using this instead:
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
var opt = document.createElement('option');
for (var d = 0; d < array.length; d++) {
for (var q = 0; q < select[0].length; q++) {
if (select[0].options[q].text !== array[d]) {
opt.value = array[d];
opt.text = array[d];
select[0].children[1].appendChild(opt);
opt.selected = true;
} else {
select[0].options[q].selected = true;
}
}
}
}
Fiddle

javascript function freezing my browser

i have two select object one with begining time and one with ending time.
when i select for example 11:00 in begining time i want that all options before 11:00 in ending time bee disabled 11:15 selected and rest options selectable.
Also i want to say that i am newbie with javascript.
This is part of my HTML code:
<select id="rbaslasaat" onchange="bitissaati(1384581600, 1384586100);">
<option value="1384581600">10:00</option>
<option value="1384582500">10:30</option>
<option value="1384583400">11:00</option>
<option value="1384584300">11:30</option>
<option value="1384585200">12:00</option>
<option value="1384586100">12:30</option>
</select></div>
<select id="rbitirsaat">
<option id="saatb1384581600" value="1384581600" disabled="">10:00</option>
<option id="saatb1384582500" value="1384582500" disabled="">10:30</option>
<option id="saatb1384583400" value="1384583400" disabled="">11:00</option>
<option id="saatb1384584300" value="1384584300" disabled="">11:30</option>
<option id="saatb1384585200" value="1384585200" disabled="">12:00</option>
<option id="saatb1384586100" value="1384586100" disabled="">12:30</option>
</select></div>
and this is my JavaScript function:
function bitissaati(saata, saatb) {
var saata, saatb, saatc, saatca, sec, i;
saatc = document.getElementById('rbaslasaat');
saatca = saatc.options[saatc.selectedIndex].value;
sec = parseInt(saatca) + 900;
for (i = saata; i<= saatb; i + 900) {
if(i <= saatca ) { document.getElementById('saatb'+i).disabled=true; }
else { document.getElementById('saatb'+i).disabled=false; }
}
document.getElementById('saatb'+sec).selected=true;
}
i could not figured out what the problem is.
each time i try function my browser is freezing.
Thank you all for trying to help
get your code fixed:
for ( i = saata; i<= saatb; i += 900) {
edit: removed the var
I'd just do :
function bitissaati(elem) {
var opt = document.getElementById('rbitirsaat').getElementsByTagName('option'),
val = elem.value;
for (i=opt.length; i--;) {
opt[i].disabled = opt[i].value <= val;
}
}
FIDDLE
Replace the loop with this
for (var k = saata; k<= saatb; k += 900) {
if (k <= saatca) {
document.getElementById('saatb'+k).disabled=true;
}
else {
document.getElementById('saatb'+k).disabled=false;
}
}

Adding Option to Drop Down Value if it doesn't exist?

How can the code below be modified so as to allow a new value to be added to the drop down list, should the specified value not be found in the found in the drop down box?
Right now, I use the given function below to find a given value (option_name) in a drop down box.
I'd like to modify the negative flag (!flag) so as to instead of alerting me that it not has found the option_name, to basically add the new option_name in the existing drop down list.
ie.
get_position( 'drop', 'flower' )
<select id="drop" style="width: 200px;">
<option value="0"></option>
<option value="1">apples</option>
<option value="2">oranges</option>
<option value="3">pears</option>
<option value="4">mangos</option>
<option value="5">bananas</option>
<option value="6">kiwis</option>
</select>
function get_position(id,option_name) {
var flag = false;
for ( var i=0; i <= document.getElementById(id).options.length - 1; i++ ) {
if (document.getElementById(id).options[i].text === option_name) {
document.getElementById(id).selectedIndex = i;
flag = true;
}
}
}
you can use return false if any match found then add the record
function get_position(id,option_name) {
var flag = false;
var length=document.getElementById(id).options.length;
for ( var i=0; i <= length - 1; i++ ) {
if (document.getElementById(id).options[i].text == option_name) {
document.getElementById(id).selectedIndex = i;
return false;
}
}
//add item on drop down now
document.getElementById(id).options[length] = new Option( txt, length );
document.getElementById(id).selectedIndex = length;
}
if you can use Jquery then some thing like this
if($("#id option:contains('option_name')").length ==0)
{
$("#id").append(new Option("option text", "value"));
}

hide elements of the select dropdown

I have a 2 select dropdowns each of them have bunch of elements (just an example below).
<select id="one">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<select id="two">>
<option>2</option>
<option>4</option>
<option>6</option>
<option>8</option>
</select>
How do I ide some options in second dropdown when the first dropdown element is selected. (for example, if 1 is selected in dropdown #1, then 1+2=2 option should be hidden in dropdown #2, if 2 is seected in #1, then 2+2=(4) should be hidden in #2. etc.
I guess I need to approach it with something like this:
document.getElementById("one").onchange = function( ){
var selectedOption = document.getElementById("one").options[document.getElementById("one").selectedIndex].text;
}
What should I do next?
Without jQuery:
document.getElementById("one").onchange = function( ){
var selectedOption = this.options[this.selectedIndex].text;
var option = getElementByText(document.getElementById("two"), selectedOption * 2);
option.style.display = "none"; // or u car remove it here
}
function getElementByText(parent, text) {
for (var i = 0; i < parent.children.length; i ++) {
if (parent.children[i].text == text) {
return parent.children[i];
}
}
return false;
}
jsfiddle
Selecting 1 removes 2, 2 removes 4, 3 removes 6, 4 removes 8 from second dropdown.
<script>
function updateSet2(sel){
var select2 = document.getElementById("two");
select2.options.length = 0; //clear
//repopulate
select2.options[0] = new Option('2', '2');
select2.options[1] = new Option('4', '4');
select2.options[2] = new Option('6', '6');
select2.options[3] = new Option('8', '8');
//remove selected
select2.options.remove(sel - 1);
}
var select1 = document.getElementById("one");
select1.onchange = function(e){
var selected = this.options[this.selectedIndex]
updateSet2(selected.text);
}
</script>
another option:
<script>
var doChange = (function() {
var storedSel;
return function () {
var sel0 = this;
var sel1 = sel0.form.sel1;
var opt;
storedSel = storedSel || sel1.cloneNode(true);
// Show all options of sel1
sel1.parentNode.replaceChild(storedSel.cloneNode(true), sel1);
sel1 = sel0.form.sel1;
// Hide some based on selection
if (sel0.value == 1) {
sel1.removeChild(sel1.options[3]);
sel1.removeChild(sel1.options[1]);
} else if (sel0.value == 2) {
sel1.removeChild(sel1.options[2]);
}
}
}());
window.onload = function() {
document.forms.f0.sel0.onchange = doChange;
}
</script>
<form id="f0">
<select name="sel0" size="4">
<option value="0">0
<option value="1">1
<option value="2">2
<option value="3">3
</select>
<select name="sel1" size="4">
<option value="4">4
<option value="5">5
<option value="6">6
<option value="7">7
</select>
</form>

Categories