0

I have created a form on my website and have used JQuery to show/hide elements based on previous selections and to add more fields. This works great.

Moving on from this I want JQuery to insert this form dynamically into the DOM when a user clicks a link using onclick($.html). This is also all working. When a user clicks a link, the form for that link shows up on the page right away.

However when the form is loaded with $.html my other JQuery statements (show/hide elements etc) no longer work.

Are we able to use JQuery on elements inserted by JQuery $.html?

2
  • 1
    Can you share your code? Also do you get any error in console? Commented Mar 8, 2014 at 15:29
  • it would be nice if you give us a fiddle Commented Mar 8, 2014 at 15:37

2 Answers 2

1

You can assign events to DOM elements created using jQuery. Without code (you should always provide), I can't say for certain, but I guess you're overwriting an element you previously had an event handler for.

Whenever possible, .append() new HTML rather than overwriting it, then you don't need to reassign the events. If you truly have to make a new element, then you have two solutions:

  1. Reassign the event handler
  2. Use event delegation to set the event handler on the first parent which isn't overwritten

See jQuery's .on() for more, but the general syntax is:

$("#always-element").on("click", ".overwritten-elem-selector", function() {
    // work
});

And here's an altogether trivial example (JSFiddle):

JS

var nums = 1;

$("#more").on("click", function() {
    var $newElem = $("<div></div>").text(++ nums);        
    $("#foo").html($newElem);
});

$("#foo").on("click", "div", function() {
    $(this).css("background-color", "#FF0000");
});

HTML

<button id="more">More</button>
<div id="foo">
    <div>1</div>
</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your detailed and very helpful response, Ian. This wasn't quite the case on this occasion as I was already using .on(). apologies for lack of code, I was working on a fiddle that actually helped to fix my own problem. Thanks again.
0

Yes you can use jQuery on markup inserted into the DOM, but you have to be sure that that code is bound after the content is inserted into the page and not before.

To elaborate, and demonstrate the problem I think you're having, consider the following fiddle http://jsfiddle.net/47wVQ/:

You have some location in the DOM where you're inserting elements:

<div id="testTarget"></div>

And some JS:

var elemBefore = $('<p id="thingToInteractWith">BEFORE</p>');

$('#thingToInteractWith').on('click', function(){
    $(this).hide();
});

$('#testTarget').append(elemBefore); //At this point, the element is in the DOM

//Below is what should be done instead
var elemAfter = $('<p id="anotherThingToInteractWith">AFTER</p>');

//Binding AFTER element exists

$('#testTarget').append(elemAfter); //At this point, the element is in the DOM

//Here I'm binding the click action after the markup is in the DOM
$('#anotherThingToInteractWith').on('click', function(){ 
    $(this).hide();
});

The long story short if you're inserting new content into the DOM (like your form) and you want show/hide, etc to work on that new content, make sure to fire your JS after you use $.html.

In your specific example this would look like:

function bindEvents(){
   //This assumes you have form elements with the following IDs
   $('#myFormElement1').on('change', function(){ $(this).hide() });
   $('#myFormElement2').on('change', function(){ $(this).hide() });
}

var $form; //We'll pretend this variable holds the markup for your form
$('#target').html($form); //Your form is now in the DOM
bindEvents(); //Since myFormElement1..2.. now exist, they can be interacted
//with and so calling bindEvents after the $.html call will work

2 Comments

Thanks for your response, Kaminari. I did think that I was binding elements before they became available and that was the issue. The form modifying events were loaded on document ready and my function that inserted the form code was triggered by an event that happened later on. A simple move around of the functions fixed this... Thank you.
From what you had described that seemed like it might be the issue, especially if what you had was working before. Glad to know that helped, @LeeSandel.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.