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" }
)

2 Answers 2

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'); });
Sign up to request clarification or add additional context in comments.

2 Comments

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?
It should be "blur" not "onblur" $('#ChooseOptions_AddCount' + id).blur(function() { alert('fired'); });
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()" }
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.