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.
Comments
-
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 over 14 years-1 because it doesn't allow multi-event binding. Griegs answer is much better.
-
Gregoire over 14 yearsWrong, it allows multi-event binding: Html.TextBox("Ejemplo",string.Empty,new{onkeyup="SumaEjemplo1();SumaEjemplo2();"})%>
-
Gregoire over 14 yearsAnd, with my method no need to rebind the events after a partial update
-
Hector Minaya over 14 yearsActually it's $("#Ejemplo").keyup(SumaEjemplo); without the "on"