2012-11-09 113 views
1

我有一个表单,我使用javascript根据属性类型(房屋,平面等)设置select元素选项。它正在使用document.myForm.priceSelect.options访问列表时正在工作。javascript设置使用getElementsById选择元素选项

我想通过id而不是名称来访问它。因为我想要设置名称以及选项,以便在提交表单时,列表的名称将决定执行哪个函数。一些代码来说明:

if(prop_type == 'flat') { 
      document.getElementById('priceRange').setAttribute('name', 'flatRange'); 
      ..... 

现在我在这里改变名为priceRange的选择列表。我如何也使用id而不是名称更改选项,如下面所示:

document.searchForm.priceRange.options[1]=new Option("10000 - 20000", "10000 - 20000"); 

预先感谢您...

UPDATE:

变更后:(不工作)

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"); 

回答

1

只需使用

document.getElementById(yourId).options[1]=new Option("10000 - 20000", "10000 - 20000"); 
+0

谢谢队友:)将尝试它 –

+0

没有工作。我更新了上面的代码以显示更改。现在列表只是不显示任何东西。 –

0

dystroy的方法应该工作 - 看到这fiddle here

另一种方法是创建选项创建的包装方法,比如这个:

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); 
    }; 
} 

那么你可以添加选项的选择:

var priceRange=document.getElementById('priceRange'); 
createOption(priceRange, "10000 - 20000", "lowball"); 

小提琴的包装方法here