Reputation: 8552
I'm trying to perform some realtime phone-number validation using javascript. I don't need help on the validation; I just need help pulling the value from the textbox into a Javascript variable.
However, on page load, I'm getting an error that says, "The name 'txtPhone' does not exist in the current context."
Here is where I declare the textbox in MVC2:
<div class="editor-field">
<%: Html.TextBoxFor(model => model.phone, new { id = "txtPhone", onblur = "checkPhoneNumber();" })%>
<%: Html.ValidationMessageFor(model => model.phone) %>
</div>
On the same page, I have this javascript:
function checkPhoneNumber() {
var phone = $("#<%= txtPhone.ClientID %>").value;
}
If I comment-out the txtPhone reference in Javascript, the page will load, and I can see the ID is properly assigned to the text box as follows (from View Source):
<div class="editor-field">
<input id="txtPhone" name="phone" onblur="checkPhoneNumber();" type="text" value="" />
Upvotes: 1
Views: 538
Reputation: 721
Using straight Javascript you can get a reference to the TextBox with
document.getElementById('myText')
but it looks like you are using a framework (jQuery perhaps)? If you are using jQuery I believe the syntax is
$("#txtPhone")
either way, once you get a reference to the text box, setting the value should work the way you are trying.
Upvotes: 1
Reputation: 887365
You're trying to work with ASP.Net server controls, which MVC doesn't use.
You only need ClientID
because ASP.Net server-side controls emit unique IDs in their generated HTML.
ASP.Net MVC does not create any server-side controls; TextBoxFor
will aways use the ID you provide it as-is.
Upvotes: 1