2016-11-05 74 views
0

我有这样的代码:如何获取特定选项的值?

function select(cities, country) { 
    $('<div class="btn-group "><button type="button" id="forecast" 
    data- toggle="modal" data-target="#myModal" name="forecast" 
    class="btn btn-primary pull-right" >Show Me The Forecast</div>').insertAfter('.btn-group'); 
    $('#cities').html(' <label for="cities">Select City</label> 
    <select name="cities" id="city" class="form-control">' + 
     '<option disabled selected value> -- select an option -- </option>' + 
      cities.map(function (city) { 
       return '<option value="' + city + '">' + city + '</option> '; 
      }).join('') + '</select>' 
    ); 
    var city = $("#city option:selected").val(); 
    console.log(city); 
} 

我想利用上述选择的元素,但它需要的第一个值,并将其存储到city变量

+0

不是真的清楚这个代码应该做什么或者你在问什么。显示'select()'也被使用。参见[mcve]和[问],然后用适当的细节编辑问题 – charlietfl

回答

0

每一刻的具体价值我想你想要的结果在这个演示:

select(['city1', 'city2', 'city3'], 'country1'); 
 

 
function select(cities, country) { 
 
    $('<div class="btn-group "><button type="button" id="forecast" data- toggle="modal" data-target="#myModal" name="forecast" class="btn btn-primary pull-right" >Show Me The Forecast</div>').insertAfter('.btn-group'); 
 

 

 
    $('#cities').html(' <label for="cities">Select City</label><select name="cities" id="city" class="form-control">' + 
 
     '<option disabled selected value> -- select an option -- </option>' + 
 
     cities.map(function(city) { 
 
      return '<option value="' + city + '">' + city + '</option> '; 
 
     }).join('') + '</select>' 
 
    ); 
 
    
 
    var city = $('#city option:selected').val(); 
 
    console.log(city) // initially selected city (none) 
 
    $("#city").on('change', function() { 
 
     city = $(this).find('option:selected').val(); 
 
     console.log(city); // changed option for new selected city 
 
    }); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="cities"> 
 
</div> 
 
<div class="btn-group"> 
 
</div>