how to access multiple select array data in javascript - javascript

I have a multiple select box and I want to access the selected data in javascript.
Here is the code:
<form onsubmit="return false;" id="multisel">
<select name="a[]" id="a" multiple style="width:350px;" tabindex="4">
<option value="Pedro">1</option>
<option value="Alexis">2</option>
<option value="Messi">3</option>
<option value="Villa">4</option>
<option value="Andres">5</option>
<option value="Sergio">6</option>
<option value="Xavi">7</option>
</select>
<button id="btn1" onclick="ajaxmultiselect()" type="submit" class="btn btn-primary">Save changes</button>
<p id="status"></p>
</form>
Here is the code I have tried so far :
<script>
function ajaxmultiselect(){
var input = [];
input = document.getElementById("a").value;
var status = _("status");
if(input == ""){
status.innerHTML = "Fill out all of the form data";
}else {
status.innerHTML = input;
}
}
</script>
When I run the code it only gives the first value.
I tried to access the values in php and it works fine, it passes the value as an array in php. Why isn't it doing the same with javascript?
I also tried to run a loop for the length of the value but that calculates the length of the first selection only.
I want to display all the values that will be selected.
Any help will be appreciated.

You can do the following:
function getSelectedOptions(element) {
// validate element
if(!element || !element.options)
return []; //or null?
// return HTML5 implementation of selectedOptions instead.
if (element.selectedOptions)
return element.selectedOptions;
// you are here because your browser doesn't have the HTML5 selectedOptions
var opts = element.options;
var selectedOptions = [];
for(var i = 0; i < opts.length; i++) {
if(opts[i].selected) {
selectedOptions.push(opts[i]);
}
}
return selectedOptions;
}
and then change your ajaxmultiselect() so you call it like this:
input = getSelectedOptions(document.getElementById("a"));
You will have to iterate for the values tho.

If you are wanting to get multiple selected items you could try something like the following:
function GetSelectedItems() {
var select = document.forms[0].a;
var selectedList = [];
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
selectedList.push(select.options[i].value);
}
}
alert(Array.join(selectedList, ","));
}

For a given <select> element, all of the selected options are in the selectedOptions property. The selectedIndex property has the index of the first selected option, or -1 if there is no selection. Each of the options are the DOM object for that element, so their value is in the value property. So:
function ajaxmultiselect(){
var input = [];
var select = document.forms[0].a;
var status = _("status");
var options = select.selectedOptions;
if(select.selectedIndex == -1){
// no selection
status.innerHTML = "Fill out all of the form data";
}else {
for (var i = 0; i < options.length)
input.push(options[i].value);
status.innerHTML = input.join(", ");
}
}
From there you should be able to derive whatever you want.

document.getElementById('a').options //All Options
This will give you an array of options that you can iterate through.

Related

Alter an existing script that works

I do not want to use JQuery. Here is a simple piece of javascript that works that allows you to search a dropdown menu list:
<HTML><HEAD><SCRIPT type="text/javascript">
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('realitems').options;
for(var i=0;i<output.length;i++) {
if(output[i].value.indexOf(input)==0){
output[i].selected=true;
}
if(document.getElementById('realtxt').value==''){
output[0].selected=true;
}
}
}
</SCRIPT></HEAD><BODY>
<FORM>
Search <input type="text" id="realtxt" onkeyup="searchSel()">
<SELECT id="realitems">
<OPTION value="">Select...
<OPTION value="afghanistan">Afghanistan
<OPTION value="albania">Albania
<OPTION value="algeria">Algeria
<OPTION value="andorra">Andorra
<OPTION value="angola">Angola
</SELECT>
</FORM></BODY></HTML>
The problem is that in order for it to work, the value of each option has to have the text. I tried changing the "value" fields in the javascript code to "name" so that it would search the name only, but no go. My option fields have numbers, and I cannot easily convert them to names. Is there a way to tweak this javascript to work with names or better yet search within the option tags?
You will need to change two things in the line
if(output[i].value.indexOf(input)==0){
use the .text property instead of .value at your <option> elements.
make it lowercase to match the lowercased input. With lowercase value attributes and numbers you did not have this problem.
This script would be the result:
function searchSel() {
var input = document.getElementById('realtxt').value.toLowerCase(),
len = input.length,
output = document.getElementById('realitems').options;
for(var i=0; i<output.length; i++)
if (output[i].text.toLowerCase().slice(0, len) == input)
output[i].selected = true;
if (input == '')
output[0].selected = true;
}
I also have used an improved startswith check.
This line:
var input=document.getElementById('realtxt').value.toLowerCase();
makes input a string.
<OPTION value=1>text
value is an integer.String will never == integer.
Change
if(output[i].value.indexOf(input)==0) to
to
if((output[i].value.indexOf(input)==0) || (output[i].value.indexOf(parseInt(input)))
use this code, i have replaced "value" with "innerHTML"
function searchSel() {
var input = document.getElementById('realtxt').value.toLowerCase();
var output = document.getElementById('realitems').options;
for (var i = 0; i < output.length; i++) {
if (output[i].innerHTML.indexOf(input) == 0) {
output[i].selected = true;
}
if (document.getElementById('realtxt').value == '') {
output[0].selected = true;
}
}
}

How to change options of a select using JavaScript

I have an HTML page in which I have 2 selects.
<select id="field" name="field" onchange="checkValidOption();">
<option />
<option value="Plugin ID">Plugin ID</option>
<option value="Name">Name</option>
</select>
<select id="operator" name="operator" onchange="checkValidOption();">
<option />
<option value="EQUALS">EQUALS</option>
<option value="CONTAINS">CONTAINS</option>
<option value="NOT CONTAINS">NOT CONTAINS</option>
<option value="REGEX">REGEX</option>
</select>
What I'd like to happen is that checkValidOption() could make it so that if "Plugin ID" is selected in field that the only option is EQUALS (and it's selected) and otherwise all the other options are available. Any idea on how to approach this?
I tried changing the innerHTML of the operator select in JS:
document.getElementById("operator").innerHTML =
"<option value='EQUALS'>EQUALS</option>";
However this results in an empty select (this would also include manually setting the many options for going back to having all the ones listed above).
I can't think of another solution, any help would be greatly appreciated.
Try this:
Demo here
var field = document.getElementById('field');
var operator = document.getElementById('operator');
field.onchange = function () { fieldcheck(); }
operator.onchange = function () { fieldcheck(); }
fieldcheck();
function fieldcheck() {
if (field.value == 'Plugin ID') {
for (i = 0; i < operator.options.length; ++i) {
if (operator.options[i].value != 'EQUALS') {
operator.options[i].disabled = true;
}
};
operator.value = 'EQUALS';
} else {
for (i = 0; i < operator.options.length; ++i) {
operator.options[i].disabled = false;
};
}
}
To manipulate options when Plugin ID was selected:
function checkValidOption(){
var x=document.getElementById("field");
var y=document.getElementById("operator");
if (x.options[1].selected === true){
document.getElementById("operator").options[1].selected = true;
for(var i=0; i<y.length; i++){
if (i !== 1){
//disabling the other options
document.getElementById("operator").options[i].disabled = true;
}
}
}
else{
for(var i=0; i<y.length; i++){
//enabling the other options
document.getElementById("operator").options[i].disabled = false;
}
}
}
Here's a link to fiddle
A select field doesn't use the innerHTML method, you need to use value.
document.getElementById("operator").value = "...";
heres a jquery solution.
every time the first select changes, it produces new options from an array for the 2nd select. issue here is i had to change the option values of the first select to 0 and 1 to select which value in the array, you can manipulate those later if you are storing this info somewhere
http://jsfiddle.net/2TZJh/
$(document).ready(function() {
$("#field").change(function() {
var val = $(this).val();
$("#operator").html(options[val]);
});
var options = [
'<option value="EQUALS">EQUALS</option>',
'<option></option><option value="EQUALS">EQUALS</option><option value="CONTAINS">CONTAINS</option> <option value="NOT CONTAINS">NOT CONTAINS</option> <option value="REGEX">REGEX</option>'
];
});

How to get focus for selected values when multiselect combo is used

I'm using a multiselect combobox, i select few values from the combobox and save the selected values to db. when i reopen the page, i need the focus to be placed on the values which was selected and saved.
function getSelectedValues() {
var from = document.getElementById("309127");
var to;
var v = from.options.length;
var selectedValues = "";
for (var i = 0; i < v; i++) {
if (from.options[i] && from.options[i].selected) {
var CVal = from.options[i].value;
var CText = from.options[i].text;
if (selectedValues == "") {
selectedValues = CVal;
}
else {
selectedValues = selectedValues + "~" + CVal;
}
}
}
return selectedValues;
}
this is the javascript function i used to save the selected values in db.
can anybody help me out on how to get the focus back on selected items ?
thank you
To set the focus with javascript you can use
document.getElementById("309127").focus();
For your question I'm assuming you send the values to a PHP page or something similar to update the database. If so your problem will be getting the selected values when you return to your page. Two suggestions:
Use ajax to update the database so you dont need to exit the page,
Pass the selected values back to your page through GET or similar and set the focus on page load.
EDIT: -------------
For example if you pass the values through GET like (www.example.com?param1=three)
You can use javascript to select that value on load:
<html>
<body onload="load()">
<select id="example">
<option value="one"> one </option>
<option value="two"> two </option>
<option value="three"> three </option>
</select>
</body>
<script>
function load(){
var param1 = getParameterByName("param1");
var selected = document.getElementById('example');
var opts = selected.options.length;
for (var i=0; i<opts; i++){
if (selected.options[i].value == param1){
selected.options[i].selected = true;
break;
}
}
}
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
</html>
try var from = document.getElementById("309127");from.focus();

Updating Selectbox options

I have 2 Selectbox
Countrynames
Airports
And as I select a countryname in first selectbox an Ajax request will be sent and it returns a list of Airposts as options like
"
<option value='1'>abc
<option value='3'>lmn
<option value='2'>xyz
"
now i have to replace only the options of select tag.
i am trying to do something like
var country_select = document.getElementById("country_select");
country_select.options.length = 0;
country_select.options = response.responseText
but this assignment is not working how may i get it done!
Try
var country_select = document.getElementById("country_select");
country_select.innerHTML = response.responseText;
This is a little bit more tricky, you won't be able to do it using innerHTML or anything like that.
You will have to change the way your ajax is returning airport names. Instead of <option>abc</option><option>xyz</option> return a string of names seperated by for example || : abc||def||xyz . then explode the string into an array in JS, create an option elements from every element in array, and add it to dropdown. check that:
<html>
<head>
<script>
var ajaxResponse = "abs||def||xyz||test||blah";
function updateOptions( optionsString )
{
var options = optionsString.split("||");
for( var i=0; i< options.length; i++ )
{
AddItem( options[i], options[i] );
}
}
function AddItem(Text,Value)
{
var opt = document.createElement("option");
opt.text = Text;
opt.value = Value;
document.getElementById("mydropdown").options.add(opt);
}
function removeOptions()
{
document.getElementById('mydropdown').length = 0;
}
</script>
</head>
<body>
<input type="button" onclick="updateOptions(ajaxResponse)" value="update"></input>
<input type="button" onclick="removeOptions()" value="remove"></input>
<select id="mydropdown">
</select>
</body>
</html>

How to set selectedIndex of select element using display text?

How to set selectedIndex of select element using display text as reference?
Example:
<input id="AnimalToFind" type="text" />
<select id="Animals">
<option value="0">Chicken</option>
<option value="1">Crocodile</option>
<option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />
<script type="text/javascript">
function SelectAnimal()
{
//Set selected option of Animals based on AnimalToFind value...
}
</script>
Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...
Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
<script type="text/javascript">
function SelectAnimal(){
//Set selected option of Animals based on AnimalToFind value...
var animalTofind = document.getElementById('AnimalToFind');
var selection = document.getElementById('Animals');
// select element
for(var i=0;i<selection.options.length;i++){
if (selection.options[i].innerHTML == animalTofind.value) {
selection.selectedIndex = i;
break;
}
}
}
</script>
setting the selectedIndex property of the select tag will choose the correct item. it is a good idea of instead of comparing the two values (options innerHTML && animal value) you can use the indexOf() method or regular expression to select the correct option despite casing or presense of spaces
selection.options[i].innerHTML.indexOf(animalTofind.value) != -1;
or using .match(/regular expression/)
If you want this without loops or jquery you could use the following
This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for
// for the term...if there is more than one then you will
// have to loop through the returned object
var selectAnimal = function() {
var animals = document.getElementById('animal');
if (animals) {
var x = animals.querySelectorAll('option[value="frog"]');
if (x.length === 1) {
console.log(x[0].index);
animals.selectedIndex = x[0].index;
}
}
}
<html>
<head>
<title>Test without loop or jquery</title>
</head>
<body>
<label>Animal to select
<select id='animal'>
<option value='nothing'></option>
<option value='dog'>dog</option>
<option value='cat'>cat</option>
<option value='mouse'>mouse</option>
<option value='rat'>rat</option>
<option value='frog'>frog</option>
<option value='horse'>horse</option>
</select>
</label>
<button onclick="selectAnimal()">Click to select animal</button>
</body>
</html>
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]');
in the index object you can now do the following:
x[0].index
Try this:
function SelectAnimal()
{
var animals = document.getElementById('Animals');
var animalsToFind = document.getElementById('AnimalToFind');
// get the options length
var len = animals.options.length;
for(i = 0; i < len; i++)
{
// check the current option's text if it's the same with the input box
if (animals.options[i].innerHTML == animalsToFind.value)
{
animals.selectedIndex = i;
break;
}
}
}
You can set the index by this code :
sel.selectedIndex = 0;
but remember a caution in this practice, You would not be able to call the server side onclick method if you select the previous value selected in the drop down..
Add name attribute to your option:
<option value="0" name="Chicken">Chicken</option>
With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.
You can use the HTMLOptionsCollection.namedItem()
That means that you have to define your select options to have a name attribute and have the value of the displayed text.
e.g
California

Categories