views:

131

answers:

3

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?

+2  A: 
<%= Html.TextBox("Ejemplo",string.Empty,new{onkeyup="SumaEjemplo()"})%>
Gregoire
thanks, works like a charm...
hminaya
-1 because it doesn't allow multi-event binding. Griegs answer is much better.
Robert Koritnik
Wrong, it allows multi-event binding: Html.TextBox("Ejemplo",string.Empty,new{onkeyup="SumaEjemplo1();SumaEjemplo2();"})%>
Gregoire
And, with my method no need to rebind the events after a partial update
Gregoire
+1  A: 

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.

griegs
+2  A: 

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.

Robert Koritnik
thanks for the additional info.
hminaya
Actually it's $("#Ejemplo").keyup(SumaEjemplo); without the "on"
hminaya
you're right. changed it.
Robert Koritnik