Converting Span to Input

javascript, jquery, jsp, web-applications

Solution

Would be good to change your dom structure to something like this (note that the span and the input are side by side and within a shared parent `.inputSwitch`

<div class="inputSwitch">
First Name: <span>John</span><input />
</div>
<div class="inputSwitch">
Last Name: <span>Doe</span><input />
</div>

Then we can do our JS like this, it will support selecting all on focus and tabbing to get to the next/previous span/input: http://jsfiddle.net/x33gz6z9/

var $inputSwitches = $(".inputSwitch"),
  $inputs = $inputSwitches.find("input"),
  $spans = $inputSwitches.find("span");
$spans.on("click", function() {
  var $this = $(this);
  $this.hide().siblings("input").show().focus().select();
}).each( function() {
  var $this = $(this);
  $this.text($this.siblings("input").val());
});
$inputs.on("blur", function() {
  var $this = $(this);
  $this.hide().siblings("span").text($this.val()).show();
}).on('keydown', function(e) {
  if (e.which == 9) {
    e.preventDefault();
    if (e.shiftKey) {
      $(this).blur().parent().prevAll($inputSwitches).first().find($spans).click();
    } else {
      $(this).blur().parent().nextAll($inputSwitches).first().find($spans).click();
    }
  }
}).hide();

Problem

I am developing web app, I have such a requirement that whenever user click on `text` inside `span` i need `convert` it into `input field` and `on blur` i need to `convert it back` to span again. So i am using following script in one of my jsp page. Java Script: ``` <script type="text/javascript"> function covertSpan(id){ $('#'+id).click(function() { var input = $("<input>", { val: $(this).text(), type: "text" }); $(this).replaceWith(input); input.select(); }); $('input').live('blur', function () { var span=$("<span>", {text:$(this).val()}); $(this).replaceWith(span); }); } ``` JSP Code: ``` <span id="loadNumId" onmouseover="javascript:covertSpan(this.id);">5566</span> ``` Now my problem is, everything works fine only for the first time. I mean whenever i click on the text inside span for the `first time` it converts into input field and again `onblur` it coverts back from input field to normal text. But if try once again to do so it won't work. Whats wrong with above script?

Original source