需要解决这个JavaScript编码问题

时间:2010-11-08 13:40:29

标签: javascript sql mysql html browser

我在FORM中有一个SELECT。 此选择使用js填充。

我需要在其中一个选项中添加“Selected”属性。 通过检查MySql数据库,查看需要添加“选定属性”的社区名称,我得到哪一个。

<select name="community" id="community">
    //OPTIONS HERE
</select>

填充()功能:

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”。我应该如何将所选内容添加到其中?

我需要一个简单的功能,适用于所有主流浏览器......

4 个答案:

答案 0 :(得分:1)

将SELECT的selectedIndex属性设置为您需要的索引。当然,从零开始。

答案 1 :(得分:1)

只做

community.value = com;

示例http://www.jsfiddle.net/jMapA/

答案 2 :(得分:0)

for(var i = 0; i < community.options.length; i++) {
  if(community.options[i].id == com)
    community.selectedIndex = i;
}

答案 3 :(得分:0)

function selectOptionValue(selectId, value)
{
    select = document.getElementById(selectId);
    if (select)
    {
        for (var i = 0; i < select.options.length)
        {
            if (select.options[i].value == value)
            {
                select.options[i].selected = 'selected';
                return true;
            }
        }
    }

    return false;
}

使用我的功能:

selectOptionValue('community', 'Karlskrona');