Unable to click on select option dynamically - javascript

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

Related

select.getElementsByTagName except for a certain option

Option List
I have an problem where my Random Option Picker picks a certain option that I don't want. How do I mitigate this?
var select = document.getElementById('edit-categories');
var items = select.getElementsByTagName('option');
var index = Math.floor(Math.random() * items.length + 1);
return select.selectedIndex = index;
The option that I want my random picker to ommit is : value="_none"
Use querySelectorAll along with :not and an attribute selector:
var items = select.querySelectorAll('option:not([value="_none"])');
var select = document.querySelector('select');
var items = select.querySelectorAll('option:not([value="_none"])');
console.log(items);
<select>
<option value="_none">--</option>
<option value="water">Water</option>
<option value="waste">Waste</option>
</select>
As an alternative, you can also use Array.prototype.filter (since It's a lot easier to pollyfil filter than the [not] selector):
var opts = [].filter.call(document.getElementById('edit-categories').options, function(opt){return opt.value != '_none'})
console.log(opts);
<select id="edit-categories">
<option value="_none">None
<option value="foo">Foo
<option value="foo">Bar
</select>
You can add a while loop just before setting the index :
var select = document.getElementById('edit-categories');
var items = select.getElementsByTagName('option');
var index = Math.floor(Math.random() * items.length);
while (items[index].value == '_none') {
index = Math.floor(Math.random() * items.length);
}
select.selectedIndex = index;
<select id="edit-categories">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="_none">none</option>
<option value="4">4</option>
</select>

Javascript select individual option

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>

Filter options according to optgroup label text

I have one select box with a list of games and the other with filled with a list of consoles. Each game has the possibility to belong to a number of consoles. I'm looking to filter the second select box according to whichever game is selected in the first.
So for instance if I select a game like Forza Horizon that belongs to more than one console then the console select box would filter just those and hide the others.
Right now I have it setup where on a select event it captures the text value of the game. From there I figured to filter through their respective optgroup's label property, which is the console it belongs to. I just can't seem to figure out how to retrieve the other possible consoles it may belong to other than the selected option.
Fiddle
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4"></optgroup>
<option value="1">Forza Horizon 2</option>
<option value="2">The Last of Us</option>
<option value="3">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="1">Forza Horizon</option>
<option value="2">Halo</option>
<option value="3">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<option value="1">PS4</option>
<option value="2">Xbox One</option>
</select>
JS
$(function() {
var gameConsoles = $(".console-select").html();
$(".game-select").on("change", function() {
var game = $(this).find("option:selected").text(),
options = gameConsoles.filter().html(); // Not sure how to filter
if (options) {
$(".console-select").html(options);
} else {
$(".console-select").empty();
}
});
});
Update 2
You can do something like this
$(function () {
var consoleSelect = $('.console-select'),
gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var selectedGame = $(this).find("option:selected").data('game'),
games = [],
selectedCategory = $(this).find("option:selected").closest('optgroup').attr('label');
if (selectedGame) {
games = $.makeArray($(this).find('option[data-game="' + selectedGame + '"]').map(function () {
return $(this).closest('optgroup').attr('label');
}));
}
if (games.length) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return games.indexOf($(v).text()) != -1;
}).show();
consoleSelect.find('option:contains('+selectedCategory+')').prop('selected', 'selected');
} else {
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/11/
Update
I added a code to each game using the data-* attribute.
For example the below two games have the same data-game attribute which can be used to figure out that these two are of the same category.
<option value="1" data-game="FH">Forza Horizon 2</option>
<option value="2" data-game="FH">Forza Horizon</option>
Complete example
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4">
<option value="1" data-game="FH">Forza Horizon 2</option>
<option value="2" data-game="LU">The Last of Us</option>
<option value="3" data-game="BI">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="1" data-game="FH">Forza Horizon</option>
<option value="2" data-game="HA">Halo</option>
<option value="3" data-game="BI">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<option value="1">PS4</option>
<option value="2">Xbox One</option>
</select>
This is the script
$(function () {
var gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var selectedGame = $(this).find("option:selected").data('game'), games = [];
console.log(selectedGame);
if (selectedGame) {
games = $.makeArray($(this).find('option[data-game="' + selectedGame + '"]').map(function () {
return $(this).closest('optgroup').attr('label');
}));
}
console.log(games);
if (games) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return games.indexOf($(v).text()) != -1;
}).show();
} else {
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/10/
You can do something like this
$(function () {
var gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var label = $(this).find("option:selected").closest('optgroup').prop('label');
if (label) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return $(v).text() === label;
}).show();
}else{
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/5/
The code should speak for itself but it all comes down to multiple jQuery filter functions and a clone of the set with options. One advice: Use data attributes instead of relying on the option element text. I updated the fiddle, see link below.
$(function() {
var gameConsoles = $(".console-select");
var consoleOptions = gameConsoles.find('option').clone();
var gameSelect = $(".game-select").on("change", function() {
var game = $(this).find("option:selected").text();
var filteredOptions = $();
gameSelect.find('optgroup').filter(function() {
return $(this).find('option').filter(function() {
return $(this).text() == game;
}).length;
}).each(function () {
var label = $(this).attr('label');
filteredOptions = filteredOptions.add(consoleOptions.filter(function() {
return $(this).text() == label;
}));
});
gameConsoles.html(filteredOptions);
});
});
Fiddle update
Is that what you wanted?
$(".game-select").on("change", function() {
var o = $('option:selected', $(this));
if (!o.val()) {
$('.game-select optgroup').show();
$('.console-select option').show();
return;
}
$('.console-select > option').hide();
var a = $('option:contains("' + o.text() + '")').filter(function() {
return $(this).text() == o.text();
}).each(function() {
var t = $(this);
var l = t.parent().attr('label');
$('.console-select option:contains("' + l + '")').filter(function() {
return l == $(this).text();
}).show();
});
});
$(".console-select").on("change", function() {
var o = $('option:selected', $(this));
if (!o.val()) {
$('.game-select optgroup').show();
$('.console-select option').show();
return;
}
$('.game-select optgroup').hide();
console.log($('.game-select optgroup[label="' + o.text() + '"]'));
$('.game-select optgroup[label="' + o.text() + '"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4">
<option value="c1">Forza Horizon 2</option>
<option value="c2">The Last of Us</option>
<option value="c3">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="s1">Forza Horizon</option>
<option value="s2">Halo</option>
<option value="s3">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<div>
<option value="c">PS4</option>
<option value="s">Xbox One</option>
</div>
</select>

How to dynamically generate a dropdown menu [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my php, I have created two dropdown or selection lists. My drop down list below:
<select name="food">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
<select name="type">
<option value="">--</option>
<option value="Apple">Apple</option>
<option value="Lettuce">Lettuce</option>
<option value="Orange">Orange</option>
<option value="Tomato">Tomato</option>
<option value="Carrots">Carrots</option>
<option value="Mango">Mango</option>
</select>
m one page to the next.
It's possible to do this using jQuery, but it will quickly become unmanageable in a large-scale app or website.
If you go this route, I would avoid using two different select boxes, as this will force you to choose two different names for the form POST, unless you use more jQuery hackery to remedy this problem.
My suggestion is to look at a lightweight JS framework. Knockoutjs has what you need.
Look at this JSFiddle.
var fruitOpts = ["Apple", "Orange", "Mango"];
var vegOpts = ["Lettuce", "Tomato", "Carrots"];
$("#food").change(function () {
var val = $(this).val();
if (val === "") {
return;
}
$("#type").find('option').not(':first').remove().end();
$.each(val === "Fruits" ? fruitOpts : vegOpts, function (i, v) {
$("#type").append("<option value=\"" + v + "\">" + v + "</option>");
});
$.each(val === "Fruits" ? vegOpts : fruitOpts, function (i, v) {
$("#type").append("<option value=\"" + v + "\">" + v + "</option>");
});
});
It's version for two different php pages:
1.php
<script src="1.js"></script>
<a id='link' href='2.php'>go to another page</a>
<select id="food" name="food" onchange="selectFoodType()">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Berries">Berries</option>
</select>
1.js
function selectFoodType()
{
var link = $('#link');
var type = $('select#food option:selected').val();
link.attr('href', link.attr('href') + '?type=' + type);
}
2.php
<script src="2.js"></script>
<select id='type' name="type" data-type='<?=$_GET['type']?>'>
<option value="">--</option>
<option data-type='Fruits' value="Apple">Apple</option>
<option data-type='Vegetables' value="Tomato">Tomato</option>
<option data-type='Vegetables' value="Carrots">Carrots</option>
<option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
2.js
$(function() {
var type = $('select#type').data('type');
var itemsId = document.getElementById("type");
var items = itemsId.getElementsByTagName("option");
var selected_type = [], other_types = [];
selected_type[0] = items[0];
for (var i = 1; i < items.length; i++){
if ($(items[i]).data('type') === type) {
selected_type.push(items[i]);
continue;
}
other_types.push(items[i]);
}
selected_type = selected_type.sort(sortByName);
other_types = other_types.sort(sortByName);
$.merge(selected_type, other_types);
var list = '';
for (i=0; i<selected_type.length; i++) {
list += selected_type[i].outerHTML;
}
$(items).remove();
$(itemsId).append(list);
});
function sortByName(a, b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
return 0;
}
You should assign all Fruits and Vegetables contents in JavaScript object and display related contents of food value in another drop down, see below demo
Food:
<select name="food" id="food">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
Content
<select name="contents" id="contents">
<option value="">...</option>
</select>
JS code
var data = {
'Fruits':['Apple', 'Lettuce', 'Orange', 'Mango'],
'Vegetables': ['Tomato', 'Carrots']
};
document.getElementById("food").onchange = function(Event){
var contents = document.getElementById("contents");
contents.innerHTML = "";
for(var i in data[this.value]){
var option = document.createElement("option");
option.setAttribute('value',data[this.value][i]);
option.text = data[this.value][i];
contents.appendChild(option);
}
var expect_data = Event.target.value == "Fruits" ? "Vegetables" : "Fruits";
for(var i in data[expect_data]){
var option = document.createElement("option");
option.setAttribute('value',data[expect_data][i]);
option.text = data[expect_data][i];
contents.appendChild(option);
}
}
FIDDLE DEMO
you need to use JQuery for this purpose.
See My Solution: http://jsfiddle.net/inventorx/YU4vJ/
Code Here:
HTML
<select name="food" >
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
<select name='type' >
<option>-- Select Food Type --</option>
</select>
<select id='Fruits' style='display:none' >
<option value="">--</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
<option value="Mango">Mango</option>
</select>
<select id='Vegetables' style='display:none' >
<option value="">--</option>
<option value="Lettuce">Lettuce</option>
<option value="Tomato">Tomato</option>
<option value="Carrots">Carrots</option>
</select>
JQUERY
$(document).ready(function(){
$("select[name='food']").on("change", function(){
var value = $(this).val();
$("select[name='type']").html($("#" + value).html());
});
});
Another option.
The list splits into two arrays: food, corresponding to the selected type; and does not correspond to the selected type. Each of these arrays, in turn, is sorted by name:
JSFIDDLE
HTML:
<select id="food" name="food" onchange="selectFoodType()">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Berries">Berries</option>
</select>
<select id='type' name="type">
<option value="">--</option>
<option data-type='Fruits' value="Apple">Apple</option>
<option data-type='Vegetables' value="Lettuce">Lettuce</option>
<option data-type='Vegetables' value="Tomato">Tomato</option>
<option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
JQuery:
function selectFoodType()
{
var type = $('select#food option:selected').val();
var itemsId = document.getElementById("type");
var items = itemsId.getElementsByTagName("option");
var selected_type = [], other_types = [];
selected_type[0] = items[0];
for (var i = 1; i < items.length; i++){
if ($(items[i]).data('type') === type) {
selected_type.push(items[i]);
continue;
}
other_types.push(items[i]);
}
selected_type = selected_type.sort(sortByName);
other_types = other_types.sort(sortByName);
$.merge(selected_type, other_types);
var list = '';
for (i=0; i<selected_type.length; i++) {
list += selected_type[i].outerHTML;
}
$(items).remove();
$(itemsId).append(list);
}
function sortByName(a, b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
return 0;
}

Compose a link based in select's option value

I have 2 dropdown menus, and I need to compose a link with it's values.
Here is the code:
<form id="dropdown1">
<select id="linha">
<option value="G12">Option 1</option>
<option value="G11">Option 2</option>
<option value="H89">Option 3</option>
</select>
<select id="dia">
<option value="all">Every day</option>
<option value="work">working days</option>
<option value="sat">saturday</option>
<option value="sun">sunday</option>
</select>
</form>
I need something in JavaScript to "compose" a link with http://somewebsite.com/*selected_linha_value*/*selected_dia_value*
How can I do that?
<select name="dia" id="dia">
<option value="all">Every day</option>
<option value="http://stackoverflow.com">working days</option>
<option value="http://anotherSite.com">saturday</option>
<option value="http://anotherSite2.com">sunday</option>
</select>
<script>
$("#dia").change(function () {
var selctedValue = "";
$("select option:selected").each(function () {
selctedValue += $(this).val();
window.location.href = selctedValue;
});
});
i think u need something like this.
<script type="text/javascript">
params = getParams();
var name1 = unescape(params["linha"]);
switch(name1)
{
case "g12":
window.location = "http://www.google.com"
}
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
Its not the full code. It will give you some idea. If you have any doubt just comment
Take a look at: http://jsfiddle.net/ERHhA/
You can use jQuery val() to get the value of the select boxes. Then just append these values to the base url.
var url = "http://somewebsite.com/" + $('#linha').val() + "/" + $('#dia').val();
What about this one?
function make_url(){
var linha = document.getElementById('linha').value;
var dia = document.getElementById('dia').value;
var url=window.location.href;
var pos=url.indexOf('?');
if (pos>-1){
url = url.substr(0,pos);
}
//alert(url + '?linha='+linha+'&dia='+dia); return;
document.location.href = url + '?linha='+linha+'&dia='+dia;
}
fiddle
HTML
<div class="container">
<select class="small-nav">
<option value="" selected="selected">Go To</option>
<option value="http://whiterabbitexpress.com">Services</option>
<option value="http://shop.whiterabbitjapan.com">Shop</option>
</div><!-- container -->
JScript:
$(".small-nav").change(function() {
window.location = $(this).find("option:selected").val();
});

Categories