7

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?

1

5 Answers 5

18

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();
2
  • I have a problem now,after updating my jquery version the above code is not working.
    – Kishan_KP
    May 6, 2013 at 6:06
  • What version? I just ran it in 2.0 and 2.x (edge) and it worked fine. What is happening? Any errors showing in console?
    – Smern
    May 6, 2013 at 11:10
2

I understand you think that element replacement is a nice thing, however, I would use a prompt to get the text. Why? It is a lot easier and actually a bit prettier for the user as well. If you are curious on how to do it, I show you.

html:

<span class='editable'>foobar</span>

js:

$(function()
{
  $('span.editable').click(function()
  {
    var span = $(this);
    var text = span.text();

    var new_text = prompt("Change value", text);

    if (new_text != null)
      span.text(new_text);
  });
});

http://jsfiddle.net/qJxhV/1/

0
1

First, you need to change your click handler to use live() as well. You should take note, though, that live() has been deprecated for quite a while now. You should be using on() in both cases instead.

Secondly, when you replace the input with the span, you don't give the element an id. Therefore, the element no longer matches the selector for your click handler.

Personally, I would take a different (and simpler) approach completely. I would have both the span and in the input in my markup side by side. One would be hidden while the other is shown. This would give you less chance to make mistakes when trying to recreate DOM elements and improve performance since you won't constantly be adding/removing elements from the DOM.

2
  • "Therefore, the element no longer matches the selector for your click handler" - which click handler? covertSpan is called only once and I see no other click handler attachment. May 4, 2013 at 12:19
  • Not a bad idea! I have to try it some time.
    – Kishan_KP
    May 6, 2013 at 3:18
0

A more generic version of smerny's excellent answer with id's can be made by slightly altering two lines: $input.attr("ID", "loadNum"); becomes $input.attr("ID", $(this).attr("ID")); -- this way, it simply takes the current id, and keeps it, whatever it is.

Similarly, $span.attr("ID", "loadNum"); becomes $span.attr("ID", $(this).attr("ID"));

This simply allows the functions to be applied to any div. With two similar lines added, both id and class work fine. See example.

0

I have done little change in code, By using this input type cant be blank, it will back to its real value.

 var switchToInput = function () {
        var $input = $("<input>", {
            val: $(this).text(),
            type: "text",
            rel : jQuery(this).text(),
        });
        $input.addClass("loadNum");
        $(this).replaceWith($input);
        $input.on("blur", switchToSpan);
        $input.select();
    };
    var switchToSpan = function () {
            if(jQuery(this).val()){
                        var $text = jQuery(this).val();
                } else {
                      var $text = jQuery(this).attr('rel');
                }
        var $span = $("<span>", {
            text: $text,
        });
        $span.addClass("loadNum");
        $(this).replaceWith($span);
        $span.on("click", switchToInput);
    }
    $(".loadNum").on("click", switchToInput);

jsFiddle:- https://jsfiddle.net/svsp3wqL/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.