Reputation: 4003
I have a form in which i use javascript to set the select element options depending on type of property (house, flat, etc). it is working now when I am accessing the list using the document.myForm.priceSelect.options.
I want to access it by id rather than name. Because I want to set the name also along with the options so that when the form is submitted, the name of the list will determine which function to execute. Some code to illustrate:
if(prop_type == 'flat') {
document.getElementById('priceRange').setAttribute('name', 'flatRange');
.....
Now here I am changing the name of the select list called priceRange. How can I also change the options using the id instead of the name like shown below:
document.searchForm.priceRange.options[1]=new Option("10000 - 20000", "10000 - 20000");
Thank you in advance...
UPDATE:
After change: (not working)
if(prop_type == 'flat') {
document.getElementById('priceRange').setAttribute('name', 'flatRange');
document.getElementById('priceRange').options.length=0;
document.getElementById('priceRange').options[0]=new Option("", "");
document.getElementById('priceRange').options[1]=new Option("10000 - 20000", "10000 - 20000");
Upvotes: 1
Views: 236
Reputation: 107247
dystroy's method should work - see this fiddle here
An alternative is to create a wrapper method for option creation, such as this:
function createOption(objSelect, optText, optValue){
var objOption = document.createElement("option");
objOption.text = optText;
objOption.value = optValue;
if(document.all && !window.opera){
objSelect.add(objOption);
}
else
{
objSelect.add(objOption, null);
};
}
Then you can add options to the select:
var priceRange=document.getElementById('priceRange');
createOption(priceRange, "10000 - 20000", "lowball");
Fiddle for the wrapper method here
Upvotes: 0
Reputation: 382130
Simply use
document.getElementById(yourId).options[1]=new Option("10000 - 20000", "10000 - 20000");
Upvotes: 1