0

I have the following html code that I would like to change it to use html helper methods instead.

<div class="form-group col-sm-4 col-md-4 col-lg-4">
    <label>Date of Birth</label>
    <div class="input-group date" id="dtp">
        <input name="Birthday" id="txtBirthday" class="form-control" onfocus="$(this).next().trigger('click')" onkeydown="event.preventDefault()" />
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-calendar"></span>
        </span>
    </div>
    @Html.ValidationMessageFor(m => m.Birthday)
</div>

I want to change the above html code to the following using html helper methods but I don't know how to write onkeydown="event.preventDefault()" and $(this).next().trigger('click')" in the below code.

<div class="form-group col-sm-4 col-md-4 col-lg-4">
    @Html.LabelFor(m => m.Birthday)
    @Html.EditorFor(m => m.Birthday, new { @class = "form-control", id="txtBirthday" })    
    @Html.ValidationMessageFor(m => m.Birthday)
</div>
4
  • 1
    Use @Html.TextBoxFor() or if EditorFor, then the format is @Html.EditorFor(m => m.Birthday, new { htmlAttributes = new { @class = "form-control" } }) Commented Mar 4, 2018 at 21:14
  • @StephenMuecke I would like to use @Html.TextBoxFor() but how can I write onkeydown="event.preventDefault()" in it ? Commented Mar 4, 2018 at 21:17
  • 2
    Stop polluting your markup with behavior - use Unobtrusive Javascript - $('#Birthday').keydown(function(e) { ... }); Commented Mar 4, 2018 at 21:21
  • And $(this).next().trigger('click')" as an attribute makes no sense so not clear what your trying to do with that. Commented Mar 4, 2018 at 21:22

1 Answer 1

1

You can add the onfocus and onkeydown to the same object where you added the @class = "form-control. As seen below

@Html.EditorFor(m => m.Birthday, new { @class = "form-control", id="txtBirthday", onkeydown = "event.preventDefault()", onfocus = "$(this).next().trigger('click')" })

Sign up to request clarification or add additional context in comments.

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.