I have a problem with Javascript. I'm trying to set a background image for an option in a multi select box. This works with Firefox 3.6.14, but not with Internet Explorer 8. I have made a short code sample to show you the problem. Does anyone have a solution for my problem?
<html>
<head>
<script language="javascript" type="text/javascript">
function changeIssueTypes(){
var testSelect = document.getElementById("testSelect");
var comboBoxTest = document.getElementById("comboBoxTest");
testSelect.options.length = 0;
if(comboBoxTest.value == 'optionTest1')
{
testSelect.options[0] = new Option();
testSelect.options[0].value = 'testOption1';
testSelect.options[0].innerHTML = 'Test option 1';
testSelect.options[0].style.backgroundImage = 'url(http://www.multimove.nl/images/icons/small/icon_document.gif)';
testSelect.options[0].style.backgroundRepeat = 'no-repeat';
}
if(comboBoxTest.value == 'optionTest2')
{
testSelect.options[0] = new Option();
testSelect.options[0].value = 'testOption1';
testSelect.options[0].innerHTML = 'Test option 1';
testSelect.options[0].style.backgroundImage = 'url(http://www.middelburg.nl/static/middelburgpresentation/images/icons/icon_pdf.gif)';
testSelect.options[0].style.backgroundRepeat = 'no-repeat';
}
}
</script>
</head>
<body>
<form>
<select id="comboBoxTest" onchange="changeIssueTypes()">
<option value="optionTest1" >Option test 1</option>
<option value="optionTest2" >Option test 2</option>
</select>
<br/>
<select multiple id="testSelect">
<option value="initialOption">Test initial option</option>
</select>
</form>
</body>
</html>
First of all: Try to set appropriate CSS properties "by hand", directly in CSS; I'm afraid IE8 doesn't allow change the background-image property on multi-line selectbox.
If so, try to use standard DOM methods like appendChild() and createElement() to proper create DOM element:
var opt = document.createElement("option");
opt.value = "value";
opt.innerHTML = "blah blah";
opt.style.backgroundImage = "...";
testSelect.appendChild(opt);
Related
So I have a simple HTML file that I want to have a select option drop down menu. I have made that when a selection is made the page reloads retaining the option but I can't get the result outside of the function.
<!doctype html>
<html>
<head>
</head><body>
<select id="mySelect" onchange = "getSelectValue();">
<optgroup label="Working">
<option value="rage.zip">Streets of Rage</option>
<option value="quest.zip">Money Quest</option>
</optgroup>
</select>
<div style="width:640px;height:480px;max-width:100%">
<script type="text/javascript">
window.addEventListener('load', function(){
if (localStorage.pick) {
var sel = document.querySelector('#mySelect');
sel.value = localStorage.pick;
}
});
function getSelectValue(){
var sel = document.querySelector('#mySelect');
localStorage.pick = sel.value;
location.reload();
return sel.value;
}
EJS_player = '#game';
EJS_gameUrl = ; // Url to Game rom
EJS_gameID = 4; // ID in your website, required for netplay.
EJS_core = 'segaMD';
</script>
<script src="https://www.emulatorjs.com/loader.js"></script>
</body>
</html>
My issue is the select option result is in the sel.value. I need that value to EJS_gameUrl = .
So if the option 1 is select which is rage.zip then it should be filled in the EJS_gameUrl = "rage.zip"
Im just having trouble with getting that result out of the function . I would prefer to define it to a variable and just add the variable in the EJS_gameUrl = x; or similar. How can I go about this?
See Storing the information you need — Variables, Storage.setItem and Storage.getItem.
Your code should be something along the lines of:
const EJS_player = '#game';
let EJS_gameUrl = ''; // Url to Game rom
const EJS_gameID = 4; // ID in your website, required for netplay.
const EJS_core = 'segaMD';
window.addEventListener('load', function() {
const storedValue = localStorage.getItem('mySelect');
if (storedValue) {
var sel = document.querySelector('#mySelect');
sel.value = storedValue;
EJS_gameUrl = storedValue;
}
});
function getSelectValue() {
localStorage.setItem('mySelect', this.value);
location.reload();
}
console.log(EJS_gameUrl)
<select id="mySelect" onchange="getSelectValue();">
<optgroup label="Working">
<option value="rage.zip">Streets of Rage</option>
<option value="quest.zip">Money Quest</option>
</optgroup>
</select>
In my HTML, I have a <select> with three <option> elements. I want to use jQuery to check each option's value against a Javascript var. If one matches, I want to set the selected attribute of that option. How would I do that?
Vanilla JavaScript
Using plain old JavaScript:
var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == val) {
sel.selectedIndex = j;
break;
}
}
}
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery - Using Value Attributes
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
Demo
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
Modern DOM
For the browsers that support document.querySelector and the HTMLOptionElement::selected property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
Demo
Knockout.js
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
Demo
Polymer
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Demo
Angular 2
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
Demo
Vue 2
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Demo
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
The right way to select Alaska and have the select show the right item as selected using:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
$('#state').val('AK').change();
You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:
document.getElementById('sel').value = 'bike';
DEMO
Markup
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Demo
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
Simplest code that worked is below:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:
Example
<select id="org_list">
<option value="23">IBM</option>
<option value="33">DELL</option>
<option value="25">SONY</option>
<option value="29">HP</option>
</select>
So you must know the value of the option to select.
function selectOrganization(id){
org_list=document.getElementById('org_list');
org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}
How to Use?
selectOrganization(25); //this will select SONY from option List
Your comments are welcome. :) AzmatHunzai.
Test this Demo
Selecting Option based on its value
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
Selecting Option based on its text
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
Supporting HTML
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
After a lot of searching I tried #kzh on select list where I only know option inner text not value attribute,
this code based on select answer I used it to change select option according to current page urlon this format
http://www.example.com/index.php?u=Steve
<select id="sel">
<option>Joe</option>
<option>Steve</option>
<option>Jack</option>
</select>
<script>
var val = window.location.href.split('u=')[1]; // to filter ?u= query
var sel = document.getElementById('sel');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
// search are based on text inside option Attr
if(opt.text == val) {
sel.selectedIndex = j;
break;
}
}
</script>
This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .
You just write the code
var theVal = 1;
$('#variable_id').val(theVal).trigger('change');
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
selectElement is a html <select> element.
Increment the value:
selectElement.selectedIndex++
Decrement the value:
selectElement.selectedIndex--
var accHos = document.getElementById("accHos");
function showName(obj) {
accHos.selectedIndex = obj.selectedIndex;
}
div {
color: coral;
}
select {
margin-left: 20px;
margin-bottom: 8px;
min-width: 120px;
}
<div>Select Account Number:</div>
<select id="accNos" name="" onchange="showName(this);">
<option value="">Select Account</option>
<option value="">1052021</option>
<option value="">2052021</option>
<option value="">3052021</option>
<option value="">4052021</option>
<option value="">5052021</option>
</select>
<div>Account Holder Name:</div>
<select id="accHos" name="" disabled>
<option value="">--Name--</option>
<option value="">Suhan</option>
<option value="">Cesur</option>
<option value="">Hopper</option>
<option value="">Rachel</option>
<option value="">Arya</option>
</select>
<!-- Just for my referece -->
Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():
NodeList.prototype.forEach = Array.prototype.forEach
Just:
var requiredValue = 'i-50332a31',
selectBox = document.querySelector('select')
selectBox.childNodes.forEach(function(element, index){
if ( element.value === requiredValue ) {
selectBox.selectedIndex = index
}
})
I want to make the options of < select > show or hide by program(JS),is it possible?
It is just like the interesting tags in the front page of StackOverFlow, when you type in some words, the drop list will expand and give you suggestions.
ps.I know StackOverFlow didn't use select in this case, anyway just take it as an example.
You add or remove items from the options collection of the select.
Here is an example that removes one item and adds another:
<html>
<head>
<title></title>
<script type="text/javascript">
function init() {
// get a reference to the element
var sel = document.getElementById('sel');
// remove an option
sel.options[2] = null;
// create a new option and add to the select
var opt = document.createElement('option');
opt.value = '5';
opt.text = 'five';
sel.options.add(opt);
}
</script>
</head>
<body onload="init();">
<form>
<select id="sel">
<option value="0">zero</option>
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</form>
</body>
</html>
function getCatListdef(sel)
{
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'data.php?cat_code='+sel;
ajax[index].onCompletion = function(){ createCities(index) };
ajax[index].runAJAX();
}
I have a SELECT which looks like this.
<select id="mySelect"><option value="">Please select</option></select>
At a certain point, my javascript sets the OPTION as follows:
var elSel = document.getElementById('mySelect');
elSel.options[0].value = myValue;
elSel.options[0].text = myText;
The problem is that you have to click the select for it to show myText. How do I make it so that myText (with myValue) shows as soon as I run that javascript?
Add elSel.selectedIndex = 0; to the end of your script. Use elSel.options.length-1 if you're going to ever have more than 1 item and you want to select the last item.
<html>
<head>
<script language="javascript">
function addItem() {
var elSel = document.getElementById('test');
elSel.options[0].value = '1';
elSel.options[0].text = 'new value';
elSel.selectedIndex = 0;
}
</script>
</head>
<body>
<form>
<select id="test"><option value="1">- SELECT AN ITEM -</option></select>
<input type="button" value="Add Item" onclick="addItem();" />
</form>
</body>
</html>
Load the script with onLoad attribute of the body tag? e.g.
<body onload="initSelect()">
Or simply put the script after the select tag:
<select>...</select>
<script>//code to generate the options</script>
Try using DOM manipulation:
<select id="mySelect">
<option value="">Please select</option>
</select>
<script>
var elSel = document.getElementById('mySelect');
var opt = {};
opt = document.createElement('option');
opt.value = '1';
opt.text = 'a';
elSel.appendChild(opt);
opt = document.createElement('option');
opt.value = '2';
opt.text = 'b';
opt.selected = true; /* Here is where we update the select element */
elSel.appendChild(opt);
opt = document.createElement('option');
opt.value = '3';
opt.text = 'c';
elSel.appendChild(opt);
</script>
Test it here:
http://dl.dropbox.com/u/186012/demos/stackoverflow/select/index.html
The problem was the jQuery plugin I was using (Uniform), I didn't realize that I had to run $.uniform.update()
http://pixelmatrixdesign.com/uniform/
This was interesting. In a select dropdown, trying not to use jQuery (with the exception of easing some of my pain on recreation), I ran into an issue that doesn't properly let any current browsers catch the proper selected option. Here is my code, for the page that recreates the issue (remember, no jQuery to necessarily solve issue, but more or less just telling me what I am doing wrong.
This one has me stumped.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
var options = new Array();
for ( var i = 0; i < 3; i++ ){
options.push(new Option("Option " + i, "Value" + i, false, false));
}
options[1].setAttribute("selected", "selected");
for ( var option in options ){
select_element.appendChild(options[option]);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
The html this creates is:
<select id="some-id" name="some-name">
<option value="Value0">Option 0</option>
<option value="Value1" selected="selected">Option 1</option>
<option value="Value2">Option 2</option>
</select>
But the anomaly here is that (in firefox at least), the selected option ends up being Option 0, which isn't the selected DOM element. In IE6, this select dropdown doesn't work at all.
There is an alternate method that does work, which includes piecing the options together manually, which works in all browsers that I have tested.
A small change made it work for me in Firefox:
...
//options[1].setAttribute("selected", "selected");
options[1].selected = true;
...
I'm manipulating the DOM element's attributes directly. Not sure why your method doesn't work. Maybe you should keep both lines so that the HTML generated has the selected = "selected" in it.
some old thread - however try something like this:
var idx=0;
while(obj.options[idx]) {
if(obj.options[idx].value==value) obj.options[idx].setAttribute('selected',true);
else obj.options[idx].removeAttribute('selected');
idx++;
}
Use selectedIndex to set the selected index of a select object.
options.selectedIndex = 1;
Here is the working code, which seems like more of a Hack!
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div id="select-holder" />
<input id="some-button" type="button">
<script type="text/javascript">
$("#some-button").click(function(){
var select_element = document.createElement('select');
select_element.setAttribute("id", "some-id");
select_element.setAttribute("name", "some-name");
for ( var i = 0; i < 3; i++ ){
var option_element = document.createElement('option');
option_element.setAttribute('value', "Value" + i);
option_element.appendChild( document.createTextNode( "Option " + i ) );
if (i == 1){
option_element.setAttribute("selected", "selected");
}
select_element.appendChild(option_element);
}
$("#select-holder").append(select_element);
});
</script>
</body>
</html>
options[1].setAttribute("selected", "selected");
is likely where your issue lies. The output you're getting is:
<option value="Value1" selected="selected">Option 1</option>
and the standard is:
<option value="Value1" selected>Option 1</option>
You may be able to do:
options[1].selected = true;