0

I'm getting a little perplexed by this issue I've had for a few days now. The background is that I've wrote a page containing a table and I want to be able to click on text within the table contents in order to edit them. I've wrote some JS (well, I'm using JQuery) and it doesn't seem to be working. I can get the text to change to an input field but struggling to click into it. What's even more strange is that I can tab into the text box.

As a proof of concept to make the code easier, I've created a test HTML / JS page which is doing the same thing.

If anyone can please help me pinpoint this problem that would be great. I must confess that I'm just learning JS/JQuery at the moment.

Thanks in advance

Wayne

HTML FILE

<html>
  <head>
    <title>Testing Page</title>
  </head>
  <body>
  <p id="test" class="testclick">
    Boo
  </p>
  <script src="jquery-1.11.3.min.js"></script>
  <script src="test.js"></script>
  </body>
</html>

test.js FILE

$(document).on('click','.testclick',function(){
  var element_text;
  element_text = '<form name="test_form" method="">';
  element_text += '<input type="text" name="name" placeholder="Boo" value="">';
  element_text += '</form>';
  $('#test').html(element_text);
  console.log(element_text);
})
Smurf
  • 541
  • 1
  • 7
  • 12

1 Answers1

4

Every time you click on the input element, that event bubbles up the DOM tree, and eventually hits the parent <p> tag. Since that tag still has the testclick class, your code runs again, and replaces the form and input element with a new copy.

The simplest solution would be to remove the CSS class when you replace the content:

$(document).on('click','.testclick',function(){
  var element_text;
  element_text = '<form name="test_form" method="">';
  element_text += '<input type="text" name="name" placeholder="Boo" value="">';
  element_text += '</form>';
  $('#test').html(element_text).removeClass('testclick');
  console.log(element_text);
})

jsFiddle

Community
  • 1
  • 1
Richard Deeming
  • 29,830
  • 10
  • 79
  • 151