1

I have an MVC form that users will complete by filling out fields (a mixture of TextBoxFor's and TextAreaFor's). The form will be submitted and persisted to the database.

Users will then have the option to update the form at a later date by using one of several buttons. Amongst them:

  • Amend Details - Allows the user to change the details of any field previously completed.
  • Add Details - Complete a field that was previously left blank.

When wishing to update their details, the actions to be taken by the user are:

  1. When the user first opens their form to update the details, the View will present all details using DisplayFor's. All fields are locked down for editing.

  2. If the user clicks, for example, the "Amend Details" button, they are then presented with a popup box containing checkboxes; one for each field that has been completed to date.

  3. The user selects the checkboxes that correspond to the fields they wish to change and then upon clicking an "Update" button, the popup will close and the form is back in focus.

  4. The fields that the user has chosen to update have now changed from DisplayFor to TextBoxFor to allow editing.

Step 4 of this process is what I'm having trouble with. I have found that there are several ways to do it via jQuery where you can change input tags from one to another. For example:

marker = $('<span />').insertBefore('#myInput');
$('#myInput').detach().attr('type', 'text').insertAfter(marker).focus();
marker.remove();

Taken from: jQuery: Change element type from hidden to input

Are there any ways in which I can do this sort of conversion with the MVC input tags in mind?

Community
  • 1
  • 1
Stu1986C
  • 1,282
  • 1
  • 17
  • 30

1 Answers1

2

The mix of server-side and client-side technologies here limits you somewhat. You need to make sure there is a form input type initially -- this means either a HiddenFor element, or a regular TextBoxFor element that is initially hidden.

The example you cite uses the former, but in your case I'd lean towards the latter as being a bit simpler. Place both the label and text boxes on the form, with the text box initially hidden:

<div>
    @Html.DisplayFor(model => model.SomeField)
</div>
@Html.TextBoxFor(model => model.SomeField, new { style = "display:none" })

Now, when the user clicks to edit the field, you can simply hide the one, and show the other:

$("input[name=SomeField]").show().prev().hide();

You could use a helper function that makes a field editable, given the name of the field:

function makeEditable(fieldName) {
    $("input[name=" + fieldName + "]").show().prev().hide();
}

So, once you have the list of fields that the user has checked, all you need to do is loop through and call the above helper function:

var fieldsToEdit = [ "SomeField", "AnotherField" ];
fieldsToEdit.forEach(makeEditable);
McGarnagle
  • 96,448
  • 30
  • 213
  • 255