从列表菜单中获取selectedIndex并将其置于功能中

时间:2013-09-16 11:45:22

标签: javascript jquery html list drop-down-menu

这里我有一个代码function findPlaces,用于搜索框中的地点对象等。

function findPlaces(boxes,searchIndex) {
   var request = {
       bounds: boxes[searchIndex],
       types: ["museum"]
   };

这项工作正常,但现在......

现在我想用list / menu中的值更改此类型,所以我这样做:

//JS CODE
function findPlaces(boxes,searchIndex) {
   var request = {
       bounds: boxes[searchIndex],
       types: document.getElementById("select").selectedIndex
   };

和HTML代码:

<label for="select"></label>
        <select name="select" id="select">
          <option>restaurant</option>
          <option>bar</option>
          <option>museum</option>
          <option>gas_station</option>
        </select>

并且此代码不会从列表/菜单中获取值并使用新值运行函数

我如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

尝试这个jQuery代码,一旦你选择了元素,你就会将索引发送到findPlaces,这会提醒它:

$("#select").change(function(){

        var values= $('#select option').map(function(){
                        return this.value;
                    }).get();
        var index=jQuery.inArray($(this).val(), values);
      
        findPlaces(boxes, index);//send index to your function

    });
 
 

DEMO HERE

答案 1 :(得分:0)

您可以像这样检索选择值:

var boxes = ['a', 'b', 'c'];

function findPlaces(boxes, searchIndex) {
   var select = document.getElementById("select")
   return {
       bounds: boxes[searchIndex],
       types: select.options[select.selectedIndex].value
   };
}

document.getElementById("select").onclick = function() {

    var r = findPlaces(boxes, 2);
    alert(r.types);
};

此处示例:http://jsfiddle.net/zaCZw/