Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add instance.getValue() and instance.setValue(newVal) #88

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 61 additions & 1 deletion src/js/nice-select2.js
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,9 @@ NiceSelect.prototype._onItemClicked = function(option, e) {
if (hasClass(optionEl, "selected")) {
removeClass(optionEl, "selected");
this.selectedOptions.splice(this.selectedOptions.indexOf(option), 1);
this.el.querySelector(`option[value="${optionEl.dataset.value}"]`).removeAttribute('selected');
var opt = this.el.querySelector(`option[value="${optionEl.dataset.value}"]`);
opt.removeAttribute('selected');
opt.selected = false;
}else{
addClass(optionEl, "selected");
this.selectedOptions.push(option);
Expand All @@ -407,6 +409,63 @@ NiceSelect.prototype._onItemClicked = function(option, e) {
}
};

NiceSelect.prototype.setValue = function(value){

var select = this.el,noSelected = true,currentValue;
if(select.multiple){
for(var i = 0; i < value.length; i++){
value[i] = String(value[i]);
}
}

for(var opt of select.options){
if(select.multiple){
if(value.indexOf(opt.value) > -1){ //-- expect Array like [1,2,3]
currentValue = opt.value;
}else{
currentValue = null;
}
}else{
currentValue = value;
}

if(opt.value == currentValue && !opt.disabled){
if(noSelected){
select.value = currentValue;
noSelected = false;
}
opt.setAttribute('selected',true);
opt.selected = true;
}else{
opt.removeAttribute('selected');
delete(opt.selected);
}
}
if(noSelected && !select.multiple){
select.options[0].setAttribute('selected',true);
select.options[0].selected = true;
select.value = select.options[0].value;
}

this.update();
}

NiceSelect.prototype.getValue = function(){
var select = this.el;
if(!select.multiple){
return select.value;
}

//-- multiple
var values = [];
for(var opt of select.options){
if(opt.selected){
values.push(opt.value);
}
}
return values;
}

NiceSelect.prototype.updateSelectValue = function() {
if (this.multiple) {
var select = this.el;
Expand All @@ -429,6 +488,7 @@ NiceSelect.prototype.resetSelectValue = function() {
var el = select.querySelector(`option[value="${item.data.value}"]`);
if (el){
el.removeAttribute("selected");
delete(el.selected);
}
});
} else if (this.selectedOptions.length > 0) {
Expand Down