Spets
Spets

Reputation: 2431

Using jQuery to toggle between DisplayFor and EditorFor in MVC

There has to be a way to toggle between a DisplayFor and a EditorFor div on my View. I want to click an "Edit" button next to a Display field and have the DisplayFor element be hidden and the EditorFor field visible. Once I'm done updating the text, I want submit the form and the data in the Editor fields.

I'm not sure why this isn't working, tips?

My jQuery

<script type="text/javascript">

function myFunction(element) {

    $(element).find("span.item-display").html($(element).find("span.item-field").find(":input:first").val());
    $(element).find("span.item-display")
        .show()
        .next("span.item-field")
        .hide();
}

My HTML View

<dt><strong>@Html.LabelFor(m => m.FirstName) </strong></dt>
        <dd>
            <span class="item-display">
                @Html.DisplayFor(m => m.FirstName)
            </span>
            <span class="item-field" style="display:none">
                @Html.EditorFor(m => m.FirstName)
            </span>

            <span>
                <button type="button" onclick="myFunction(this)" />

            </span>
        </dd>

Upvotes: 2

Views: 2613

Answers (1)

Hiren Kagrana
Hiren Kagrana

Reputation: 932

Use Jquery toggle as below:

<dt><strong>@Html.LabelFor(m => m.FirstName) </strong></dt>
    <dd>
        <span class="item-display toggle-control">
            @Html.DisplayFor(m => m.FirstName)
        </span>
        <span class="item-field toggle-control" style="display:none">
            @Html.EditorFor(m => m.FirstName)
        </span>

        <span>
            <button type="button" onclick="toggler()" />

        </span>
    </dd>
  </dt>

<script>
function toggler()
{
    $(".toggle-control").toggle();
}
</script>

Upvotes: 6

Related Questions