I am trying to save a phone number, but when I try to pass in the value through some javascript, it is null in the backend.
this is my 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" />
</div>
and this is my JS
document.getElementById("#phone").val("#phoneInput");
CodePudding user response:
I would also get rid of the # in id = "#phone" as its not needed and will just complicate things as you learn more.
Then in getElementById don't need to pass the #. And second, val isn't valid vanilla javascript, and #phoneInput would just set the value to the string of "#phoneInput".
This is a very basic version of what you are trying
document.getElementById("phone").value = document.getElementById("phoneInput").value;
CodePudding user response:
Don't use
#phone
as anid
, just simplyphone
instead:id = "phone"
What is
.val()
? You're trying to set the.value
property:document.getElementById("phone").value = "#phoneInput";
Are you sure you want the value to be the literal string
"#phoneInput"
? Or do you want it to be the value of thephoneInput
element?:document.getElementById("phone").value = document.getElementById("phoneInput").value;
Make sure you do this after an actual value has been entered, such as in response to a
change
event or some other UI event.
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>
As an aside... Are you sure you need all of this at all? Why not just make the TextBoxFor
helper be a tel
input?:
@Html.TextBoxFor(m => m.Phone, new { type = "tel" })