Javascript array select option - javascript

I have a problem with my Javascript code, I have a select and I add the value of the selected option (for example Volvo) in an array but when the user change the selected option (for example Lamborghini). I want to delete the last selected option in the array and add the newest in that.
How Can I do it ?
For information, I have multiple select option and I call the function changeClass()
Thank you for your helps
My HTML code
<select class="form-control" id="car" onchange="changeClass(this)">
<option value="1">Volvo</option>
<option value="2">VW</option>
<option value="3">Lamborghini</option>
</select>
My Javascript code
<script>
var data = [];
function changeClass(select) {
data.push(select.value);
}
</script>

use this in common select function, it will get all selected value into one array
var data;
$("select").change(function () {
data = $("select").map(function () {
return this.value;
}).get();
console.log(data)
});
DEMO

You can simply empty the array by re-defining it to empty array:
function changeClass(select) {
data = [];
data.push(select.value);
}

Just use splice to replace the last element with the new one:
var arr = ["aaa", "bbb", "ccc"];
arr.splice(arr.length - 1, 1, "ddd");
console.log(arr);
logs:
["aaa", "bbb", "ddd"]

If the item was added just before the new item then you can do something like this:
<script>
var data = [];
function changeClass(select) {
data.pop();
data.push(select.value);
}
</script>
If you wish to remove the item which was not added just before then you'll have to use event onfocus, grab the previously selected value and delete it when onchange event is fired.

Related

Get selected index from select list

I have a select like this:
<select class="form-control" ng-change="filtro(selected)" ng-init="Catalogos[0]" ng-model="selected" ng-options="item.Nombre for item in Catalogos"></select>
I wan to get select index value, I try to use:
$scope.selected
But I get params from the database instead of the index of the selected list. How can I get that Index? Regards
I try as maddockst comment:
$scope.filtro = function (item) {
$scope.Catalogos.indexOf(item);
}
But when I use it I get other values instead of index
There is how I have now:
HTML
<select class="form-control" ng-change="filtro(selected)" ng-init="Catalogos[0]" ng-model="selected" ng-options="Catalogos as item.Nombre for item in Catalogos"></select>
JS
function editar() {
$scope.filtro = function (item) {
alert($scope.Catalogos.indexOf(item));
console.log(index);
}
($("#tabla_catalogos tr.selected").hasClass("selected"));
{
var table = $('#tabla_catalogos').DataTable();
var row = table.rows('.selected').data();
var id = table.cell(row[0], 1).data();
//Toma el id referente a la columna seleccionada
$state.go("root.detalleregistros", { codigo: row[0].Codigo, nombre: row[0].Nombre, catalogoid: row[0].ID, catalogoselected: $scope.filtro });
}
}
But I always get -1 into alert
Inside filtro, you could get the index of the selected item in the Catalogos array using the following code:
Change the filtro function to:
$scope.filtro = function(item) {
var index = $scope.Catalogos.indexOf(item);
}
SO in this scenario if you go into dev tools, I assume chrome and go to your console tab. Type $scope.selected, it will give you the object definition and from there you'll see your selected index value.
It will have to be something like $scope.selected[0].value

jquery - variable as parameter of function

I have a multiple select:
<select name="courier" class="selectpicker courierpicker" multiple>
<option value="value1">Value1</option>
<option value="value2">Value2</option>
...
</select>
I want to use selected options as parameters for filtering rows in my table. This code doesn't work for me (assume, just for this example, that there is always more than one selected option):
$(".selectpicker").change(function() {
var items = [];
$('.courierpicker option:selected').each(function(){
items.push($(this).val());
});
var $result = '["' + items.join('","') + '"]';
$('#data-table').bootstrapTable('filterBy', {
courierfilter: $result
});
});
When I trigger:
$('#data-table').bootstrapTable('filterBy', {
courierfilter: ["value1","value2"]
});
Everything works just fine.
I know it will be some stupid mistake of the beginner, but thanks in advance for every help.
The issue is because the courierfilter property expects an array, yet you're providing it a string which is formatted like an array. Also note that the array generation can be made simpler through the use of the map() method. Try this:
$(".selectpicker").change(function() {
var items = $('.courierpicker option:selected').map(function(){
return this.value;
}).get();
$('#data-table').bootstrapTable('filterBy', {
courierfilter: items
});
});
Just use {courierfilter: items}.

Javascript: Unique Option in Select

I Want to archive to have unique options in a select.
For example:
At first there is only one Select. But you can add infinitely Selects. All Selects use the same array to fill in the options.
The Array is for example [1,2].
If you know select "1" in the first Select, the second Select should only have "2" as an option.
Thanks
Example of how a filter could look like:
JavaScript
app.filter('notInArray', function() {
return function(inputArray, filterArray) {
if (inputArray) {
return inputArray.filter(function (item) {
return !filterArray || filterArray.indexOf(item) === -1;
});
}
return [];
}
});
Usage:
<select data-ng-model="mySelect" data-ng-options="item as item.Name for item in items | notInArray:mySelected">
<option value="">-- Choose option --</option>
</select>
And then maybe have a $watch on mySelect that adds it to mySelectedand sets mySelect to null. This way you only need one select. You should probably implement a way to remove options from the mySelected array also.
Example of this:
JavaScript
$scope.$watch("mySelect", function(){
if($scope.mySelect){
$scope.mySelected.push($scope.mySelect);
$scope.mySelect = null;
}
});
$scope.removeOption = function(option){
$scope.mySelected.splice($scope.mySelected.indexOf(option), 1);
}

Drop-down box with Json data

I am trying to use jquery to populate the dropdown box with the following JSON data
{
"Name":["A","B","C"],
"Movie":["X","Y","Z"]
}
And this the script what I have done so far
$("#firstbox").change(function(){
var $selection=$(this);
$.getJSON("data.json",function(data){
var i=$selection.val();
var arr=[];
switch(i){
case 'Name':
arr=data.Name.split(",");
break;
case 'Movie':
arr=data.Movie.split(",");
break;
}
});
});
My basic index.html is just like this
<select id="firstbox">
<option selected value="">---Select---</option>
<option value="Name">Name</option>
<option value="Movie">Movie</option>
</select>
<select id="secondbox" name="">
<option selected value="">---Generate---</option>
<script src="myjs.js"> </script>
</select>
The 'secondbox' drop-down should generate the value corresponding to the selections of 'firstbox' drop-down. The error I received is 'undefined split function'. Can anyone give me a hint ?
Thanks
split is a method of the String object, here you use it on the Array object.
You dont need to split as the Name and Movie keys are allready arrays in the JSON object.
$("#firstbox").on("change", function(e){
var sel=$(this).val();
$("#secondbox").empty();
$.getJSON("data.json",function(data){
var values=data[sel] || ['Error : key not found'];
$(values).each(function(index,element) {
$("<option />", {value: element, text:element}).appendTo("#secondbox");
});
});
});
Here is a working exemple : http://jsfiddle.net/cKBeE/
$("#firstbox").on("change", function(e){
writeOptions();
}
function getJSONData(firstboxval) {
//make ajax call to get data for second dropdown
//that corresponds to the value selected in firstbox
//then make function return the array of options
}
function writeOptions() {
var firstboxval = $("#firstbox").val();
var optionValues = getJSONData(firstboxval);
var dropDown = document.getElementById("secondbox");
for(var i=0; i<optionValues.length; i++) {
var key = i;
var value = optionValues[i];
dropDown.options[i] = new Option(value, key);
}
}

Search a dropdown

I have this HTML dropdown:
<form>
<input type="text" id="realtxt" onkeyup="searchSel()">
<select id="select" name="basic-combo" size="1">
<option value="2821">Something </option>
<option value="2825"> Something </option>
<option value="2842"> Something </option>
<option value="2843"> _Something </option>
<option value="15999"> _Something </option>
</select>
</form>
I need to search trough it using javascript.
This is what I have now:
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('basic-combo').options;
for(var i=0;i<output.length;i++) {
var outputvalue = output[i].value;
var output = outputvalue.replace(/^(\s| )+|(\s| )+$/g,"");
if(output.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
The code doesn't work, and it's probably not the best.
Can anyone show me how I can search trough the dropdown items and when i hit enter find the one i want, and if i hit enter again give me the next result, using plain javascript?
Here's the fixed code. It searches for the first occurrence only:
function searchSel() {
var input = document.getElementById('realtxt').value;
var list = document.getElementById('select');
var listItems = list.options;
if(input === '')
{
listItems[0].selected = true;
return;
}
for(var i=0;i<list.length;i++) {
var val = list[i].value.toLowerCase();
if(val.indexOf(input) == 0) {
list.selectedIndex = i;
return;
}
}
}
You should not check for empty text outside the for loop.
Also, this code will do partial match i.e. if you type 'A', it will select the option 'Artikkelarkiv' option.
Right of the bat, your code won't work as you're selecting the dropdown wrong:
document.getElementById("basic-combo")
is wrong, as the id is select, while "basic-combo" is the name attribute.
And another thing to note, is that you have two variable named output. Even though they're in different scopes, it might become confusing.
For stuff like this, I'd suggest you use a JavaScript library like jQuery (http://jquery.com) to make DOM interaction easier and cross-browser compatible.
Then, you can select and traverse all the elements from your select like this:
$("#select").each(function() {
var $this = $(this); // Just a shortcut
var value = $this.val(); // The value of the option element
var content = $this.html(); // The text content of the option element
// Process as you wish
});

Categories