我在表格中有一个选择。 此选择是使用 js 填充的。
我需要向其中一个选项添加“选定”属性。 我通过检查 MySql 数据库来查看需要添加“选定属性”的社区名称来了解哪一个。
<select name="community" id="community">
//OPTIONS HERE
</select>
filler()函数:
function filler(com){
//com is the options which needs to be selected, this variables value comes from the mysql database
var community = document.getElementById("community");
var area = document.getElementById("area").value;
// area is just another input on the page which value also is fetched from mysql db. Each area has x communities, so I have alot of IF:s.
if(area == 'Blekinge') {
community.length = 6;
community.options[0].value = "Välj Kommun";
community.options[0].text = "-- Välj Kommun --";
community.options[0].id = "Välj Kommun";
community.options[1].value = "Karlshamn";
community.options[1].text = "Karlshamn";
community.options[1].id = "Karlshamn";
community.options[2].value = "Karlskrona";
community.options[2].text = "Karlskrona";
community.options[2].id = "Karlskrona";
community.selected = 0;
}
}
如您所见,“com”变量是需要添加“selected”属性的选项。
我有超过 30 个这样的 if 语句,但我不知道如何创建一个函数来将此“Selected”属性添加到匹配选项。
所以我有“com”,例如上面示例中的“Karlskrona”。我应该如何将所选内容添加到其中?
我需要一个可以在所有主要浏览器中运行的简单函数......
最佳答案
将 SELECT 的 selectedIndex
属性设置为您需要的索引。当然是从零开始。
关于javascript - 需要解决这个 javascript 编码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4124334/