![](/img/trans.png)
[英]How can I get a DropDownList selected value and send it to the controller in ASP.NET MVC 4 and using JavaScript?
[英]How to get selected value from dropdownlist in asp.net using Javascript?
我正在從數據庫中填充國家/地區下拉列表。 我需要從下拉列表中選擇一個值並使用 Javascript 將其分配給文本框。
代碼:
var textboxId = document.getElementById("txtCountry");
var dropdownListId =document.getElementById("ddlLocation");
var e = document.getElementById("ddlLocation");
var strUser = e.options[e.selectedIndex].value;
document.getElementById(textboxId).value = strUser;
document.getElementById(textboxId).focus();
通過這樣做,我得到了錯誤。 任何解決方案?
你的代碼是錯誤的,看看我在哪里對相同的代碼進行了更改:
var textboxId = document.getElementById("txtCountry");
var e = document.getElementById("ddlLocation");
var strUser = e.options[e.selectedIndex].value;
textboxId.value = strUser;
textboxId.focus();
您所做的是,您選擇了文本框,JS 返回了該文本框的 DOM 元素,並且您想通過在getElementById()
函數中傳遞文本框的DOM
來填充它。
這是它破裂的地方:
document.getElementById(textboxId).value = strUser;
要使用getElementById()
方法,您需要傳遞元素 id 的字符串值。
希望這可以幫助。
嘗試:
document.getElementById('<%=txtCountry.ClientID%>').value
或者
var textBox = document.getElementById('<%=txtCountry.ClientID%>');
textBox.value = strUser;
這是因為生成的文檔中 html 元素的 id 與您在代碼中分配的 id 不匹配。 要在 html 中獲取分配給您的控件的 id,您可以使用下拉列表的 ClientID 屬性。
另一個問題是您將 yourhtml 元素分配給變量,然后使用無效調用的 getElementById 函數。
這在即將發布的 ASP.NET 4 中有所改變。
希望有幫助!
這兩行:
document.getElementById(textboxId).value = strUser;
document.getElementById(textboxId).focus();
也錯了。 如果您的前一行確實有效:
var textboxId = document.getElementById("txtCountry");
will actually be the textbox control, so you will be doing a using the control instead of a string identifier.那么您所稱的實際上將是文本框控件,因此您將使用該控件而不是字符串標識符來執行 。
遵循@anthares所說的; 嘗試這個:
var textboxId = '<%=txtCountry.ClientID%>';
alert('My textbox id is: ' + textboxId);
並確保您獲得了文本框的正確 ID(請記住,它會被 ASP.Net 修改,至少確保您沒有得到任何東西)。 you need to check the result before using:然后,當您執行您需要在使用前檢查結果:
var myTextBox = document.getElementById(textboxId);
if (myTextBox !== null) {
...now i can access the properties...
}
如果您不想使用
document.getElementById()
嘗試一下:
var VarName = $('#<%=YouDropDownId.ClientId %>').val();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.