jquery - How can i take the value of the specific option? -
i have code :
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 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 option -- </option>' + cities.map(function (city) { return '<option value="' + city + '">' + city + '</option> '; }).join('') + '</select>' ); var city = $("#city option:selected").val(); console.log(city); }
i want take specific value of above select element every single moment takes first value , stores city
variable
i think wanted results in demo:
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 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 option -- </option>' + cities.map(function(city) { return '<option value="' + city + '">' + city + '</option> '; }).join('') + '</select>' ); var city = $('#city option:selected').val(); console.log(city) // selected city (none) $("#city").on('change', function() { city = $(this).find('option:selected').val(); console.log(city); // changed option 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>
Comments
Post a Comment