Onchange drop down menu - javascript

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.

Related

Select options to be a for result

So, I basically have a for in javascript with the variable i that goes from 0 to 23
for($i=0; $i <= 23; $i++)
And I want to clear the current select options of the select that I have (only 1 and 2)
<select id="hour_interview_ini">
<option>1</option>
<option>2</option>
</select>
And add the for result in javascript as the new options (in this case, the options would be 0 to 23)
I primarily use jQuery, so this is what that would look like. I'll make a codepen too, for you. We've all be new to a language before so I totally get not being able to troubleshoot by yourself!
To clear the list you'll want to do something like this:
$('#hour_interview_ini')
.find('option')
.remove()
.end()
;
And then to add in a loop, you'll want to do this:
for(i = 0; i <= 23; i++){
$('#hour_interview_ini').append('<option value="' + i + '">' + i + '</option>')
}
However, If you want to do it in javascript, this will work too. I put these ones in as functions (although the jquery could be functions too). If you need to know how to call them, check the code pen. It'll show you how to use the function on a click, or how to access the jQuery ID and trigger a function:
Clearing list (not the best method, but works and is super small):
function clearList(){
document.getElementById("hour_interview_ini").innerHTML = "";
}
Adding through the loop
function addList(){
var select = document.getElementById("hour_interview_ini");
for (var i = 0; i<=23; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
}
https://codepen.io/humanhickory/pen/NWKQLyR

Use values from different dropdown menus

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.

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.

get value in javascript from select tag

I am using a javascript function to get the id from a particular <select></select>.
<select name="no" id="dropdownlist" class="defaultvalue" style="width: 100%;">
<option value="">Select Option</option>
</select>
But the problem is I have 8 <select></select> for dropwdown and i want to get the value of these in the javascript like:
var list = document.getElementById('dropdownlist');
But this is only possible through using getElementByClass but this is not working for me. Any help would be appreciated.
Due you tagged your question with jquery I suggest you using it:
$('#dropdownlist').val();
UPDATE: But if you have 8 selects - just use same class for them and you can use next code:
$('.className').each(function(i,el){
console.log($(this).val());
})
There is no getElementByClass, it's getElementsByClassName, but you might as well use querySelectorAll, which has better support
var list = [];
var elems = document.querySelectorAll('.defaultvalue');
for (var i=0; i<elems.length; i++) {
list.push( elems[i].value );
}
FIDDLE
in jQuery you can do
var list = $.map($('.defaultvalue'), function(el) { return el.value});
FIDDLE
And ID's are unique, they can not be used for more than one element in the same document
If you want to go with pure javascript with multi select tag, then use below code
Update
function getAllValue(){
var allSelectTags = document.getElementsByClassName("defaultvalue");
var selVal = [];
for(var i=0; i<allSelectTags.length; i++){
var value = allSelectTags[i].options[allSelectTags[i].selectedIndex].value;
selVal.push(value);
}
var result = "";
for(var j=0; j<selVal.length; j++){
result += selVal[j] + "<br />";
}
document.getElementById("result").innerHTML = result;
}
DEMO

Trouble parsing a select element

I have a dropdown in a Grid. This is how it looks like. Now I am
trying to get the name of the select tag.
var x = document.getElementsByTagName('select');
I need to get the name and
parse it in such a way to get this value 13442111. What's the best way to go about getting this information?
<td class="cl">
<select name="ctrlvcol%3DId%3Bctrl%3DTabListView%3Brow%3D13442111%3Btype%3Dtxt" onchange="getTypeValue(this.value,13442111)">
<option value="1025">TEST-AAAA</option>
<option selected="" value="1026">TEST-BBBB</option>
<option value="1027">TEST-CCCC</option>
</select>
</td>
var selectElements = document.getElementsByTagName('select');
var selectElementsLen = selectElements.length;
for (var i = 0; i < selectElementsLen; i++) {
// split row parts
var rowID = unescape(selectElements[i].name).split(';');
if (rowID.length >= 3) {
// trim meta
rowID = rowID[2].replace(/^row=/, '');
// validate row ID
if (/^[0-9]+$/.test(rowID)) {
console.log('Valid Row ID: ' + rowID);
// do whatever needs to be done
}
}
}
http://jsfiddle.net/N4sJv/
Here's the approach with regular expression only:
var selectElements = document.getElementsByTagName('select');
var selectElementsLen = selectElements.length;
for (var i = 0; i < selectElementsLen; i++) {
// extract Row ID
var rowID = unescape(selectElements[i].name).match(/(?:row=)([0-9]+)/);
if (rowID && (rowID.length >= 2)) {
rowID = rowID[1];
console.log('Valid Row ID: ' + rowID);
// do whatever needs to be done
}
}
http://jsfiddle.net/N4sJv/1/
Keep in mind that document.getElementsByTagName() may not be the best choice as it selects all specified elements in the DOM tree. You might want to use a framework such as jQuery to consider browser compatibilities and performance.
Here is a bit of code that may help you. This little snippet will work if and only if this is the only select element on the page. As the comments above state, it would be better to identify this element with an id. However, for your use case the following should work:
// Get all select elements (in this case the one) on the page.
var elems = document.getElementsByTagName("select");
// Select the first "select" element and retrieve the "name" attribute from it
var nameAttr = decodeURIComponent(elems[0].getAttribute("name"));
// Split the decoded name attribute on the ";" and pull the second index (3rd part)
var nameProp = nameAttr .split(';')[2];
// Substr the name prop from the equal sign to the the end
nameProp = nameProp.substr(nameProp .indexOf('=') + 1);

Categories