ExceptionLimeCat
ExceptionLimeCat

Reputation: 6400

JS Events not attaching to elements created after load

Problem: Creating an Element on a button click then attaching a click event to the new element.

I've had this issue several times and I always seem to find a work around but never get to the root of the issue. Take a look a the code:

HTML:

<select>
  <option>567</option>
  <option>789</option>
</select>

<input id="Add" value="Add" type="button">    <input id="remove" value="Remove" type="button">   

<div id="container">
  <span class="item">123</span>
  <br/>
  <span class="item">456</span>
  <br/>
</div>

JavaScript

 $(".item").click(function () {
    if ($("#container span").hasClass("selected")) {
        $(".selected").removeClass("selected");
    }
    $(this).addClass("selected");
});


$("add").click(function() {

   //Finds Selected option from the Select

   var newSpan = document.createElement("SPAN");
    newSpan.innerHTML = choice;//Value from Option
    newSpan.className = "item";
    var divList = $("#container");
    divList.appendChild(newSpan);//I've tried using Jquery's Add method with no success
   //Deletes the selected option from the select
})

Here are some methods I've already tried:

Caveat: I can not create another select list because we are using MVC and have had issues retrieving multiple values from a list box. So there are hidden elements that are generated that MVC is actually tied to.

Upvotes: 1

Views: 217

Answers (1)

Sampson
Sampson

Reputation: 268344

Use $.on instead of your standard $.click in this case:

$("#container").on("click", ".item", function(){
  if ( $("#container span").hasClass("selected") ) {
    $(".selected").removeClass("selected");
  }
  $(this).addClass("selected");
});

It looks to me like you want to move the .selected class around between .item elements. If this is the case, I would suggest doing this instead:

$("#container").on("click", ".item", function(){
  $(this)
    .addClass("selected")
    .siblings()
      .removeClass("selected");
});

Also note your $("add") should be $("#add") if you wish to bind to the element with the "add" ID. This section could also be re-written:

$("#add").click(function() {
  $("<span>", { html: $("select").val() })
    .addClass("item")
    .appendTo("#container");
});

Upvotes: 2

Related Questions