使用.Change()和dropdownlistFor(想要将选择的值添加到另一个div作为文本)

时间:2015-09-18 11:15:24

标签: javascript jquery html

我尝试将您在下拉列表中选择的值添加为div中的文本。试着用Jquery来实现这一点,但由于我对此完全陌生,我似乎无法让它发挥作用。

代码下拉列表:

<p>
   @Html.Label("Departure route:")
   @Html.DropDownListFor(m => m.Departureroute, Model.RoutesList, new {@class = "dropdownlist", @id = "departureroute"})
</p>

我已为其指定了id = departureroute。

Js代码

<script type="text/javascript">

$("#departureroute").change(function () {
  var str = "";
  $("#departureroute option:selected").each(function () {
      str += $(this).text() + " ";
  });
  $("informationcontent-outbound").text(str);
  }).change();
</script>

我希望此文字出现的div是&#34; informationcontent-outbound&#34;

希望有人能看到这里的错误。

2 个答案:

答案 0 :(得分:0)

您只需使用this.value获取所选值,无需使用each()。您的div选择器也无效

&#13;
&#13;
$("#departureroute").change(function() {
  $("#informationcontent-outbound").text(this.value);
  //-^--------- if class then use '.'
}).change();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id=departureroute>
  <option value=1 selected>1</option>
  <option value=2>2</option>
  <option value=3>3</option>
</select>
<div id="informationcontent-outbound"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

Working Demo

取决于信息内容出站Div

//Using Id Selector
 $("#departureroute").change(function () {
   $("#informationcontent-outbound").text(this.value);
    //If informationcontent-outbound is an Id use above line
   $(".informationcontent-outbound").text(this.value);
    //If informationcontent-outbound is a class use above line
 });

//Using Class Selector
$(".dropdownlist").change(function () {
   $("#informationcontent-outbound").text(this.value);
    //If informationcontent-outbound is an Id use above line
   $(".informationcontent-outbound").text(this.value);
    //If informationcontent-outbound is a class use above line
 });