brian4342
brian4342

Reputation: 1253

Get value from html textbox with javascript

I have created an ASP.NET MVC app and would like to do some "stuff" with a value in the textbox before its sent back to the controller.

So I have a textbox in a form:

using (Html.BeginForm("HandleForm","Home")
{
    <p>Enter Value<p>
    @Html.TextBox("amount")
    <input type="submit" value="Submit" />
}

normally i would use something like this in JS:

var value = document.getElementById(ID).value;

So how would I do this with the HTML Helpers? is it possible to give this textbox an id?

Upvotes: 2

Views: 3670

Answers (3)

Nitin Varpe
Nitin Varpe

Reputation: 10704

Ofcourse you can assign Id, Class and various Html attributes to any Html Helper as these helpers are parsed to normal html tags.

E.g

@Html.TextBoxFor(m=>m.amount,new { id = "txtAmount", class="anyClass" })

or

@Html.TextBox(m=>m.amount,null,new { id = "txtAmount", class="anyClass" })

This is parsed to

<input id="txtAmount" name="amount" class="anyClass" type="text" />

Then in javascript you can access value of this control as

  var value = document.getElementById("txtAmount").value;

Upvotes: 0

Arunkumar Ravikumar
Arunkumar Ravikumar

Reputation: 31

we can specify additional html attributes when using html helpers in mvc

http://msdn.microsoft.com/en-us/library/dd493049(v=vs.118).aspx

The html attributes are specified as simple object eg

new { id = "text1", maxlength="20", size="15" }

Method Signature

public static MvcHtmlString TextBox(
    this HtmlHelper htmlHelper,
    string name,
    Object value,
    Object htmlAttributes
)

Upvotes: 0

Alexandre Rondeau
Alexandre Rondeau

Reputation: 2687

You can't get an HTML Helper for that, but this might help you.

var value = document.getElementById('@Html.Id("amount")').value;

using the @Html.Id() Html Helper you will get the id of that specific viewData

Upvotes: 1

Related Questions