I've got a list of available options in a first 'select' which is supposed the be the main option.
Then I want the user to choose optional options so when he choose the first option, a new select is added displaying the remaining options available.
If the user choose an optional option I want a new select to be displayed, etc until there's no more options.
The options also need (and here's my issue) to be synchronized between every select. I've got this code:
html
<form action="">
<select name="primary" id="primary">
</select>
<br/>
<div id="optional" style="display: none">
<button id="addField">Add field</button>
<br/>
</div>
</form>
js
var counter = 0;
var selects = [];
var categories = JSON.parse('[ { "value": "", "label": "Aucune", "taken": false }, { "value": "Électronique/Électroménager", "label": "Électronique/Électroménager", "taken": false }, { "value": "Maison Jardin", "label": "Maison Jardin", "taken": false } ]');
function addField() {
$("#optional").append("<select name='optional' id='secondary" + counter + "'></select>");
var jid = $("#secondary" + counter);
fill(jid);
jid.on("click", function () {
updateCat(jid.val());
});
selects.push(jid);
counter++;
}
function fill(select) {
console.warn("select");
//select.empty();
console.groupCollapsed();
for (var cat in categories) {
console.log(categories[cat].label + " -> " + categories[cat].taken);
if (!categories[cat].taken) {
select.append("<option value=" + categories[cat].value + ">" + categories[cat].label + "</option>");
}
}
console.groupEnd();
}
function updateCat(cat) {
console.warn("update "+cat);
var catId = findCat(cat);
if (catId != -1) {
categories[catId].taken = true;
}
for (var s in selects) {
fill(selects[s]);
}
}
function findCat(cat) {
for (var i = 0; i < categories.length; i++) {
if (categories[i].label == cat) {
return i;
}
}
return -1;
}
$(function () {
var primary = $("#primary"), optional = $("#optional"), buttonField = $("#addField");
fill(primary);
selects.push(primary);
primary.on("click", function () {
if (primary.val() !== "") {
updateCat(primary.val());
optional.css("display", "block");
buttonField.on("click", function (e) {
e.preventDefault();
addField();
});
}
else {
buttonField.css("display", "none");
}
})
});
And I'm having a hard time reloading every select, because the empty function works but I lose the previous selected option. I could save it, then reload it etc, but I'm not sure if that's the right way.
Anyone got any idea how I would do something like that ?
Aucun commentaire:
Enregistrer un commentaire