I am trying to create a “single source” on a form page that may be in edit mode or view mode. For various reasons, this does not use ASP.NET FormView controls or the DetailsView control.
Since there is no way to turn off the text field without turning its contents gray (well, we could “eat” all the keystrokes, but this is also not very elegant) and disable the drop-down list or list, t, what we want is our first the attempt was to duplicate all form input elements with a label and use CSS to select which ones are visible depending on the form mode. This works, but it is ugly for editing, and the code-code must fill both elements each time.
We could control the visibility of the code to avoid filling both controls, but we still need to add both of them to the form.
So I got the idea of using jQuery to replace input controls for <label> , <div> or <span> elements. This works to some extent by creating appropriate selectors and using the replace() jQuery method to dynamically change elements.
The problem is that I need to not only copy the contents, but also the styles, attributes and sizes of the original input controls (at the moment we are only talking about text blocks - we have another solution for drop-down lists and lists).
Mutual power should work — backing up all attributes of the input control, creating a new read-only element, and then replacing the input control with a new element. What I'm looking for is something simpler.
Compressed using jQuery, what is the best way to replace a text field with a label and have a label with the same content and display in the same place and style as the text field?
Here is what I still have:
$(":text").each( function() { var oldClass = $(this).attr("class"); var oldId = $(this).attr("id"); var oldHeight = $(this).outerHeight(); var oldWidth = $(this).outerWidth(); var oldStyle = $(this).attr("style"); $(this).replaceWith("<div id='" + oldId + "'>" + $(this).val() + "</div>"); $("div#" + oldId).attr("class", oldClass); $("div#" + oldId).attr("style", oldStyle); $("div#" + oldId).width(oldWidth); $("div#" + oldId).height(oldHeight); $("div#" + oldId).css("display", "inline-block"); });