Add onblur event to ASP.Net MVC's Html.TextBox
Asked Answered
L

2

5

What's the correct syntax for an HTML helper (in MVC2) to define an onblur handler where the textbox is generated with code like:

<%=Html.TextBox(
    "ChooseOptions.AddCount" + order.ID,
    (order.Count > 0) ?  AddCount.ToString() : "",
    new { @class = "{number: true}  small-input" }
)
Luella answered 8/5, 2010 at 17:52 Comment(0)
D
8

Add the onblur to htmlattributes

<%=Html.TextBox(
    "ChooseOptions.AddCount" + order.ID,
    (order.Count > 0) ?  AddCount.ToString() : "",
    new { @class = "{number: true}  small-input", onblur = "alert('fired')" }
) %>

Or a better way add it with jQuery

$('#ChooseOptions_AddCount' + id).onblur(function() { alert('fired'); });
Dowsabel answered 8/5, 2010 at 17:54 Comment(2)
The page uses jQuery but I haven't parsed the model values over to it in any overt way. In order to use the jQuery suggestion i'd have to do some sort of <script> jqValue = <%=serverSideValue%> </script>, right. Things are quite _that magical yet, are they?Luella
It should be "blur" not "onblur" $('#ChooseOptions_AddCount' + id).blur(function() { alert('fired'); });Oboe
M
0

I wanted to submit a solution which allows you to reuse your function code, if you want. You can define the function elsewhere, and then call it from the HTML element.

Somewhere in the myView.cshtml file (maybe at the top of the body tags) you can define a script and define myFunc inside, like this:

<script>
    function myFunc() {
        alert('fired');
    }
</script>

Then call it from the HTML element, like this:

<%=Html.TextBox(
    "ChooseOptions.AddCount" + order.ID,
    (order.Count > 0) ?  AddCount.ToString() : "",
    new { @class = "{number: true}  small-input", onblur = "myFunc()" }
) %>

Or, if you're happy to use a HTML helper to define your textbox, you can do

@Html.TextBoxFor(m => m.ChooseOptions.AddCount,
    (order.Count > 0) ?  AddCount.ToString() : "",
    new { @class = "{number: true}  small-input", onblur = "myFunc()" }
)
Modillion answered 23/9, 2018 at 21:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.