noel293
noel293

Reputation: 504

jQuery - Is it possible to change selectbox's options during cloning?

Is it possible to change selectbox's options during cloning?

I am cloning a div with its inner children. Each one of them has a different id every time they get cloned. The original div contains a select box which gets it's values from the database. My question is, is it possible to amend the values of the cloned select boxes so they will not contain the previous selected values? Any tips on how to do this?

What I need is the newly created select boxes won't contain the values of the previous selections.

Example if in select box 1 I choose 1 (from a range 1-10) then the value 1 will not appear in the other select boxes

JS

<script>
document.getElementById('btn_new_service').onclick = duplicate;
var i =0;
function duplicate() {
    var original = document.getElementById('duplicator');
    var clone = original.cloneNode(true); // "deep" clone
    clone.id = "duplicator" + ++i; // there can only be one element with
    var new_service_ID = 'c_service-'+i;
    var new_vat_ID = 'vat-'+i;
    var new_amount_ID = 'amount-'+i;
    var new_vatamount_ID = 'vat_amount-'+i;
    clone.querySelector('#c_service').setAttribute('id',new_service_ID);
    clone.querySelector('#vat').setAttribute('id',new_vat_ID);
    clone.querySelector('#amount').setAttribute('id',new_amount_ID);
    clone.querySelector('#vat_amount').setAttribute('id',new_vatamount_ID);
    original.parentNode.appendChild(clone); 
};
</script>

Upvotes: 1

Views: 48

Answers (1)

Apolo
Apolo

Reputation: 4050

You should keep track of what's selected and regenerate a select from scratch, this would be easier

const selectClass = "mySelect";
const options = [
  {id: "c_service", name: "c_service"},
  {id: "vat", name: "vat"},
  {id: "amount", name: "amount"},
  {id: "vat_amount", name: "vat_amount"}
];

var id = 0;

function addSelect() {
  // Get selects
  let selects = document.getElementsByClassName(selectClass);
  // Get all selected values
  let selectedOpts = [];
  for (let select of selects) {
    if (select.value != "") {
      selectedOpts.push(select.value);
    }
  }
  // Create the new select
  let select = document.createElement("select");
  select.setAttribute("class",selectClass);
  select.appendChild(document.createElement("option"));
  // Get available options
  var avOpts = options.filter(o => selectedOpts.indexOf(o.id) == -1);
  // Create the options
  for (var option of avOpts) {
    id++; 
    let o = document.createElement("option");
    o.setAttribute("id", option.id + id);
    o.innerHTML = option.name;
    select.appendChild(o);
  }
  // Add the select to DOM
  document.getElementById("divToInsertInto").appendChild(select);
}


// add the initial select
addSelect();
// Attach event
document.getElementById('btn_new_service').onclick = addSelect;
<button id="btn_new_service">clone</button>

<div id="divToInsertInto">
</div>

Upvotes: 1

Related Questions