1

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="" />

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

are you saying that I should just remove the "ClientID" suffix from my Javascript?
Thanks. You were right, I just needed $("#txtPhone").val() .
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.