Use values from different dropdown menus - javascript

I am new to coding, therefore I don't fully understand this piece of code.
What I am trying to achieve is that I want to put in multiple drop down menus.The problem with my code is that it accepts values from only certain drop down menus.
My code helps users select the region, country and state according to what they select in the previous drop down menus. I am using this code because it is similar to what I am planning to achieve.
The issue that I face is that I have about 8 drop down menus whose data need to be used. There are 8 region drop downs, 8 country drop downs, and 8 state drop downs. All in the same page. The code stops working if I put 8 ones. What am I doing wrong?
Can somebody please help me? This is the code:
<form>
Region» <select onchange="set_country(this,country,city_state)" size="1" name="region">
<option value="" selected="selected">SELECT NOTE</option>
<option value=""></option>
<script type="text/javascript">
setRegions(this);
</script>
</select>
Country» <select name="country" size="1" disabled="disabled" onchange="set_city_state(this,city_state)"></select>
City/State» <select name="city_state" size="1" disabled="disabled" onchange="print_city_state(country,this)"></select>
<script>
////////////////////////////////////////////////////////////////////////////
// city_state.js ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
var countries = Object();
countries['C'] = '|C|Cm|';
countries['D'] = '|D|Dm|';
////////////////////////////////////////////////////////////////////////////
var city_states = Object();
//C
city_states['C'] = '|032010|335553|';
city_states['Cm'] = '|335543|';
city_states['D'] = '|000232|557775';
city_states['Dm'] = '|000231|557765';
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
function setRegions()
{
for (region in countries)
document.write('<option value="' + region + '">' + region + '</option>');
}
function set_country(oRegionSel, oCountrySel, oCity_StateSel)
{
var countryArr;
oCountrySel.length = 0;
oCity_StateSel.length = 0;
var region = oRegionSel.options[oRegionSel.selectedIndex].text;
if (countries[region])
{
oCountrySel.disabled = false;
oCity_StateSel.disabled = true;
oCountrySel.options[0] = new Option('SELECT TYPE','');
countryArr = countries[region].split('|');
for (var i = 0; i < countryArr.length; i++)
oCountrySel.options[i + 1] = new Option(countryArr[i], countryArr[i]);
document.getElementById('txtregion').innerHTML = region;
document.getElementById('txtplacename').innerHTML = '';
}
else oCountrySel.disabled = true;
}
function set_city_state(oCountrySel, oCity_StateSel)
{
var city_stateArr;
oCity_StateSel.length = 0;
var country = oCountrySel.options[oCountrySel.selectedIndex].text;
if (city_states[country])
{
oCity_StateSel.disabled = false;
oCity_StateSel.options[0] = new Option('SELECT TAB','');
city_stateArr = city_states[country].split('|');
for (var i = 0; i < city_stateArr.length; i++)
oCity_StateSel.options[i+1] = new Option(city_stateArr[i],city_stateArr[i]);
document.getElementById('txtplacename').innerHTML = country;
}
else oCity_StateSel.disabled = true;
}
function print_city_state(oCountrySel, oCity_StateSel)
{
var country = oCountrySel.options[oCountrySel.selectedIndex].text;
var city_state = oCity_StateSel.options[oCity_StateSel.selectedIndex].text;
if (city_state && city_states[country].indexOf(city_state) != -1)
document.getElementById('txtplacename').innerHTML = city_state + ', ' + country;
else document.getElementById('txtplacename').innerHTML = country;
}
</script>
Please check out the updated code at http://jsfiddle.net/HzJ9J/1/
I have not pasted one javascript code in the Javascript section, because I think that specific code needs to run in the correct place. Not sure if I have to move it to the javascript section.

The call to setRegions(this); is failing because 'setRegions is not yet defined; the function definition hasn't been loaded by the browser yet.
I added an ID attribute to your SELECT:
<select onchange="set_country(this,country,city_state)" size="1" name="region" id="region">
and then moved the call to setRegions to the very last thing before the closing SCRIPT tag. Can't use THIS any more, so I added a document.getElementById:
setRegions(document.getElementById("region"));
Using document.write is in general a bad idea, and will not work when the call to setRegions is moved out of line, as it must be. One can accomplish the same thing using innerHTML, so I changed setRegions to be this:
function setRegions(elem) {
for (region in countries)
elem.innerHTML +='<option value="'+region+'">'+region+'</option>';
}
I also deleted the empty OPTION element from the SELECT. Those changes make your code work, although there may be more things that need adjustment.
I'm supposed to answer questions, not give advice, but if you're not using Firefox and the Firebug debugger, or the similar tool in Chrome, you're working far too hard!
Edited 2014-07-21 to add: Your code:
<script type="text/javascript">
setRegions(document.getElementById("region1"));
</script>
is between the beginning and ending tags for the SELECT with the ID of "region1", and I would have bet that the DOM element would not exist at the time of the call. However, if I move your JavaScript into the head of the document, the region selects work, at least in Firefox. I'm not sure why, and I strongly urge you to move that stuff to the end as I've done in my example, or hook it to onload. The DOM really does have to be set up before you start manipulating it.
However, when I run your code with the changes I just suggested, using the Firebug debugger, it tells me: TypeError: oCountrySel.options is undefined.
Get a copy of Firebug, install it in Firefox, or use the developer tools in Chrome, run your code from your own server environment, and look at the console tab. It really will help you, and it really isn't hard.

Related

Activate function on a specific element of a select JAVASCRIPT

I would make sure that the items in select from activating the specific features I'll explain.
I have this select:
<select id='selection'> <!-->this is for the class<!-->
<option>4B</option>
<option>5B</option>
</select>
<select id='secondSelection'> <!-->this is for the data to be loaded<!-->
</select>
if I select 4B must load all pupils corresponding to that class, pupils are in the array 4B.
if instead go to select 5B must be able to load in the other select the contents of the 5B. The user can also decide to select both classes.
EXAMPLE:
4B [selected in selection] => Mario, Luigi, John are now loaded in secondSelection
similarly for all values ​​have to be able to do the same thing by enabling multiple.
I have already made a similar code in the past, but here the situation is a bit 'different, I would like the help of an expert. PEACE!
Well, you can do
var b4 = ["Mario", "Luigi", "John"],
b5 = ["Some", "Other", "Names"],
elem = document.getElementById('selection');
elem.onchange = function () {
document.getElementById('secondSelection').innerHTML = this[elem.options[this.selectedIndex].text == "4B" ? "b4" : "b5 "].map(function (x) {
return "<option>" + x "</option>";
}).join();
};
You can use
<select onchange="myFunction()">
<script>
function myFunction(){
}
</script>
it will also work

How do I get javascript to see updated select value?

I have a page with about 100 dropdown menus that I need to pass to another. So, I've put everything in an array that I'm sending via javascript. However, I'm not sure how to get the javascript to see the changed values of the dropdowns before sending. I mocked up some code to give you an idea of the problem. It only sends the value of the dropdown box at the time the page is initialized. Any help would be appreciated.
<select id="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
<script>
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
</script>
<form name="data" method="POST" action="passdata1b.php">
<input type="hidden" name="data">
</form>
<script>
function sendData()
{
// Initialize packed or we get the word 'undefined'
var packed = "";
for (i = 0; (i < data.length); i++) {
if (i > 0) {
packed += ",";
}
packed += escape(data[i]);
}
document.data.data.value = packed;
document.data.submit();
}
</script>
<h1>This is what the array contains:</h1>
<ul>
<script>
for (i = 0; (i < data.length); i++) {
document.write("<li>" + data[i] + "</li>\n");
}
</script>
</ul>
Go to passdata1b.php
Sam's answer was good, except..
data[0] = document.getElementById("mydropdown").value;
..that won't work since it's a dropdown menu. Instead get the value of the selected option. Use this instead:
var zeData = document.getElementById("mydropdown");
data[0] = zeData.options[zeData.selectedIndex].value;
Why can't you put this logic:
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
In your sendData() function?
Comment if you need an example, but this should be a pretty easy fix. That way, when you click the link and run sendData(), it will parse the mydropdown value..instead of doing it on page load.

Onchange drop down menu

How can i take a value when a user choose an option from a drop down menu(select) and add it with another choice of another drop down menu and output the total of a mark? I want this total to change automatically with on-change method. I have wrote my code in JavaScript using DOM to write the form! Can you help me please?
I would personally recommend doing this with AngularJs. If you are using Angular, simply assigning the DOM element with a model (ng-model) name and you can dynamically change the items inside of your dropdown in your javascript. Check out this very simple example:
http://plnkr.co/edit/?p=preview
and here is documentation on how to use the ng-change utility that comes with AngularJs:
http://docs.angularjs.org/api/ng.directive:ngChange
(edit: I guess I should describe what is happening in the example in more detail. Basically, what is inside of <div ng-controller="Controller"> will be tied to the controller called "Controller" in the script.js. By assigning ng-model="confirmed" to the checkbox, it ties a variable of the same name to the checkbox. As you can see a couple lines down, simply calling {{confirmed}} can call the value from html. Also, assigning ng-change="change()" to the element basically tells the controller to call the function, change(), whenever there is changes made to the element in question. Hope this helps)
This is using regular javascript.
function Total()
{
var e1 = document.getElementById("ObjectsIDValue1");
var e2 = document.getElementById("ObjectsIDValue2");
if(e1.selectedIndex < 0||e2.selectedIndex < 0 )
return;//nothing is selected in 1 of the dropdowns
var ValueUserSelected1= new Number(e1.options[e1.selectedIndex].value);
var ValueUserSelected2= new Number(e2.options[e2.selectedIndex].value);
var e3 = document.getElementById("TotalsIDValue");
e3.value = ValueUserSelected1+ValueUserSelected2;//assuming it's an input:text
};
And just add this to your select objects.
<Select id = "ObjectsIDValue1" onchange="Total();">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<!-- more option objects -->
</Select>
<Select id = "ObjectsIDValue2" onchange="Total();">
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<!-- more option objects -->
</Select>
Note: This doesn't validate whats in your select is a number.
Edit: As you appear to be new here on Stack Overflow I'd like to mention that if you found this solved your problem please mark it as the accepted answer by giving it a check mark. Also if you found this helpful and have enough points to up-vote please do that too.
Hope this helps.
Edit2: From the OP's comment I think you're looking for this,
document.getElementById("ObjectsIDValue1").onchange = function(){Total()};
document.getElementById("ObjectsIDValue2").onchange = function(){Total()};
just add that after you define Total();
Edit3: I want to be forthcoming and explain that what you're looking to do is VERY ugly in regular Javascript to do. I would recommend a JS library such as JQuery where doing this is much cleaner and easier to code.
Anyway here is ALL the code needed to do this.
<script type = "text/javascript">
//Create Selects from an Array
function CreateSelectFromArray (SelectID, ArrayOfValues)
{
var Code="";
Code += "<Select id='"+SelectID+"'>";
for(var x = 0; x < ArrayOfValues.length; x++)
{
Code += "<option>";
Code += ArrayOfValues[x];
Code += "</option>";
}
Code += "</Select>";
return Code;
};
//Repopulate a select from a start and end value
function ChangeSelectFromValues (SelectID, StartValue,EndValue)
{
var Code="";
var SelectObject = document.getElementById(SelectID);
for(var x = StartValue; x <= EndValue; x++)
{
Code += "<option>";
Code += x;
Code += "</option>";
}
SelectObject.innerHTML = Code;
};
//Add up the values of 2 Selects (currently hardcoded)
function Total()
{
var e1 = document.getElementById("ObjectsIDValue1");
var e2 = document.getElementById("ObjectsIDValue2");
if(e1.selectedIndex < 0||e2.selectedIndex < 0 )
return;//nothing is selected in 1 of the dropdowns
var ValueUserSelected1= new Number(e1.options[e1.selectedIndex].value);
var ValueUserSelected2= new Number(e2.options[e2.selectedIndex].value);
var e3 = document.getElementById("TotalsIDValue");
e3.value = ValueUserSelected1+ValueUserSelected2;//assuming it's an input:text
};
var yourArray = [5,10,15];
var SelectCode="";
SelectCode += CreateSelectFromArray ('FirstSelect', yourArray);//create select with array values
SelectCode += CreateSelectFromArray ('SecondSelect', yourArray);//create select with array values
SelectCode += CreateSelectFromArray ('ObjectsIDValue1', [1,2,3,4,5]);//create select with default array
SelectCode += CreateSelectFromArray ('ObjectsIDValue2', [1,2,3,4,5]);//create select with default array
SelectCode += "<input id='TotalsIDValue'/>";
var doc = document.open("text/html","replace");
doc.writeln(SelectCode);
doc.close()
//Add events to the Selects for desired functionality
document.getElementById("FirstSelect").onchange = function(){
var e0 = document.getElementById("FirstSelect");
ChangeSelectFromValues('ObjectsIDValue1',1,new Number(e0.options[e0.selectedIndex].value));
};
document.getElementById("SecondSelect").onchange = function(){
var e0 = document.getElementById("SecondSelect");
ChangeSelectFromValues('ObjectsIDValue2',1,new Number(e0.options[e0.selectedIndex].value));
};
document.getElementById("ObjectsIDValue1").onchange = function(){Total()};
document.getElementById("ObjectsIDValue2").onchange = function(){Total()};
</script>
That's about as clean as you can get this in regular JavaScript
Note:
var doc = document.open("text/html","replace");
doc.writeln(SelectCode);
doc.close()
Can be replace with,
document.getElementById("PlaceYouWantTheSelects").innerHTML =SelectCode;
If you have a specific place in mind to put the selects.

Using div value like php variable

I have a script like this
<script type="text/javascript">
function showSelected(val){
document.getElementById
('selectedResult').innerHTML = "The selected number is - "
+ val;
}
</script>
<div id='selectedResult'></div>
<select name='test' onChange='showSelected(this.value)'>
<option value='1'>one</option>
<option value='2'>two</option>
</select>
The output is shown with
<div id='selectedResult'></div>
So, I want to use this a variable
Actually, I want to get drop down box value with out submit. This script make it, but I can use another suggestions
Thanks
I'm not sure I really understand the question, but if you want to get what's stored in the DIV, use:
var stuff = document.getElementById('selectedResult').innherHTML;
I can suggest you another alternative i think is more useful and you can use it in different way # your project.
In this example you click the options you one and insert them to option list, you can send them from your select name=test if you want, you just need to change it.
DEMO
This is the script you can catch item,links,images,attributes and add them to select box:
$(document).ready(function(){
$('li').on('click',function(){
$('#theSelect').append('<option SELECTED>'+$(this).find('img').attr('value')+'</option>');
var seen = {};
$('option').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
});
})
$('#del').click(function() {
var $list = $('#theSelect option');
var d = $list.length;
var b=($list.length-1);
$('#theSelect option:eq('+b+')').remove();
});

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