如何从选择选项中获得结果?

时间:2015-03-27 12:32:16

标签: jquery html forms select

我想创建一个select选项,其中每个选项在div上显示不同的html文本。

<form>
    <label>Select Country:</label>
    <select class="country">
        <option value="1">United States</option>
        <option value="2">India</option>
        <option value="3">United Kingdom</option>
    </select>
</form>

和jquery。

$("select.country").change(function(){
    var selectedCountry = $(".country option:selected").val();
   // alert("You have selected the country - " + selectedCountry);
    $('#mydiv').prepend('<h2> option one </h2>');
});

我怎样才能做到这一点。任何的想法。

由于

3 个答案:

答案 0 :(得分:1)

如果我理解你的问题,这样的事情对你有用:DEMO

<强> HTML

<form>
    <label>Select Country:</label>
    <select class="country">
        <option disabled>Please select a country</option>
        <option value="us">United States</option>
        <option value="india">India</option>
        <option value="uk">United Kingdom</option>
    </select>
</form>
<div id="uk" class="countryOption"><img src="http://upload.wikimedia.org/wikipedia/en/a/ae/Flag_of_the_United_Kingdom.svg" /><br />Text about the UK</div>
<div id="us" class="countryOption"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/US_flag_48_stars.svg/220px-US_flag_48_stars.svg.png" /><br />Text about the US </div>
<div id="india" class="countryOption"><img src="http://upload.wikimedia.org/wikip1/Flag_of_India.svg/225px-Flag_of_India.svg.png" /><br />Text about India</div>

<强>的jQuery

$("select.country").change(function(){
    var selectedCountry = $(this).val();
    $('.countryOption').hide()
    $('#' + selectedCountry).show();
});

如果我不在这里,请告诉我。希望这有帮助!

答案 1 :(得分:1)

&#13;
&#13;
$(".country").change(function(){
       var selectedCountry = $(".country").val();
        var text = $('.country option:selected').text();
        var text1='You have selected:';
   if( selectedCountry > 0 ){
      
  $('#mydiv').html(text1+text );
   }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<html>
  <select class="country">
    <option>Please Select </option>
    <option value="1">India </option>
    <option value="2">UK </option>
    <option value="3">Canada </option>
    <option value="4">Iran </option>
  </select>
  <div id="mydiv"> </div>
  </html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

试试这个

	
function getval(){

   var selectedCountry = $('select[name=selector] option:selected').text();
    alert("You have selected the country - " + selectedCountry);
    $('#mydiv').prepend('<h2> option one </h2>');

}	
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
    <label>Select Country:</label>
    <select class="country" onChange="getval();" name='selector'>
        <option value="1">United States</option>
        <option value="2">India</option>
        <option value="3">United Kingdom</option>
    </select>
</form>