2016-11-05 130 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>