0

Currently I'm having this code:

    <div id="groups">
        <select multiple="multiple" id="availableGroups" name="availableGroups">
          <option >Opt 1</option>
          <option >Opt 2</option>
        </select>
    </div>

The "select" element has a click event listener which attach to it.

What I'm to do is to change the $('div#groups') content with <p> element when the user click next button, so I do like this:

var $groupContent=$('div#groups').children(); //save the content
$('div#groups').html($("<p>").append("Opt 1"))

And if the user click the prev button,I will restore the "select" element like this:

 $('div#groups').append($groupContent);

The problem is the click event listener also has been remove when I'm using .html() as stated on this question

So the question is,is there a workaround I can implement same action like .html() without removing the event listener?

Community
  • 1
  • 1
FreezY
  • 1,641
  • 2
  • 18
  • 31
  • 2
    Read about [`Event delegation`](https://learn.jquery.com/events/event-delegation/) – Rayon May 21 '16 at 04:05
  • Are you intending to replace all of the content, including the 'select' element, with a paraphraph containing 'Opt 1' as text? Using .html() you are actually replacing all of the contents of
    , so you are not just replacing the event hander, but the entire select control as well.
    – Grant Macdonald May 21 '16 at 04:07
  • Stop replacing all the HTML. Instead, add, modify or delete individual DOM elements directly as needed, thus preserving all event handlers on element which are not deleted. – jfriend00 May 21 '16 at 04:07
  • also you can save and restore event handlers: http://stackoverflow.com/questions/2518421/jquery-find-events-handlers-registered-with-an-object – Scherbius.com May 21 '16 at 04:08

1 Answers1

1

You can attach the event handler to the parent element like this. It will be preserved. Something like:

$("div#groups").on("click", "#availableGroups", yourClickHandler);

See the live demo https://jsfiddle.net/nf3wyf21/

Read more about jQuery event delegation here.

Chintan
  • 773
  • 9
  • 18