I'm trying to "single source" a form page which can be in edit mode or view mode. For various reasons, this isn't using the ASP.Net FormView or DetailsView controls.
Since there is no way to disable a textbox without turning its contents gray (well, we could "eat" all of the keystrokes into it, but that isn't very elegant either) and disabling a dropdown list or listbox isn't what we want, our first try was to duplicate all of the form input controls with a label and use CSS to select which ones are visible depending on the mode of the form. That works, but it's ugly to edit and the code-behind has to populate both controls every time.
We could control the visibility in the code-behind to avoid filling both controls, but we still have to add them both to the form.
So I had the idea to use jQuery to swap out the input controls for <label>
, <div>
, or <span>
elements. This works, to some extent, by creating the appropriate selectors and using the replace()
jQuery method to swap out the elements dynamically.
The problem is that I not only need to copy the contents, but also the styles, attributes, and sizing of the original input controls (at this point we're only talking about textboxes - we have a different solution for dropdown lists and listboxes).
Brute force should work - "backup" all of the attributes of the input control, create the new "read only" element, then replace the input control with the new element. What I'm looking for is something simpler.
Succinctly, using jQuery, what is the best way to replace a textbox with a label and have the label have the same contents and appear in the same location and style as the textbox?
Here is what I have so far:
$(":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");
});