Skip to content
Advertisement

Add an element (input) in div where the js function has been fired

I’d like to insert an input in an adjacent div where the JS function has been fired.

JavaScript: to add an element (input in this case) jQuery: to detect where the javascript function has been fired.

The issues I’m facing :

  1. The input is created after the second click.
  2. All the inputs move from one div to another on each click …

I don’t understand why this happens! Do you guys have an idea why everything messes up? Thanks a lot.

JavaScript
JavaScript
JavaScript

Full code and live example in the JS fiddle right here: https://jsfiddle.net/t7x350d9/

Advertisement

Answer

Your code is much more complicated than it needs to be.

Firstly when dealing with repeated HTML structures do not use id attributes. Use the same class on them all to group them. If you need to identify each one, listen for the event and use the target to determine which element was interacted with. In the example below this can be done through the target property of the event which is raised.

Secondly, to achieve your goal simply use an unobtrusive event handler in your JS (not an onclick attribute in the HTML) and append() the new HTML. Try this:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement