开发者

MVC2 - Trying to pull a textbox's value into Javascript

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开发者_C百科 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="" />


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜