get list of selected items from select box in javascript - javascript

i am using a multi select box in javascript as given here:
i want to get the list of selected items in the multi select text box (the left list)
what can i do to achieve that?
my select box is as follows:
<select id="userList" class="multiselect" multiple="multiple" name="users[]" style="width: 75px;">
//List
</select>
i guess users[] stores the selected users at a point in time. but i can't figure out how to retrieve that variable.

Doing this will work:
$('[name="user[]"]').val()
PS: You need to have jQuery included in your webpage.
from the demo at http://www.quasipartikel.at/multiselect/, doing $('[name="countries[]"]').val() will give sample output:
["ARM", "AUS", "AUT"]

Get a list of values with jQuery:
var values = $select.find('option:checked').map(function() {
return this.value || this.text;
});
// or $select.val() of course, like lemarc says
// => ['ABC', 'DEF']
var prefix = encodeURIComponent($select.attr('name')) + '=';
var httpQuery = values.length ? prefix + values.map(function() {
return encodeURIComponent(this);
}).join('&' + prefix);
// => users[]=ABC&users[]=DEF
I didn't test it.

This will return array of selected values
$('#userList').val();
DEMO

You can directly target $(".multiselect") Object, by doing this:
$("input[type='submit']").click(function(e){
e.preventDefault();
_selValue = $(".multiselect").val(); //You will have variable of selected values
for(var i=0;i<_selValue.length;i++){
alert(_selValue[i]);
//You can iterate it individually in loop
}
});

Related

Set value on select options to select JSON data

I'm creating a select based on the JSON I got with an API. Based on that select, when I choose another option I want some data to change (text and image src).
I got the select with the options done. Each option is a name and I done that with forEach. My problem is setting the value so I can use it to change the other data. In my mind the easiest solution would be setting the value to the objects index so when I choose the first option I get 0 and can get the first JSON object. I'm not sure if this is the best way anyway.
This is my code reduced to only the forEach:
<select name="select" id="selector"> </select>
data_json.show.forEach((element) => {
document.getElementById('selector').innerHTML +=
`<option value="">${element.name}</option>`;
});
(the value is what I want to be the same as the index of each json data)
My idea of what I want to get:
<select name="select" id="selector">
<option value="0">Name_01</option>
<option value="1">Name_02</option>
<option value="2">Name_03</option>
</select>
So I can use the value like this:
let titulos = document.getElementById("titulos");
selectVal.onchange = function() {
let actualVal = selectVal.options[selectVal.selectedIndex].value;
titulos.innerHTML = "Títulos:" + " " + data_json.show[actualVal].image;;
};
<p id="titulos">Títulos:</p>
Hope it makes sense
You're setting them all to an empty value. You can use the array index to give them each a different value.
data_json.show.forEach((element, index) => {
document.getElementById('selector').innerHTML +=
`<option value="${index+1}">${element.name}</option>`;
});
BTW, you can simplify selectVal.options[selectVal.selectedIndex].value to just selectVal.value.

Angularjs select with count of filtred elements

I want to create select, which show count of elements in filter. Seems like that
Here is PlunkR with code, that i have wrote. It's great make his job, but i cannot add count of active/deactive elements in select. How can I do this?
Thank's
You can format the values before binding with the select options.
<select ng-options="i as format(i) for i in statusList" ng-model="statusFilter">
</select>
The format function is,
$scope.format = function(val) {
return val.status + ' ' + $scope.objs.filter(function(state) {
return state.status === val.value;
}).length;
}
Where the $scope.objs is the array of values which has active/inactive items.
Here is the working plunkr

unable to push selected values of dropdown in a javascript array (meteor js)

I have the following HTML code:
<select id="select_opt" class="form-control">
{{# each manageprofile_data}}
<option>{{Usergroup}}</option>
{{/each}}
</select>
and its corresponding JS event helper in meteorjs as:
'change #select_opt': function(event){
var select_data = [];
var val = $('#select_opt option:selected').val();
select_data.push(val);
console.log(select_data);
}
I want to push each selected option in the select_data array but it is only inserting a single element all the times and not saving all the elements.
on clicking each select option the value of the selected option must be saved in the array like ["ROOT", "ADMINISTRATOR", "ROOT"...]
but currently I am getting: ["ROOT"], ["ADMINISTRATION"] on clicking each option.
Just put your array outside of the function, like this:
var select_data = [];
'change #select_opt': function(event){
var val = $('#select_opt option:selected').val();
select_data.push(val);
console.log(select_data);
}
It seems that you are using backbone.js. You only have to make your select_data global. Inside your view add below line
select_data : [],

Automaticly setting default texts in select dropdown

I have a very simple select dropdown with urls that direct users to respective pages
<select>
<option value="url1">title1 </option>
<option value="url2">title2 </option>
<option value="url3">title3 </option>
.........
</select>
I will have this drop down in all these (url1, url2, url3...) serving for navigation. Would it be possible to set the default text in the selection box based on my urls? Say if I am currently on url2, my default text in the selection box will be title2. I know manually you can just use
<option selected="selected" value="url2">title2</option>
But is there a way I can use javascript to do because I have hundreds of pages? All the urls and titles are stored in an array that I can retrieve.
Thanks for your help!
Assuming you want to match the url in the window location (such as http://www.example.com/some/page.html) with the URL to the page found in your dropdown:
var dropdown = document.getElementById( 'dropdown' );
for ( var i = 0; i < dropdown.childElementCount; ++i ) {
if ( dropdown.children[i].value === document.location.href) {
dropdown.selectedIndex = i;
break;
}
}
Where 'dropdown' contains the ID of your <select> element. Jsfiddle: http://jsfiddle.net/RhZy6/
You should be able to use this:
var path = decodeURIComponent(window.location.pathname.replace(/\/$/, ""));
$("option").each(function () {
var url = $(this).val();
if (path.substring(0, url.length) === url) {
$(this).prop('selected', true);
}
});
Path is the end of the URL. The next block of code loops through the option elements and looks to see if the option value matches the path, and if it does, sets the selected property to true.
You can get the current URL using document.URL and on document ready you can use ,
$("#selectId option[value=" + document.URL + "]").prop('selected', true);
However document.URL contains full path , so you need to truncate the unnecessary part like http:// https:/ , if it is not present in value of select.
And , here is the working fiddle
P.S The Fiddle will work second time only. It is shwoing diffrent URL on first time. Gotta be a JSFiddle personal thing.
Say you have
<form name="MyForm">
<select name="SelectBox1">
<option>One
<option>Two
<option>Three
</select>
.. etc .. rest of form/page ..
then in your javascript code ..
var el=document.forms.MyForm.SelectBox1;
el.selectedIndex=2; // sets option to "Three" in Select box, because first option is number 0, second =1, third = 2 etc
Or to set it to a value use a function like this .. pass in the Select field name and the value it should be
function setSelect(sFieldName, sValue) {
var el=document.getElementsByName(sFieldName)[0] // returns array of all elements with that name so use [0] to get 1st one
for (var i=0;i<el.options.length;
if (el.options[i].value == sValue) { // if they match...
el.selectedIndex=i; // then this should be the default
}
}
call it usiong something like
setSelect("SelectBox1","http://ectetc")

jquery, get value of different select list

I have a lot of select list (hundreds) like this (they have all the same name and id (I think my problem comes from here... but I can't change it):
<select name="custom_element_grid_class" id="custom_element_grid_class" class="select-size">
<option value="normal">normal</option>
<option value="square">square</option>
<option value="wide">wide</option>
<option value="tall">tall</option>
</select>
I want to get value of each list when an user change the value. I made this script but it only works on my fist select list...
jQuery("#custom_element_grid_class").change(function(){
var element = jQuery(this);
var selected = element.find('option:selected');
var size = selected.val();
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class',sclass);
});
How can I make it works for all my select form?
EDIT: each select list comes from an ajx call, that's the reason I've got the same ID, but only in the futur DOM.
You cannot have double ID's.
So my suggestion in calling a function by inline onchange in the select.
For example:
<select name="custom_element_grid_class" id="custom_element_grid_class" onchange="func(this)" class="select-size">
And then your function:
function func(el){
var element = el;
var size = element.value;
var sclass = size + " element isotope-item";
jQuery(element).closest('.element').attr('class', sclass);
};
Demo here
I would suggest adding a first option with no value, so that, as you say "when an user change the value" you can read in case he took the first value.
If you can help it avoid duplicate IDs in exchange for classes. If this isn't an option use an attribute selector. Modifying the above code slightly.
Document Ready
$(function()
{
$('[name=custom_element_grid_class]').change(function(){
var $element = $(this);
var size = $element.val();
var sclass = size + " element isotope-item";
$element.closest('.element').attr('class',sclass);
});
});
Fiddle

Categories

Resources