I am populating several selects with JavaScript. For some of them, the select option is the same so I have thought about creating one option and then populating all the concerning selects.
Here is how I am doing actually:
var option = document.createElement('option');
option.text = 'please select a journal';
option.value ='NULL';
try
{
selectSection.add(option, null); // standards compliant; doesn't work in IE
}
catch(ex)
{
selectSection.add(option); // IE only
}
var option = document.createElement('option');
option.text = 'please select a journal';
option.value ='NULL';
try
{
selectSpecialIssue.add(option, null); // standards compliant; doesn't work in IE
}
catch(ex)
{
selectSpecialIssue.add(option); // IE only
}
var option = document.createElement('option');
option.text = 'please select a journal';
option.value ='NULL';
try
{
selectVolume.add(option, null); // standards compliant; doesn't work in IE
}
catch(ex)
{
selectVolume.add(option); // IE only
}
.............ETC................
I have tried to create only one option (options are the sames) and then populating those selects:
var option = document.createElement('option');
option.text = 'please select a journal';
option.value ='NULL';
try
{
selectSection.add(option, null);
selectSpecialIssue.add(option, null);
selectVolume.add(option, null);
}
catch(ex)
{
selectSection.add(option);
selectSpecialIssue.add(option);
selectVolume.add(option);
}
The code is here much nicer and easier to understand but the problem is that only my last select (selectVolume) is populated, I don’t know why.
I think it’s because you don’t initalize the option object new. So you append the element to each slection, but there is only one object of the option, so it must be removed at the other selection. A better way is to do this inside a function: