我有一个表格供人们输入用户名,如果用户名,它将为他们提供3个选项,旁边有单选按钮。我尝试使用onclick函数来获取相应的单选按钮,并将其值放入文本框中。我正在使用ASP.NET MVC 3.以下是我正在使用的视图:
@{
ViewBag.Title = "ChangeUsername";
}
<script type="text/javascript">
function setText(target) {
var txt = document.getElementById(target);
var temp = txt.value;
var tf = document.getElementById("uName_change");
tf.value = temp;
}
</script>
@using (Ajax.BeginForm("ChangeUsername", "User", new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "change_name" }, new { uniqueUserId = @Model.UserGuid }))
{
<div class="form_section">
<h3>Update Username:
</h3>
<div class="form_item">
<div class="frm_label">
<label for="username">
@AdminResource.CurrentUserName
</label>
</div>
<div class="item">
<p>@Model.UserName</p>
</div>
</div>
<div class="form_item">
<div class="frm_label">
<label for="username">
@AdminResource.UserName
</label>
</div>
<div class="item">
@Html.EditorFor(model => model.NewUsername, new { id = "uName_change" }) @Html.ValidationMessageFor(model => model.NewUsername)
@if (Model.AlternateUsernames != null && Model.AlternateUsernames.Count() != 0)
{
<p>
<strong>Suggested usernames:</strong><br />
@foreach (var username in Model.AlternateUsernames)
{
<input type="radio" name="un" id="un_Change" value="@username" onclick="setText(target);" />@username<br />
}
</p>
}
</div>
</div>
<div class="form_item">
<div class="frm_label">
<label for="password">
</label>
</div>
<div class="item">
<input type="submit" name="submit" value="Update Username" class="btn_primary" />
</div>
</div>
</div>
@Html.HiddenFor(model => model.UserGuid)
@Html.HiddenFor(model => model.UserName)
}
除了javascript部分附加文本字段的替代值之外,其他所有内容都可以正常工作。我在javascript上做错了什么?或者是&#34; AlternateUsernames&#34;是一个列表项?
答案 0 :(得分:0)
如果我理解正确,
将this
传递给函数以识别所选的无线电,如下所示
<input type="radio" name="un" id="un_Change" value="@username" onclick="setText(this);" />@username<br />
修改功能
function setText(radio) {
var txt = document.getElementById('target'); // where target is the id of the text field in which you want to display the selected option
txt.value= radio.value;
}
旁注:您已为循环内的单选按钮设置id
,这会使您的HTML无效..