The select element is not bound as expected.
html:
<select ng-model="SelectedPage"
ng-change="ShowPageResult();" ng-options="o for o in PageNumbers">
</select>
ctrl.js:
function BindPageNumbers() {
$scope.PageNumbers = [];
for (var i = 1; i <= 2) ; i++) {
$scope.PageNumbers.push(i);
}
}
output:
<option value="0"label="1">1</option>
<option value="1" label="2">2</option>
if i put $scope.PageNumbers.push(i.toString());, then the output is
<option value="?"label=""></option>
<option value="0" label="1">1</option>
<option value="1" label="2">2</option>
expected:
<option value="1">1</option>
<option value="2">2</option>
what should be done to get the desired o/p : http://jsfiddle.net/s222904f/
In your controller:
$scope.PageNumbers = [];
for (var i = 1; i <= 2 ; i++) {
$scope.PageNumbers.push({ id: i, value: i });
}
In your view:
<select ng-model="SelectedPage"
ng-options="o.id for o in PageNumbers track by o.value"></select>
Check it: http://jsfiddle.net/khwuv4Lj/
Per the answer here, the empty option exists because the
ng-model="SelectedPage"
line binds it to an empty string. You can avoid this by setting the default value if the select in the scope.
Edit: Plnkr was updated to fix the OP's comment.
Related
i'm trying to figure out how can i make dynamic selection of values in few dropdown lists using Vanilla JS. I have 3 dropdown lists with same values. Each of them should have different value selected at the same time (duplicates not allowed). So once user changes another value in one list, value of another list should be updated accordingly. Basically, i need to swap their numbers in such case. But i can't complete the task as I'm quite new to JS and overall in programming. I tried following:
// defining initial values
var startPoint = document.querySelectorAll("select");
// function to recalculate value of each list on change
function calculateNewValues() {
var changes = new Array();
// getting updated values from lists as an array
var updatedValues = document.querySelectorAll("select");
// looping through array
for (let i = 0; i < updatedValues.length; i++) {
// if in updated array value of current index isn't equal to value
// of index in initial array
if (updatedValues[i].value != startPoint[i].value) {
// creating variable changes for tracking
changes[i] = updatedValues[i].value;
}
// if var changes has been defined (i.e. value of any list was updated)
if (changes.length > 0) {
// finding index of initial array with same value
var key = startPoint.findIndex(changes[i]);
// setting value of found index to previously stored value in updated list
updatedValues[key].value = startPoint[i].value;
}
}
updatedValues.forEach(element => {
console.log(element.value);
});
}
// event listeners for change of every dropdown list
const lists = document.querySelectorAll("select");
for (k = 0; k < lists.length; k++) {
lists[k].addEventListener("change", calculateNewValues, false);
}
<p>
<select name="list1" id="list1">
<option value="1" id="list1option1" selected>1</option>
<option value="2" id="list1option2">2</option>
<option value="3" id="list1option3">3</option>
</select>
</p>
<p>
<select name="list2" id="list2">
<option value="1" id="list2option1">1</option>
<option value="2" id="list2option2" selected>2</option>
<option value="3" id="list2option3">3</option>
</select>
</p>
<p>
<select name="list3" id="list3">
<option value="1" id="list3option1">1</option>
<option value="2" id="list3option2">2</option>
<option value="3" id="list3option3" selected>3</option>
</select>
</p>
i am probably doing some mistake when it comes to if (changes.length > 0) {
but i can't understand how i can make this part better.
Thanks a lot in advance.
You have assigned startPoint to querySelectorAll. Which will hold exact same objects whenever you write same querySelectorAll. So in your case startPoint and updatedValues will always same.
I have definen startPoint as an array of values and set its values in setStartingPointValues().
Added target as current list which is being updated.
Updated if (target.id == updatedValues[i].id && updatedValues[i].value != startPoint[i]) and retrieved target's old value.
var key = startPoint.findIndex(x => x == target.value); will find select with value similar to new value. If we found key != -1, then update that select with oldValue.
Call setStartingPointValues() at end of change event.
// defining initial values
var startPoint = [];
// store values for all select.
function setStartingPointValues() {
startPoint = [];
document.querySelectorAll("select").forEach(x => startPoint.push(x.value));
}
setStartingPointValues();
// function to recalculate value of each list on change
function calculateNewValues() {
let target = this;
let oldValue = 0;
// getting updated values from lists as an array
var updatedValues = document.querySelectorAll("select");
// looping through array
for (let i = 0; i < updatedValues.length; i++) {
// if in updated array value of current index isn't equal to value
// of index in initial array
if (target.id == updatedValues[i].id && updatedValues[i].value != startPoint[i]) {
// creating variable changes for tracking
// changes[i] = updatedValues[i].value;
oldValue = startPoint[i];
}
// if var changes has been defined (i.e. value of any list was updated)
// finding index of initial array with same value
var key = startPoint.findIndex(x => x == target.value);
// setting value of found index to previously stored value in updated list
if (key !== -1)
updatedValues[key].value = oldValue;
}
setStartingPointValues();
}
// event listeners for change of every dropdown list
const lists = document.querySelectorAll("select");
for (k = 0; k < lists.length; k++) {
lists[k].addEventListener("change", calculateNewValues, false);
}
<p>
<select name="list1" id="list1">
<option value="1" id="list1option1" selected>1</option>
<option value="2" id="list1option2">2</option>
<option value="3" id="list1option3">3</option>
</select>
</p>
<p>
<select name="list2" id="list2">
<option value="1" id="list2option1">1</option>
<option value="2" id="list2option2" selected>2</option>
<option value="3" id="list2option3">3</option>
</select>
</p>
<p>
<select name="list3" id="list3">
<option value="1" id="list3option1">1</option>
<option value="2" id="list3option2">2</option>
<option value="3" id="list3option3" selected>3</option>
</select>
</p>
Define good structure (store selected value somewhere) and rest should be easy
const lists = Array.from(document.querySelectorAll("#list")).map(element => {
const options = Array.from(element.children);
const selected = options.findIndex(child => child.selected) + 1;
return {
element,
options,
selected
}
});
const calculateNewValues = ({target}) => {
const value = Number(target.value);
const currentList = lists.find(pr => pr.element === target);
const list = lists.find(pr => pr.selected === value)
const oldValue = currentList.selected;
currentList.selected = value;
list.options[value - 1].selected = false;
list.options[oldValue - 1].selected = true;
list.selected = oldValue;
}
for(let {element} of lists) {
element.addEventListener("change", calculateNewValues, false);
}
<p>
<select name="list1" id="list">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</p>
<p>
<select name="list2" id="list">
<option value="1">1</option>
<option value="2" selected>2</option>
<option value="3">3</option>
</select>
</p>
<p>
<select name="list3" id="list">
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected>3</option>
</select>
</p>
I have a select dropdown field that is being created dynamically from a database . Due to the way this is being created it results in the dropdown having duplicate items and values.
<select id="locationList">
<option value="1">Andover</option>
<option value="2">Bishops waltham</option>
<option value="1">Andover</option>
<option value="3">Boscombe</option>
<option value="4">Bournemouth</option>
<option value="2">Bishops waltham</option>
<option value="4">Bournemouth</option>
</select>
Does anyone know if there is a way to use some code on the page which checks the dropdown for duplicates and removes duplicates from the menu only by Javascript No Jquery?
Thanks in advance,
Abhinav
Javascript has removeChild option, you can use it to remove duplicate value:
var fruits = document.getElementById("locationList");
[].slice.call(fruits.options)
.map(function(a){
if(this[a.value]){
fruits.removeChild(a);
} else {
this[a.value]=1;
}
},{});
<select id="locationList">
<option value="1">Andover</option>
<option value="2">Bishops waltham</option>
<option value="1">Andover</option>
<option value="3">Boscombe</option>
<option value="4">Bournemouth</option>
<option value="2">Bishops waltham</option>
<option value="4">Bournemouth</option>
</select>
Another option is to use the set as suggested here: alternatives or another alternative.
[ ...new Set([ ...<arg1>, ...<arg2> ]) ] for e.g.
var y = [ ...new Set([ ...[1, 2, 3, 4, 5], ...[3, 4, 5] ]) ]
// expected output: [ 1, 2, 3, 4, 5 ]
Use the output to bind to the dropdown list.
Do it with dual for loop using pure js
Simple and easy way with select remove method
function clearList() {
var x = document.getElementById("locationList");
//count the lenth of select optons
var listLength = x.length;
for (var i = 0; i < listLength; i++) {
for (var j = 0; j < listLength; j++) {
//i != j This prevents the actual index from being deleted
//x.options[i].value == x.options[j].value => it finds the duplicate index.
if (x.options[i].value == x.options[j].value && i != j) {
//Remove duplicate option element
x.remove(j);
//Refresh the list Length
listLength--;
}
}
}
}
<select id="locationList">
<option value="1">Andover</option>
<option value="2">Bishops waltham</option>
<option value="1">Andover</option>
<option value="3">Boscombe</option>
<option value="4">Bournemouth</option>
<option value="2">Bishops waltham</option>
<option value="4">Bournemouth</option>
</select>
<p>Click to remove duplicates</p>
<button onclick="clearList()">Remove</button>
I would like to put multiple values in tag within select, so I could adress precisely one or few items.
Example:
<select id="select1">
<option value="pf, nn">NN</option>
<option value="pf, x2, jj">JJ</option>
<option value="pf, uu">UU</option>
<option value="pf, x2, oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>
In my js I got that one function that depend on one value that is common for many items:
if (document.getElementById("select1").value = "pf";) {
// do something;
}
if (document.getElementById("select1").value = "x2";) {
// do some-other-thing;
}
But I don't want to use (cos' and with more options gonna get messy)
var sel1 = document.getElementById("select1").value
if (sel1="nn" || sel1="jj" || sel1="uu" || sel1="oo") {
// do something;
}
if (sel1="jj" || sel1="oo") {
// do some-other-thing;
}
Neverthelesst I need to be able to set item by precise one value
if (document.somethingelse = true) {
document.getElementById("select1").value = "oo";)
}
Is there a nice way to achieve this? Maybe use some other "value-like" attribute of option (but which?)?
Only JS.
I think you can do what you want with selectedOpt.value.split(",").includes("sth") code:
$(document).ready(function(e){
selectedChange($("#select1")[0])
});
function selectedChange(val) {
var selectedOpt = val.options[val.selectedIndex];
var status1 = selectedOpt.value.split(",").includes("x2");
var status2 = selectedOpt.value.split(",").includes("pf");
console.log(status1);
console.log(status2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1" onchange="selectedChange(this)">
<option value="pf,nn">NN</option>
<option value="pf,x2,jj">JJ</option>
<option value="pf,uu">UU</option>
<option value="pf,x2,oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>
I have a dynamically generated <select> field with <option>.
<select>
<option value=""></option>
<option value=""></option>
<option value=""> False</option>
<option value=""> True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
I would like to remove the duplicate occurrences and combinations. The final <select> field with <option> should look like :
<select>
<option value=""></option>
<option value="">False</option>
<option value="">True</option>
</select>
Here is how my fiddle looks like. Been trying to solve this for hours.
var values = [];
$("select").children().each(function() {
if (values.length > 0) {
var notExists = false;
for (var x = 0; x < values.length; x++) {
var _text = this.text.replace(/\s/g, "");
var value = values[x].replace(/\s/g, "");
if (values[x].length > _text.length) {
//console.log('>>+', value, ' || ', _text, value.indexOf(_text))
notExists = value.indexOf(_text) > -1 ? true : false;
} else {
//console.log('>>*', value, ' || ', _text, _text.indexOf(value))
notExists = _text.indexOf(value) > -1 ? true : false;
}
}
if (notExists) {
//this.remove();
values.push(this.text);
}
} else {
values.push(this.text);
}
});
Any help to solve this is appreciated.
You can use map() to return all options text and use split() on white-space. Then to remove duplicates you can use reduce() to return object. Then you can empty select and use Object.keys() to loop each property and append to select.
var opt = $("select option").map(function() {
return $(this).text().split(' ')
}).get();
opt = opt.reduce(function(o, e) {return o[e] = true, o}, {});
$('select').empty();
Object.keys(opt).forEach(function(key) {
$('select').append(' <option value="">'+key+'</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value=""></option>
<option value=""></option>
<option value="">False</option>
<option value="">True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
You can loop through each of this children text , then use substring to get the first text & put it in an array.
Once done empty the select element and append the newly created options
var _textHolder=[]; // NA empty array to hold unique text
var _options="";
$("select").children().each(function(item,value) {
var _textVal = $(this).text().trim(); // Remove white space
//get the first text content
var _getText = _textVal.substr(0, _textVal.indexOf(" "));
// if this text is not present in array then push it
if(_textHolder.indexOf(_getText) ==-1){
_textHolder.push(_getText)
}
});
// Create new options with items from _textHolder
_textHolder.forEach(function(item){
_options+='<option value="">'+item+'</option>'
})
// Empty current select element and append new options
$('select').empty().append(_options);
JSFIDDLE
I would do with pure JS ES6 style. This is producing a words array from the whitespace separated options element's innerText value regardless the words are in the front, middle or the end; and it will create a unique options list from that. Basically we are concatenating these arrays and getting it unified by utilizing the new Set object. The code is as follows;
var opts = document.querySelector("select").children,
list = Array.prototype.reduce.call(opts, function(s,c){
text = c.innerText.trim().split(" ");
return new Set([...s].concat(text)) // adding multiple elements to a set
},new Set());
list = [...list]; // turn set to array
for (var i = opts.length-1; i >= 0; i--){ //reverse iteration not to effect indices when an element is deleted
i in list ? opts[i].innerText = list[i]
: opts[i].parentNode.removeChild(opts[i]);
}
<select>
<option value=""></option>
<option value=""></option>
<option value=""> False</option>
<option value=""> True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
How is it possible to change the numbers in within the option tag with JS?
<select name="resunit">
<option value="res_0">R1 (18768194)</option>
<option value="res_1">R2 (44507354)</option>
<option value="res_2">R3 (15217874)</option>
<option value="unit_1">U1 (3047)</option>
<option value="unit_2">U2 (10)</option>
<option value="unit_3">U3 (60)</option>
</select>
e.g.
<option value="res_0">R1 (18768194)</option>
to
<option value="res_0">R1 (10)</option>
Not quite sure what you're asking, but have a look:
var select = document.getElementsByName("resunit")[0];
for (var i = 0; i < select.length; i++) {
if (select[i].value === "res_0") {
select[i].innerHTML = "R1 (10)";
} else if (select[i].value === "res_1") {
select[i].innerHTML = "R2 (12)";
}
}