简体   繁体   中英

How to write Javascript code for HTML helpers ASP.NET MVC?

I have an HTML helper textBox like this:

@Html.TextBox("txt1") <br />

Now I want to fire a javascript onchange event on this textbox. Is it possible to do so or should I use an HTML input type instead.

You can specify html attributes using the htmlAttributes parameter of the TextBox Html helper method like so:

@Html.TextBox("txt1", null, new { onchange="..." })

See: InputExtensions.TextBox Method

From the above link:

The htmlAttributes parameter consists of an object that contains name/value pairs. The attributes that are specified in the name/value pairs depend on the HTML element that is being rendered.

If you have an ID for this textbox, you can hook the event to the textbox using Jquery.

$("#textboxid").keydown(function(event) {
    alert("Hey!");
});

Note that I've used the Keydown event. You can also use press or up events.

Or you can make the binding in the ready event.

$(document).ready(function(){
        $("#textboxid").bind("onchange", yourfunction);
          });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM