0

I am trying to make a link which when clicked turns into a text-box. The text-box is "focused" by default and when you click anywhere outside the text-box (thus making it "unfocused", it turns back to the original link. I am trying to use replaceWith() function in JQuery to do this, but couldn't get it correctly. The link turns into the text-box but and but for some reason which I am not properly understanding it doesn't turn back into the link when the text-box is "unfocused". Here is the fiddle that I've created to illustrate this. Could anyone tell me what I am doing wrong here.

The code that I've used is,

<script>
    $(document).ready(function() {
      $('a.edit').click(function() {
        var removed = $(this).replaceWith("<input type='text' class='searchBox'/>");
        $('input.searchBox').focus();
      });

      $('input.searchBox').focusout(function() {
        $(this).replaceWith('<a class="edit" href="#">Edit</a>');
      });
    });
</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">

<div class="controls">
  <a class="edit" href="#">Replace Link</a>
</div>

Thanks a lot. :)

Shuping
  • 4,888
  • 5
  • 37
  • 59
Sudo
  • 21
  • 1
  • 7

1 Answers1

1

Attach events to parent .controls element, use event delegation

$(document).ready(function() {
  $(".controls").on("click", 'a.edit', function() {
    var removed = $(this).replaceWith("<input type='text' class='searchBox'/>");
    $('input.searchBox').focus();
  });

  $(".controls").on("focusout", 'input.searchBox', function() {
    $(this).replaceWith('<a class="edit" href="#">Edit</a>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<div class="controls">
  <a class="edit" href="#">Replace Link</a>
</div>
guest271314
  • 1
  • 10
  • 82
  • 156
  • Thanks much for the response. I am still learning JQuery and your post helps a lot. :) – Sudo Oct 04 '16 at 04:43
  • @Sudu See also [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element/) , [Understanding Event Delegation](https://learn.jquery.com/events/event-delegation/) – guest271314 Oct 04 '16 at 04:44