Javascript选择个别选项

时间:2015-09-18 08:19:58

标签: javascript

我最近一直试图创建一个函数,在选择框上进行更改时,它只返回选定的选项值。

我的标记看起来像这样:

<select id='rangeSelector'>
    <option value='custom'>Custom</option>
    <option value='7 days'>7 days</option>
    <option value='14 days'>14 days</option>
    <option value='WTD'>WTD</option>
    <option value='MTD'>MTD</option>
    <option value='QTD'>QTD</option>
    <option value='YTD'>YTD</option>
</select>

和javascript函数:

var rangeSelector = document.getElementById('rangeSelector');
rangeSelector.addEventListener('change', function(e) {
    var x = rangeSelector.children;
    for (var i = 0; i < x.length; i++) {
        var newX = x[i].value;
        console.log(newX);
    }   
}, false);

我想要做的是当我点击7天只返回7天。

4 个答案:

答案 0 :(得分:2)

不要阅读<option>。阅读<select>

document.getElementById('rangeSelector').value

其他有趣的位包括.selectedIndex.selectedOptions

(当然,正如Abhitalks在评论中指出的那样,在你的处理程序中,元素获取已经为你做了。)

答案 1 :(得分:0)

您可以使用jQuery,例如:

$("#rangeSelector").on("change", function() {
    var rangeSelect = document.getElementById("rangeSelector");
    var value = selectJaar.options[rangeSelect.selectedIndex].value;
    return value;
});

首先获取下拉列表,然后获取所选值,然后返回。

答案 2 :(得分:0)

 var rangeSelector = document.getElementById('rangeSelector');
 rangeSelector.addEventListener('change', function(e) {
       console.log(rangeSelector.value);
    }, true);

您不需要循环,在触发事件后,“更改”rangeSelector.value已经具有所选元素的值。

因此,如果您想为所选选项添加“有效”,您可以这样做:

     var rangeSelector = document.getElementById('rangeSelector');
     rangeSelector.addEventListener('change', function(e) {
         var x = rangeSelector.children;
         var y = rangeSelector.selectedIndex;
         x[y].className = x[y].className + " active";
         console.log(rangeSelector.value);
     }, true);

但你应该通过循环来删除所有非活动的“活动”类:)

     var rangeSelector = document.getElementById('rangeSelector');
     rangeSelector.addEventListener('change', function(e) {
         var x = rangeSelector.children;
         var y = rangeSelector.selectedIndex;
         for (var i = 0; i < x.length; i++) {
             x[i].className = "";  //or x[i].removeAttribute("class");`
         }   
         x[y].className = x[y].className + " active";
         console.log(rangeSelector.value);
     }, true);

答案 3 :(得分:0)

尝试使用this.value

&#13;
&#13;
document.getElementById('rangeSelector').addEventListener('change', function(e) {
  alert(this.value);
});
&#13;
<select id='rangeSelector'>
  <option value='custom'>Custom</option>
  <option value='7 days'>7 days</option>
  <option value='14 days'>14 days</option>
  <option value='WTD'>WTD</option>
  <option value='MTD'>MTD</option>
  <option value='QTD'>QTD</option>
  <option value='YTD'>YTD</option>
</select>
&#13;
&#13;
&#13;