Call a JavaScript function from a texbox that is generated by an MVC Helper

10,042

Solution 1

Use event binding

By using jQuery you could write this code in Javascript (either directly inside a <script> tag or in a separate script file that's loaded with the view:

$(function(){
    $("#Ejemplo").keyup(SumaEjemplo);
});

function SumaEjemplo(eventInstance){
    // handle onkeyup event
}

This way you'll be able to attach multiple events to the same control and is considered the proper way of doing this.

Solution 2

<%= Html.TextBox("Ejemplo",string.Empty,new{onkeyup="SumaEjemplo()"})%>

Solution 3

You could also use jQuery to automatically bind the event when the control is created. This is really only useful I guess when you want to create the controls within a javascript/jquery event.

Share:
10,042
Hector Minaya
Author by

Hector Minaya

https://github.com/hminaya

Updated on June 14, 2022

Comments

  • Hector Minaya
    Hector Minaya almost 2 years

    How do I call a JavaScript function from a texbox that is generated by an MVC Helper. I want my textbox to call a function like this:

    <input type="text" id="Ejemplo" onkeyup="SumaEjemplo()" />
    

    I'm using:

    <%= Html.TextBox("Ejemplo") %>
    

    Where do I put it?

  • Robert Koritnik
    Robert Koritnik over 14 years
    -1 because it doesn't allow multi-event binding. Griegs answer is much better.
  • Gregoire
    Gregoire over 14 years
    Wrong, it allows multi-event binding: Html.TextBox("Ejemplo",string.Empty,new{onkeyup="SumaEjemplo‌​1();SumaEjemplo2();"‌​})%>
  • Gregoire
    Gregoire over 14 years
    And, with my method no need to rebind the events after a partial update
  • Hector Minaya
    Hector Minaya over 14 years
    Actually it's $("#Ejemplo").keyup(SumaEjemplo); without the "on"