How do I get javascript to see updated select value? - javascript

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.

Related

jquery how to fill select option in my form

enter image description here
The json (data) looks like this
guys! I have a little form. Like this:
<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
<select id="activity_2" name="activity_2">
<option value="">Exmaple</option>
</select>
<input type="submit" value="GO GO GO"/>
</form>
<script src="/add-information/aa.js"></script>
In this little code i receive a json with data from my database:
var data = JSON.parse(response);
console.log(data);
in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:
var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?
help me please, how i can fill select with data from 'data'?
THE SOLUTION BY ADEON IS:
var data = JSON.parse(response);
console.log(data);
var select = document.getElementById('activity_2');
for (var i = 0; i < data.data.length; i++) {
select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
}
You need to do these:
1) Your call getelementById should be changed to getElementById otherwise you would receive error.
2) You need to create options string first and then append that string to DOM rather than touching DOM every time you add options. Touching DOM as less as possible is a good idea from performance point of view.
3) To simplify the syntax you can use string interpolation syntax like below:
var select = document.getElementById('activity_2');
//$(select).html('');
var data = [{id:1, name_rom:'a', name_rus:'abc'},{id:2, name_rom:'x', name_rus:'xyz'}];
var options = "";
for (var i = 0; i < data.length; i++) {
options += `<option value=${data[i].id}>${data[i].name_rus}</option>`;//<--string
//interpolation
}
$(select).append(options);
//OR below, so you don't need to call document.getElementById
//$('#activity_2').append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
<select id="activity_2" name="activity_2">
<option value="">Exmaple</option>
</select>
You can loop your data and append option html to your select.
var select = document.getelementById('activity_2');
$(select).html('');
for (var i in data) {
$(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
}
Assuming data is an array, you could iterate over it and apply it to the DOM like so.
var optionString = '';
var data = ['John', 'Josh'];
data.forEach(function(dataItem, index){
optionString += '<option value="' + index + '">' + dataItem + '</option>';
});
$('#activity_2').append(optionString);
Here is a working jsfiddle:
https://jsfiddle.net/9ke5fzqo/
You should use add method which accepts as parameter a new Option.
The constructor of Option looks like this: new Option(text,value).
var array=[{
"text":"text1",
"value":"value1"
},{
"text":"text2",
"value":"value2"
}];
var select = document.getElementById('activity_2');
array.forEach(function(item){
select.add(new Option(item.text,item.value));
});
<select id="activity_2" name="activity_2">
You can use $.append in jquery to add new option into a select input.
Html:
<select id="selinput" name="activity_2"> <option value="">Exmaple</option> </select>
Jquery:
$("#selinput").append('<option value="1">value</option>');
Or you can use jquery.selec2 plugin.

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

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.

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?

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