set option "selected" attribute from dynamic created option - javascript

I have a dynamically created select option using a javascript function. the select object is
<select name="country" id="country">
</select>
when the js function is executed, the "country" object is
<select name="country" id="country">
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
...
<option value="ID">Indonesia</option>
...
<option value="ZW">Zimbabwe</option>
</select>
and displaying "Indonesia" as default selected option. note : there is no selected="selected" attribute in that option.
then I need to set selected="selected" attribute to "Indonesia", and I use this
var country = document.getElementById("country");
country.options[country.options.selectedIndex].setAttribute("selected", "selected");
using firebug, I can see the "Indonesia" option is like this
<option value="ID" selected="selected">Indonesia</option>
but it fails in IE (tested in IE 8).
and then I have tried using jQuery
$( function() {
$("#country option:selected").attr("selected", "selected");
});
it fails both in FFX and IE.
I need the "Indonesia" option to have selected="selected" attribute so when I click reset button, it will select "Indonesia" again.
changing the js function to dynamically create "country" options is not an option. the solution must work both in FFX and IE.
thank you

You're overthinking it:
var country = document.getElementById("country");
country.options[country.options.selectedIndex].selected = true;

Good question. You will need to modify the HTML itself rather than rely on DOM properties.
var opt = $("option[val=ID]"),
html = $("<div>").append(opt.clone()).html();
html = html.replace(/\>/, ' selected="selected">');
opt.replaceWith(html);
The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string: <option value="ID">Indonesia</option>.
It then does a string replace to add the attribute selected="selected" as a string, before replacing the original option with this new one.
I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/

Instead of modifying the HTML itself, you should just set the value you want from the relative option element:
$(function() {
$("#country").val("ID");
});
In this case "ID" is the value of the option "Indonesia"

So many wrong answers!
To specify the value that a form field should revert to upon resetting the form, use the following properties:
Checkbox or radio button: defaultChecked
Any other <input> control: defaultValue
Option in a drop down list: defaultSelected
So, to specify the currently selected option as the default:
var country = document.getElementById("country");
country.options[country.selectedIndex].defaultSelected = true;
It may be a good idea to set the defaultSelected value for every option, in case one had previously been set:
var country = document.getElementById("country");
for (var i = 0; i < country.options.length; i++) {
country.options[i].defaultSelected = i == country.selectedIndex;
}
Now, when the form is reset, the selected option will be the one you specified.

// get the OPTION we want selected
var $option = $('#SelectList').children('option[value="'+ id +'"]');
// and now set the option we want selected
$option.attr('selected', true);​​

What you want to do is set the selectedIndex attribute of the select box.
country.options.selectedIndex = index_of_indonesia;
Changing the 'selected' attribute will generally not work in IE. If you really want the behavior you're describing, I suggest you write a custom javascript reset function to reset all the other values in the form to their default.

This works in FF, IE9
var x = document.getElementById("country").children[2];
x.setAttribute("selected", "selected");

Make option defaultSelected
HTMLOptionElement.defaultSelected = true; // JS
$('selector').prop({defaultSelected: true}); // jQuery
HTMLOptionElement MDN
If the SELECT element is already added to the document (statically or dynamically), to set an option to Attribute-selected and to make it survive a HTMLFormElement.reset() - defaultSelected is used:
const EL_country = document.querySelector('#country');
EL_country.value = 'ID'; // Set SELECT value to 'ID' ("Indonesia")
EL_country.options[EL_country.selectedIndex].defaultSelected = true; // Add Attribute selected to Option Element
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country">
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="HR">Croatia</option>
<option value="ID">Indonesia</option>
<option value="ZW">Zimbabwe</option>
</select>
</form>
The above will also work if you build the options dynamically, and than (only afterwards) you want to set one option to be defaultSelected.
const countries = {
AF: 'Afghanistan',
AL: 'Albania',
HR: 'Croatia',
ID: 'Indonesia',
ZW: 'Zimbabwe',
};
const EL_country = document.querySelector('#country');
// (Bad example. Ideally use .createDocumentFragment() and .appendChild() methods)
EL_country.innerHTML = Object.keys(countries).reduce((str, key) => str += `<option value="${key}">${countries[key]}</option>`, '');
EL_country.value = 'ID';
EL_country.options[EL_country.selectedIndex].defaultSelected = true;
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country"></select>
</form>
Make option defaultSelected while dynamically creating options
To make an option selected while populating the SELECT Element, use the Option() constructor MDN
var optionElementReference = new Option(text, value, defaultSelected, selected);
const countries = {
AF: 'Afghanistan',
AL: 'Albania',
HR: 'Croatia',
ID: 'Indonesia', // <<< make this one defaultSelected
ZW: 'Zimbabwe',
};
const EL_country = document.querySelector('#country');
const DF_options = document.createDocumentFragment();
Object.keys(countries).forEach(key => {
const isIndonesia = key === 'ID'; // Boolean
DF_options.appendChild(new Option(countries[key], key, isIndonesia, isIndonesia))
});
EL_country.appendChild(DF_options);
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country"></select>
</form>
In the demo above Document.createDocumentFragment is used to prevent rendering elements inside the DOM in a loop. Instead, the fragment (containing all the Options) is appended to the Select only once.
SELECT.value vs. OPTION.setAttribute vs. OPTION.selected vs. OPTION.defaultSelected
Although some (older) browsers interpret the OPTION's selected attribute as a "string" state, the WHATWG HTML Specifications html.spec.whatwg.org state that it should represent a Boolean selectedness
The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute.
html.spec.whatwg.org - Option selectedness
one can correctly deduce that just the name selected in <option value="foo" selected> is enough to set a truthy state.
Comparison test of the different methods
const EL_select = document.querySelector('#country');
const TPL_options = `
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="HR">Croatia</option>
<option value="ID">Indonesia</option>
<option value="ZW">Zimbabwe</option>
`;
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver
const mutationCB = (mutationsList, observer) => {
mutationsList.forEach(mu => {
const EL = mu.target;
if (mu.type === 'attributes') {
return console.log(`* Attribute ${mu.attributeName} Mutation. ${EL.value}(${EL.text})`);
}
});
};
// (PREPARE SOME TEST FUNCTIONS)
const testOptionsSelectedByProperty = () => {
const test = 'OPTION with Property selected:';
try {
const EL = [...EL_select.options].find(opt => opt.selected);
console.log(`${test} ${EL.value}(${EL.text}) PropSelectedValue: ${EL.selected}`);
} catch (e) {
console.log(`${test} NOT FOUND!`);
}
}
const testOptionsSelectedByAttribute = () => {
const test = 'OPTION with Attribute selected:'
try {
const EL = [...EL_select.options].find(opt => opt.hasAttribute('selected'));
console.log(`${test} ${EL.value}(${EL.text}) AttrSelectedValue: ${EL.getAttribute('selected')}`);
} catch (e) {
console.log(`${test} NOT FOUND!`);
}
}
const testSelect = () => {
console.log(`SELECT value:${EL_select.value} selectedIndex:${EL_select.selectedIndex}`);
}
const formReset = () => {
EL_select.value = '';
EL_select.innerHTML = TPL_options;
// Attach MutationObserver to every Option to track if Attribute will change
[...EL_select.options].forEach(EL_option => {
const observer = new MutationObserver(mutationCB);
observer.observe(EL_option, {attributes: true});
});
}
// -----------
// LET'S TEST!
console.log('\n1. Set SELECT value');
formReset();
EL_select.value = 'AL'; // Constatation: MutationObserver did NOT triggered!!!!
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n2. Set HTMLElement.setAttribute()');
formReset();
EL_select.options[2].setAttribute('selected', true); // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n3. Set HTMLOptionElement.defaultSelected');
formReset();
EL_select.options[3].defaultSelected = true; // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n4. Set SELECT value and HTMLOptionElement.defaultSelected');
formReset();
EL_select.value = 'ZW'
EL_select.options[EL_select.selectedIndex].defaultSelected = true; // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
/* END */
console.log('\n*. Getting MutationObservers out from call-stack...');
<form>
<select name="country" id="country"></select>
</form>
Although the test 2. using .setAttribute() seems at first the best solution since both the Element Property and Attribute are unison, it can lead to confusion, specially because .setAttribute expects two parameters:
EL_select.options[1].setAttribute('selected', false);
// <option value="AL" selected="false"> // But still selected!
will actually make the option selected
Should one use .removeAttribute() or perhaps .setAttribute('selected', ???) to another value? Or should one read the state by using .getAttribute('selected') or by using .hasAttribute('selected')?
Instead test 3. (and 4.) using defaultSelected gives the expected results:
Attribute selected as a named Selectedness state.
Property selected on the Element Object, with a Boolean value.

select = document.getElementById('selectId');
var opt = document.createElement('option');
opt.value = 'value';
opt.innerHTML = 'name';
opt.selected = true;
select.appendChild(opt);

// Get <select> object
var sel = $('country');
// Loop through and look for value match, then break
for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }
// Select index
sel.options.selectedIndex = i;
Begitu loh.

This should work.
$("#country [value='ID']").attr("selected","selected");
If you have function calls bound to the element just follow it with something like
$("#country").change();

You could search all the option values until it finds the correct one.
var defaultVal = "Country";
$("#select").find("option").each(function () {
if ($(this).val() == defaultVal) {
$(this).prop("selected", "selected");
}
});

Vanilla JS
Use this for Vanilla Javascript, keeping in mind that you can feed the example "numbers" array with any data from a fetch function (for example).
The initial HTML code:
<label for="the_selection">
<select name="the_selection" id="the_selection_id">
<!-- Empty Selection -->
</select>
</label>
Some values select tag:
const selectionList = document.getElementById('the_selection_id');
const numbers = ['1','3','5'];
numbers.forEach(number => {
const someOption = document.createElement('option');
someOption.setAttribute('value', number);
someOption.innerText = number;
if (number == '3') someOption.defaultSelected = true;
selectionList.appendChild(someOption);
})
You'll get:
<label for="the_selection">
<select name="the_selection" id="the_selection_id">
<!-- Empty Selection -->
<option value="1">1</option>
<option value="3" selected>3</option>
<option value="5">5</option>
</select>
</label>

You can solve this on ES6 like this:
var defaultValue = "ID";
[...document.getElementById('country').options].map(e => e.selected = (e.value == defaultValue));
I haven't test in other browsers but in Chrome works just fine.
...document.getElementById('country').options using the spread operator you cast options as an array.
.map allows you to apply a function to each element of your array.
e represents each <option> element of your object so you can access its attributes like .select and .value as getter and setter.
Because you .select receives a boolean option you want to assign when its value is equal to your default value.

To set the input option at run time try setting the 'checked' value. (even if it isn't a checkbox)
elem.checked=true;
Where elem is a reference to the option to be selected.
So for the above issue:
var country = document.getElementById("country");
country.options[country.options.selectedIndex].checked=true;
This works for me, even when the options are not wrapped in a .
If all of the tags share the same name, they should uncheck when the new one is checked.

Realize this is an old question, but with the newer version of JQuery you can now do the following:
$("option[val=ID]").prop("selected",true);
This accomplishes the same thing as Box9's selected answer in one line.

The ideas on this page were helpful, yet as ever my scenario was different. So, in modal bootstrap / express node js / aws beanstalk, this worked for me:
var modal = $(this);
modal.find(".modal-body select#cJourney").val(vcJourney).attr("selected","selected");
Where my select ID = "cJourney" and the drop down value was stored in variable: vcJourney

I was trying something like this using the $(...).val() function, but the function did not exist. It turns out that you can manually set the value the same way you do it for an <input>:
// Set value to Indonesia ("ID"):
$('#country').value = 'ID'
...and it get's automatically updated in the select. Works on Firefox at least; you might want to try it out in the others.

To set value in JavaScript using set attribute , for selected option tag
var newvalue = 10;
var x = document.getElementById("optionid").selectedIndex;
document.getElementById("optionid")[x].setAttribute('value', newvalue);

Related

How to change the text-content of an html-element as soon as a new option was selected?

I am trying to change a span element when a new option is selected in Javascript.
This is the html code:
<span id="month"></span>
(...)
<option id="plan_option".....
And this is my javascript code that currently just displays a text in when the page loads:
window.onload = function month_freq() {
var id = document.getElementById("plan_option").value;
var freq = '';
if (id == 5144746){
freq = 'ogni mese';
} else{
freq = 'ogni due mesi';
}
document.getElementById("month").innerHTML = freq;
}
So, should I make a new function that is called when option changes or idk.
Any help is appreciated, thanks!
EDIT
So, I try to set it in more context and update it to the current status.
My goal here is to tell the client, relative to the plan that he chooses, on which basis will he pay (monthly or two monthly).
Thanks to #Peter Seliger I updated the code, so I now have this:
Liquid/HTML(1):
<select name="plan_select" id="plan_select">
{% for plan in selling_plan_group.selling_plans %}
<option id="plan_option" data-billing-frequency="{% if plan.id == 5144746 %}ogni mese{% else %}ogni due mesi{% endif %}" value="{{ plan.id }}">{{ plan.options[0].value }}</option>
{% endfor %}
</select>
HTML(2):
<span id="month"></span>
Javascript:
function displayBoundBillingFrequency(evt) {
const elementSelect = evt.currentTarget;
if (elementSelect) {
const selectedOption = elementSelect[elementSelect.selectedIndex];
// `this` equals the bound billing-frequency display-element.
this.textContent = (selectedOption.dataset.billingFrequency || '');
}
}
function mainInit() {
const planOptions = document.querySelector('#plan_select');
const frequencyDisplay = document.querySelector('#month');
if (planOptions && frequencyDisplay) {
const displayBillingFrequency = displayBoundBillingFrequency.bind(frequencyDisplay);
// synchronize display data initially.
displayBillingFrequency({
currentTarget: planOptions,
});
// initialize event listening/handling
planOptions.addEventListener('change', displayBillingFrequency);
}
}
mainInit();
But it still doesn't work. Thanks.
One just wants to listen to the changes of a select element.
Thus one somehow needs to identify this very select element and not so much each of its option elements. The latter one's then do not need to feature either a name- or an id-attribute but a value-attribute instead.
Then one does implement an event handler which does read the currently selected option's value and also does write this very value to the desired/related html-element.
One also needs to provide the event listening/handling to the formerly mentioned select element.
In addition one wants to synchronize the default selected value with the displaying element at load/render time.
Note
For security reasons one does not really want to render a text value via innerHTML ... in this case a textContent write access does the job just fine.
function handleMonthOptionChangeForRelatedDisplay(evt) {
const elementDisplay = document.querySelector('#month');
const elementSelect = evt.currentTarget;
if (elementDisplay && elementSelect) {
const elementSelect = evt.currentTarget;
const selectedIndex = elementSelect.selectedIndex;
elementDisplay.textContent = elementSelect[selectedIndex].value
}
}
function initMonthOptionChange() {
const elementSelect = document.querySelector('#month-options');
elementSelect.addEventListener('change', handleMonthOptionChangeForRelatedDisplay);
}
// window.onload = function () {
// handleMonthOptionChangeForRelatedDisplay({
// currentTarget: document.querySelector('#month-options')
// });
// initMonthOptionChange();
// }
handleMonthOptionChangeForRelatedDisplay({
currentTarget: document.querySelector('#month-options')
});
initMonthOptionChange();
<select name="plan_option" id="month-options">
<option value=""></option>
<option value="Ogni Mese">ogni mese</option>
<option value="Ogni due Mesi" selected>ogni due mesi</option>
</select>
<p id="month"></p>
In case the OP has to render an option-specific text-value different from the option element's value-attribute there was still the approach of providing this information via an option-specific data-attribute in order to keep the handler-implementation as generic (without any additional and case-specific compare-logic) as possible ...
function displayBoundBillingFrequency(evt) {
const elementSelect = evt.currentTarget;
if (elementSelect) {
const selectedOption = elementSelect[elementSelect.selectedIndex];
// `this` equals the bound billing-frequency display-element.
this.textContent = (selectedOption.dataset.billingFrequency || '');
}
}
function mainInit() {
const planOptions = document.querySelector('#plan-options');
const frequencyDisplay = document.querySelector('#plan-billing-frequency');
if (planOptions && frequencyDisplay) {
const displayBillingFrequency = displayBoundBillingFrequency.bind(frequencyDisplay);
// synchronize display data initially.
displayBillingFrequency({
currentTarget: planOptions,
});
// initialize event listening/handling
planOptions.addEventListener('change', displayBillingFrequency);
}
}
mainInit();
<select name="plan_option" id="plan-options">
<option value=""></option>
<option value="541758" data-billing-frequency="ogni mese" selected>First Option</option>
<option value="752649" data-billing-frequency="ogni due mesi">Second Option</option>
<option value="invalid">Invalid Option</option>
</select>
<p id="plan-billing-frequency"></p>
You should check HTMLElement: change event
var planSelectElem = document.getElementById("plan_select"); // <select id="plan_option_select"></select>
planSelectElem.onchange = month_freq;
// OR
planSelectElem.addEventListener("change", month_freq);

How to change the current selected option in the <select> by JS [duplicate]

This question already has answers here:
Changing the selected option of an HTML Select element
(14 answers)
Closed 5 years ago.
I try a several ways to make it, but only what I got - two selected items in one time. Also I found on SOF a "solution" - document.getElementById("selection-type").selectedIndex = 2; , but it does not work.
I understand that this is a very simple question, but I really do not know what is I'am missed.
var select = document.body.querySelector('select');
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
}
}
select.options[1].selected = false;
var newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
You are confusing attributes and properties. Changing a property is a dynamic action that affects the in-memory object, it doesn't modify the static HTML that the element was originally parsed with. If you want to change the attribute, you need to use setAttribute() or removeAttribute().
var select = document.body.querySelector('select');
// Get the element with the "selected" attribute
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value"));
// Get the element with the "selected" value:
console.log("Element with value property of 'selected': " + select.value);
// Change the value property of the select
console.log("Changing value of select element to 'Rock'");
select.value = "Rock";
// Get the element with the "selected" attribute
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value")); // Still Blues!
// Get the element with the "selected" value:
console.log("But, value of the select element is now: " + select.value); // Now Rock!
// Change which element has the selected attribute
console.log("Switching elment that has the 'selected' attribute...");
select.querySelector("[selected]").removeAttribute("selected");
select.querySelector("[value=Rock]").setAttribute("selected", "selected");
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value"));
console.log(select.options[0])
console.log(select.options[1]);
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
To answer the question in the title, all you need to do is set the desired option as selected. To get current <select> value one should look into the select.value:
let select = document.body.querySelector('select'),
newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
console.log(select.value);
// Classic
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
Also note selected attribute only marks default selection, and is different than the selected property of the <option>. The attribute simply tells the browser if it should render the option as selected when initially drawing the DOM element or not.
When dealing with <select multiple>, you need to check the .selectedOptions property of the <select> and map it to an array. Example:
let select = document.body.querySelector('select'),
newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
let values = [].slice.call(select.selectedOptions).map(a => a.value);
console.log(values)
// ["Blues","Classic"]
<select multiple>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
The .selectedOptions is an object which contains the selected options, the length and native methods, such as item() and namedItem(). Do note option groups are not contained.

How to populate select options from an array based on a select value?

Trying to get my second select element's options to populate from an array based on the value of the first select element. I can't seem to understand why it only populates the items from the array of the first select element. I know the appendChild is causing the items to keep tacking on at the need, but I've tried to clear the variables, but it seems the option elements that were created stay.
Any help would be great, thanks!
<select id="makeSelect" onChange="modelAppend()">
<option value="merc">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<select id="modelSelect">
</select>
<script>
var audiModels = ["TT", "R8", "A4", "A6"]; //audimodels
var mercModels = ["C230", "B28", "LTX",]; //mercmodels
var bmwModels = ["328", "355", "458i",]; //bmwmodels
var selectedMake = document.getElementById("makeSelect"); //grabs the make select
var selectedModel = document.getElementById("modelSelect"); //grabs the model select
var appendedModel = window[selectedMake.value + "Models"]; // appends "Models" to selectedMake.value and converts string into variable
function modelAppend() {
for (var i = 0; i < appendedModel.length; i ++) { // counts items in model array
var models = appendedModel[i]; // // sets "models" to count of model array
var modelOptions = document.createElement("option"); //create the <option> tag
modelOptions.textContent = models; // assigns text to option
modelOptions.value = models; // assigns value to option
selectedModel.appendChild(modelOptions); //appeneds option tag with text and value to "modelSelect" element
}
}
</script>
This line is fishy:
var appendedModel = window[selectedMake.value + "Models"];
You need to get the element when the value has changed, not on page load. Then you need to remove the options on change too, or you will get a very long list if the user selects multiple times. Use an object to store the arrays, that makes it much easier to access them later. Also better use an event listener instead of inline js (though that's not the main problem here).
Try below code:
let models = {
audiModels: ["TT", "R8", "A4", "A6"],
mercModels: ["C230", "B28", "LTX"],
bmwModels: ["328", "355", "458i"]
}
document.getElementById('makeSelect').addEventListener('change', e => {
let el = e.target;
let val = el.value + 'Models';
let appendTo = document.getElementById('modelSelect');
Array.from(appendTo.getElementsByTagName('option')).forEach(c => appendTo.removeChild(c));
if (!models[val] || !Array.isArray(models[val])) {
appendTo.style.display = 'none';
return;
}
models[val].forEach(m => {
let opt = document.createElement('option');
opt.textContent = opt.value = m;
appendTo.appendChild(opt);
});
appendTo.style.display = '';
});
<select id="makeSelect">
<option value=""></option>
<option value="merc">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<select id="modelSelect" style="display:none">
</select>

Retrieving the value of a specific attribute via javascript for the onChange attribute

Good morning/afternoon,
Not so much a problem but more of a query. If I have the following code to grab hold of the users selection on a drop-down box (see figure 1), how do I also add the ability to also grab the value of a specific attribute? (see figure 2)
Figure 1:
<select onChange="productString(this.value)">
<option selected>Please Choose an Option</option>
<option value="Foo"></option>
</select>
Figure 2:
<select onChange="productString(this)">
<option selected>Please Choose an Option</option>
<option value="Foo" id="Bar"></option>
</select>
If anyone would be so kind as too show me where I am going wrong in figure 2 it would be greatly appreciated.
Thanks in advance,
Dan.
EDIT:::::
Would the following work it collecting the information?
function productString(element) {
var id = element.value;
var name = element.id;
var box = element.class;
}
Just pass though this:
<select onChange="productString(this)">
and then you can get whatever you want:
function productString(element) {
var value = element.value, id = element.id;
// ...
}
Here is a sample jsfiddle.
edit — oops sorry - the element that's being passed through is, in IE everywhere (gee I must be blind), the "select" element, not the "option". Thus:
function productString(element) {
if (element.tagName.toLowerCase() === 'select')
element = element.options[element.selectedIndex];
var id = element.id;
var value = element.value;
// ...
}
Updated jsfiddle.

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories