2013-10-29 63 views
0

我正在使用ASP MVC 3,並且當我更改我的dropdownlistfor的值時,當前有問題在我的文本框中獲取新數據。更改TextBoxFor當更改DropDownListFor

<div id="BagelProductEdit"> 
      <h2>Bagel</h2> 
      @Html.DropDownListFor(x => x.SelectedOptionBagel, Model.LstBagelsList, new { @class = "width200", @onchange = "refreshTextBoxFors()" }) 
      <br /> 

       <table> 
       <tr> 
        <td>Bagelnaam</td><td> @Html.TextBoxFor(x => x.LstBagels.ElementAt(x.SelectedOptionBagel).Name,new { Name ="txtEditBagelName" })</td> 
       </tr> 
       <tr> 
        <td>Vertaling</td><td> @Html.TextBoxFor(x => x.LstBagels.ElementAt(x.SelectedOptionBagel).NameFr,new { Name ="txtEditBagelNameFr" })</td> 
       </tr> 
       <tr> 
        <td>Prijs</td> 
        <td> @Html.TextBoxFor(x => x.LstBagels.ElementAt(x.SelectedOptionBagel).Price,new { Name ="txtEditBagelPrice" })</td> 
       </tr> 

      </table> 
      <input class="button widthorderProduct" type="submit" name="BtnEditBagel" value="Edit een bagel" /> 
     </div> 

當我的下拉列表的值發生變化時,如何在我的文本框中獲取刷新值?

回答

0

您可以添加一個ID到下拉列表:

@Html.DropDownListFor(x => x.SelectedOptionBagel, Model.LstBagelsList, new { @class = "width200", @onchange = "refreshTextBoxFors()", id= "myDDL" }) 

然後,在refreshTextBoxFors()你可以訪問下拉列表中選擇值這樣(假設你使用jQuery的):

$("#myDDL").val(); 

如果您需要選擇的文字(不是數值):

$("#myDDL :selected").text(); 

在你不使用jQuery的,但普通的Javascript,你可以用這個在DropDownList中獲取選擇的值:

var e = document.getElementById("myDDL"); 
var selValue = e.options[e.selectedIndex].value; 

編輯 - 設置文本框的數據:

一旦你的DDL選擇的值,你可以這樣做:現在

if(selValue == '1'){ 
    $('#test').val('here is the value you want to put'); 
} 
else{ 
$('#test').val('other value'); 
} 

,在您的評論的例子,看來你有tex的列表tBoxFors。所以如果你在一個循環中添加一個id,它會將它設置到所有的文本框中。您可以改爲@class = "test",然後使用$('.test')而不是$('#test')訪問文本框。

+0

這是一個很好的例子,如何檢索索引,但仍textboxfors沒有更新.. 我現在有一個功能,從下拉列表retreive指數: 功能refreshTextBoxFors(){ $(「#bagelname」 ).VAL($( 「#myDDL」)VAL())。 index = $(「#bagelname」)。val(); } 這是我textboxfor: ​​Bagelnaam​​@ Html.TextBoxFor(X => x.LstBagels.ElementAt(指數).name和新{名稱= 「txtEditBagelName」 ID = 「測試」}) –