Skip to content

Commit 9ac17cf

Browse files
authored
Merge pull request #1969 from mlarghydracept/changing-select-option
Changing Select Option
2 parents 3fff3f6 + 4a034e5 commit 9ac17cf

File tree

1 file changed

+33
-7
lines changed

1 file changed

+33
-7
lines changed

lib/addons/p5.dom.js

+33-7
Original file line numberDiff line numberDiff line change
@@ -574,13 +574,39 @@
574574
self = addElement(elt, this);
575575
}
576576
self.option = function(name, value) {
577-
var opt = document.createElement('option');
578-
opt.innerHTML = name;
579-
if (arguments.length > 1)
580-
opt.value = value;
581-
else
582-
opt.value = name;
583-
elt.appendChild(opt);
577+
var index;
578+
//see if there is already an option with this name
579+
for (var i = 0; i < this.elt.length; i++) {
580+
if(this.elt[i].innerHTML == name) {
581+
index = i;
582+
break;
583+
}
584+
}
585+
//if there is an option with this name we will modify it
586+
if(index !== undefined) {
587+
//if the user passed in false then delete that option
588+
if(value === false) {
589+
this.elt.remove(index);
590+
} else {
591+
//otherwise if the name and value are the same then change both
592+
if(this.elt[index].innerHTML == this.elt[index].value) {
593+
this.elt[index].innerHTML = this.elt[index].value = value;
594+
//otherwise just change the value
595+
} else {
596+
this.elt[index].value = value;
597+
}
598+
}
599+
}
600+
//if it doesn't exist make it
601+
else {
602+
var opt = document.createElement('option');
603+
opt.innerHTML = name;
604+
if (arguments.length > 1)
605+
opt.value = value;
606+
else
607+
opt.value = name;
608+
elt.appendChild(opt);
609+
}
584610
};
585611
self.selected = function(value) {
586612
var arr = [];

0 commit comments

Comments
 (0)