Skip to content Skip to sidebar Skip to footer

Jquery Multiselect Doesnt Work On Dynamically Added Element Into Html Page

I dynamically create element using js calling js function like this function addElement(){ var counter = 1; var newdiv = document.createElement('div'); newdiv.id='dynam

Solution 1:

You have to call it again after injecting element, because your first code is just getting executing once when DOM is loaded, and you are adding elements to DOM via js after DOM is loaded:

functionaddElement(){
    var counter = 1;
    var newdiv = document.createElement('div');
    newdiv.id='dynamicdiv' + counter;
    newdiv.innerHTML += "<select class=\"checkedValues\" multiple=\"multiple\"><option value=\"1\">One</option><option value=\"2\">Two</option></select>";
    document.getElementById(divName).appendChild(newdiv);
    counter++;

    $(newdiv).find('.checkedValues').multiselect({
     includeSelectAllOption: true
   });  // call it here again
}

Solution 2:

You can bind the multiselect to recently added item after appending:

functionaddElement(){
  var counter = 1;
  var newdiv = document.createElement('div');
  newdiv.id='dynamicdiv' + counter;
  newdiv.innerHTML += "<select class=\"checkedValues\" multiple=\"multiple\"><option value=\"1\">One</option><option value=\"2\">Two</option></select>";
  document.getElementById(divName).appendChild(newdiv);
  counter++;

  $('#'+divName+' .checkedValues:last').multiselect({
     includeSelectAllOption: true
  }); 
}

Solution 3:

You need to call the code on the new element. The code does not magically listen for new elements to be added to the page.

var counter =1;

function addElement() {
  var newdiv = $("<div/>", {
    id: 'dynamicdiv' + counter
  });
  var select = $("<select class=\"checkedValues\" multiple=\"multiple\"><option value=\"1\">One</option><option value=\"2\">Two</option></select>");
  newDiv.append(select);
  $("#"+ divName).append(newdiv);
  select.multiselect({
    includeSelectAllOption: true
  });
  counter++;
}

Post a Comment for "Jquery Multiselect Doesnt Work On Dynamically Added Element Into Html Page"