用另一个输入的值填充html.textboxfor



我试图保存一个电话号码,但当我试图通过一些javascript传递值时,它在后端为null。

这是我的html

<div style="margin-bottom: 15px;">
@Html.LabelFor(m => m.Phone)
@Html.TextBoxFor(m => m.Phone, new { 
id = "#phone",
style = "display: none;",
})
<input type="tel" id="phoneInput" class="iti, form-control" />
</div>

这是我的JS

document.getElementById("#phone").val("#phoneInput");

我也会去掉id="中的##电话">,因为它不需要,而且随着你了解更多,它只会使事情变得复杂。

然后在getElementById中不需要传递#。其次,val不是有效的普通javascript,#phoneInput只会将值设置为字符串"#phoneInput";。

这是你正在尝试的的一个非常基本的版本

document.getElementById("phone").value = document.getElementById("phoneInput").value;
  1. 不要将#phone用作id,只需简单地使用phone

    id = "phone"

  2. 什么是.val()?您正在尝试设置.value属性:

    document.getElementById("phone").value = "#phoneInput";

  3. 您确定要将值设为文本字符串"#phoneInput"吗?还是希望它是phoneInput元素的值?:

    document.getElementById("phone").value = document.getElementById("phoneInput").value;

  4. 请确保在输入实际值后执行此操作,例如响应change事件或其他UI事件。

document.getElementById("phoneInput").addEventListener("change", function () {
document.getElementById("phone").value = document.getElementById("phoneInput").value;
});
<div style="margin-bottom: 15px;">
<label for="phone">Phone</label>
<input type="text" name="phone" id="phone" />
<input type="tel" id="phoneInput" />
</div>


作为旁白。。。你确定你需要这些吗?为什么不将TextBoxFor辅助对象设置为tel输入?:

@Html.TextBoxFor(m => m.Phone, new { type = "tel" })

最新更新