Get Specific arrays data using <select> element in JavaScript - javascript

Although there are already some questions related to this one but thing I could not found is " getting arrays data using <select> element".
For Example ...There are 3 arrays
<script>
function myCountry() {
var country_1 = ["city1", "city2", "city3"];
var country_2 = ["city2_1", "city2_2","city3_3"];
var country_3 = ["city3_1", "city3_2" ,"city3_3"];
}
</script>
Now using HTML <select> Element.
<select onchange="myCounty()">
<option>Country1</option>
<option>Country2</option>
<option>Country3</option>
</select>
<p id="demo"></p>
I want that if a specific country is selected (For Example 'Country1') then cities in array 1 (i.e. var country_1 = ["city1".....]) should be display in paragraph with id = demo (For Example)

You can simply use an array to grab some data that you want to get.
function myCountry(index) {
var country = [
["city1", "city2", "city3"],
["city2_1", "city2_2","city3_3"],
["city3_1", "city3_2" ,"city3_3"]
]
return country[index];
}
var p = document.querySelector('p');
var select = document.querySelector('select');
p.innerHTML = myCountry(0);
select.addEventListener('change', function(e){
p.innerHTML = myCountry(e.target.selectedIndex);
});
<select>
<option>Country1</option>
<option>Country2</option>
<option>Country3</option>
</select>
<p></p>

Does this help you?
We first create an id for the select element. The get the index of the element being selected, then I create an array of arrays and access the corresponding index's array, then finally print the output with a comma.
Please let me know if this fixes your issue!
var country_1 = ["city1", "city2", "city3"];
var country_2 = ["city2_1", "city2_2", "city3_3"];
var country_3 = ["city3_1", "city3_2", "city3_3"];
function myCountry() {
var elem = document.getElementById("country");
var options = [country_1, country_2, country_3];
var index = elem.options[elem.selectedIndex].index;
var output = "";
for( var k of options[index]){
output += k + ", ";
}
document.getElementById("demo").innerHTML = output;
}
document.getElementById("country").addEventListener("change", myCountry);
myCountry();
<select id="country">
<option>Country1</option>
<option>Country2</option>
<option>Country3</option>
</select>
<p id="demo"></p>

Related

How to generate multiple <select> elements with option tags?

I'm trying to append the defined select element to the document.
This answer, describes quite well about fixed arrays, but in my case I have a slice which is applied to the template by ExecuteTemplate method, so the value of <option> tags are defined by slice values.
Here is my code which does not work, as it should:
<html>
<input type="number" id="count">
<select id="select">
{{ range .Slice }}
<option value="{{ .Name }}">{{ .Name }}</option>
{{ end }}
</select>
<div class="test"></div>
<button onclick="generateSelects();">Test</button>
</html>
<script>
function generateSelects() {
var count = document.getElementById("count").value;
var i;
var select = document.getElementById("select");
var divClass = document.getElementsByClassName("test");
for (i = 0; i < Number(count); i++) {
divclass[0].appendChild(select);
)
}
</script>
What am I looking for is about generating select list based on the user's input. For example if the user enters 2, so two select menu going to appear on the screen.
How can I do this?
First of all make sure that generated selects all have different IDs, in your example they all have the same id which is "select".
Then instead of appending the "original" select element, try to clone it then add its clone to your div.
What I would do is :
function generateSelects() {
var count = document.getElementById("count").value;
var i;
var select = document.getElementById("select");
var divClass = document.getElementsByClassName("test");
for (i = 0; i < Number(count); i++) {
var clone = select.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
divclass[0].appendChild(clone);
}
}
Hope it helps!
To append multiple select elements, first you have create a select element. You can not directly get an elementById and append different element as child.
<script>
function generateSelects() {
var count = document.getElementById("count").value;
var i;
var divClass = document.getElementsByClassName("test");
for (i = 0; i < Number(count); i++) {
var option = document.createElement("OPTION");
option.setAttribute("value", "optionvalue");
var select = document.createElement("SELECT");
select.appendChild(option);
divclass[0].appendChild(select);
)
}
</script>

drop down list items taken from the java script

<select id="myList" onchange="favBrowser()">
<option> var x</option>
<option> var y</option>
</select>
<script>
var x="google"; var y="firefox";
</script>
my question is , how to take the option's values from javascript
i think he ment he want to fill the options by Script
this can be done by
<select id="myDropdown">
</select>
<script type="text/javascript">
function fillDropDown() {
var ddl = document.getElementById('myDropdown');
for (var i = 1; i < 50; i++) {
var myNewOption = new Option();
myNewOption.value = i;
myNewOption.text = "my " + i.toString() + " option...";
ddl.options.add(myNewOption);
}
}
fillDropDown();
</script>
Cheers.
You can get it by writing
function favBrowser(){
var sel = document.getElementById("myList");
var value =sel.options[sel.selectedIndex].value;
window.alert(value);
}
You need to supply more information about what it is you really want to do. If what you want is to take the selected value, then take a look at this question
Get selected value in dropdown list using JavaScript?

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();

Get value of multi-select - No jQuery

Every relevant "question that may already have [my] answer" uses jQuery, which I am not using.
So, is there any simple way to get the values of selected options in a <select multiple> tag, or do I have to loop through all the options to see which ones are selected and manually build an array?
Side-question: Which browsers don't support selectElement.value and instead require selectElement.options[selectElement.selectedIndex].value?
You can use select.selectedOptions. However, this returns an HTMLCollection, so you still have to clean it to get a string array. http://jsfiddle.net/9gd9v/
<select multiple>
<option value="foo" selected>foo</option>
<option value="bar">bar</option>
<option value="baz" selected>baz</option>
</select>
and:
var select = document.querySelector("select");
var values = [].map.call(select.selectedOptions, function(option) {
return option.value;
});
If you end up wanting to loop through and grab the selected values you could use something like this:
function loopSelected()
{
var txtSelectedValuesObj = "";
var selectedArray = new Array();
var selObj = document.getElementById('selectID');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj = selectedArray;
alert(txtSelectedValuesObj);
}
You can view an example HERE, adapted from this example.
.
You could also simply track the selected options via the onchange event in real-time and collect them whenever you want them. I admit it's still looping, but at least you're not doing it every time you need to retrieve the selected options, and it has the added bonus of being simple (come retrieval time, anyway...). Working fiddle: http://jsfiddle.net/cyg9Z/
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trackSelected = function (e) {
var selector = document.getElementById('selector'),
selected = [],
i = 0;
for (i = 0; i < selector.children.length; i += 1) {
if (selector.children[i].selected) {
selected.push(selector.children[i].value)
}
}
selector.selMap = selected;
};
Test.addListeners = function () {
var selector = document.getElementById('selector'),
tester = document.getElementById('tester');
selector.onchange = Test.trackSelected;
tester.onclick = Test.testSelected;
};
Test.testSelected = function () {
var div = document.createElement('div');
div.innerText = document.getElementById('selector').selMap.join(', ');
document.body.appendChild(div);
};
Test.addListeners();
}());​

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>

Categories