title: How can I switch a text box for a <label>, <div>, or <span> using jQuery?
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>So I had the idea to use jQuery to swap out the input controls for <code>&lt;label&gt;</code>, <code>&lt;div&gt;</code>, or <code>&lt;span&gt;</code> elements. This works, to some extent, by creating the appropriate selectors and using the <code>replace()</code> jQuery method to swap out the elements dynamically.</p>
  
  <p>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). </p>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p>Here is what I have so far:</p>
  
  <pre><code>$(":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("&lt;div id='" + oldId + "'&gt;" + $(this).val() + "&lt;/div&gt;");
      $("div#" + oldId).attr("class", oldClass);
      $("div#" + oldId).attr("style", oldStyle);
      $("div#" + oldId).width(oldWidth);
      $("div#" + oldId).height(oldHeight);
      $("div#" + oldId).css("display", "inline-block");
  });
  </code></pre>