get the selected value of the select box - javascript

I have the selectbox and that selected box has one value selected, now i can change the value and i want that it should pick the changed value instead of the already selected value
i am using it like this
var x= document.getElementById("numbervalue");
var y= document.getElementById("dayvalue");
ax = dnum.options[x.selectedIndex].value;
at = dDay.options[y.selectedIndex].value;
ut the above only giving me the previously selected value instead of new one

Hopefully this helps
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>get value of select box</title>
<style>
body {
font-family: Courier, monospace;
}
#output {
margin-top:10px;
text-align:center;
padding:10px;
width: 200px;
height:100px;
border-style:groove;
}
.info {
font-size: 12px;
width: 270px;}
</style>
</head>
<body>
<h3>select box stack overflow</h3>
<p class = "info">On any change in an option element, the JS will use the vals from the numbervalue option element to reset the val in the dayvalue option element.<br><br>You must change the number to change anything</p>
<label for = "dayvalue">Choose a day:</label>
<select name="dayvalue" id="dayVal" onchange="readBoxes()">
<option value="m">Monday</option>
<option value="t">Tuesday</option>
<option value="w">Wednesday</option>
<option value="th">Thursday</option>
<option value="f">Friday</option>
<option value="sat">Saturday</option>
<option value="sun">Sunday</option>
</select>
<br>
<label for = "numbervalue">Choose a number:</label>
<select name="numbervalue" id="numVal" onchange="readBoxes()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<div id="output">Day of Week</div>
<p>-h34dsp1nns</p>
<script>
function readBoxes() {
var out = document.getElementById("output");
var day = document.getElementById("dayVal");
var num = document.getElementById("numVal");
var numIndex = num.selectedIndex;
day.selectedIndex = numIndex; //resets the index
var dayVal = day[numIndex]; //gets the option element at an index
out.innerHTML = dayVal.text;
}
</script>
</body>
</html>

Related

Display selected items in a list

How to display selected items in a list?
So that the elements selected in the selector are displayed in the list below it.
Example code:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="md-form">
<select name="users" multiple="multiple"
required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</body>
</html>
What should be the result:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<select name="users" multiple="multiple"
required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Selected items:
<ul>
<li>1</li>
<li>3</li>
</ul>
</body>
</html>
You need check your selected is exist or not and create it.
if( document.getElementById("mySelect") != undefined) {
document.getElementById("mySelect").remove();
}
var selectList = document.createElement("select");
And you map function to create options selected in change event handle as
function change (options) {
var parent = document.getElementsByClassName("md-form")[0];
if( document.getElementById("mySelect") != undefined) document.getElementById("mySelect").remove();
var selectList = document.createElement("select");
let selected = [...options].filter(o => o.selected).map(o => {
selectList.id = "mySelect";
selectList.multiple = "multiple";
parent.appendChild(selectList);
var option = document.createElement("option");
option.value = o.value;
option.text = o.text;
selectList.appendChild(option);
});
}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="md-form">
<select name="users" multiple="multiple"
required onchange="change(this.options);">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
</body>
</html>
Another approach is to do something like that (added notes inside the code):
const userSelection = document.querySelector('[name="users"]'); // select element
const userSelect = document.querySelector('ul'); // list container
userSelection.addEventListener('change', function() { // add event listener to change of the select
const options = userSelection.querySelectorAll('option'); // list of options
options.forEach(option => { // iterate them
if(option.selected == true) { // if one of them selected
const newLI = document.createElement('li'); // create li element
newLI.textContent = option.value; // add the value of selected option as text content
newLI.addEventListener('click', function() { userSelect.removeChild(this); }); // BONUS: remove list item with click
userSelect.appendChild(newLI); // append the new created li element to the list
}
});
});
<div class="md-form">
<select name="users" multiple="multiple" required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<ul></ul>
Hope that helps!
I was thinking that you could use JavaScript (JS) as a way to get the items that are selected and paste them elsewhere (wherever you want).
Try this:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<select id="select" name="users" multiple="multiple"
required>
<option class="option" value="1">1</option>
<option class="option" value="2">2</option>
<option class="option" value="3">3</option>
</select>
Selected items:
<ul>
<li>1</li>
<li>3</li>
</ul>
</body>
</html>
Then add JS:
// Get the select input
document.getElementByID("select")
// Get the options
document.getElementByClassName("option")
// Get the options that are selected
var print = `.option:[active]`;
// Print (paste) the selected options elsewhere on the page
if print {
document.write(print);
}
Please tell me if this works, as it might not. After all, I'm just an 8-year old, and just starting to learning web development.
You could use the following:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="md-form">
<select name="users" multiple="multiple"
required>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<script>
// References to elements
var select = document.querySelector('select'),
options = Array.from(select.querySelectorAll('option')),
form = document.querySelector('.md-form'),
ul = document.createElement('ul');
// Variables with information
var selected = [];
select.addEventListener('change', function() {
selected = [];
ul.innerHTML = '';
options.map(function(el) {
if (el.selected) selected.push(el);
});
if (selected.length) {
selected.map(function(el) {
var li = document.createElement('li');
li.textContent = el.textContent;
ul.appendChild(li);
});
form.appendChild(ul);
} else {
form.removeChild(ul);
}
});
</script>
</body>
</html>
Working fiddle:
https://jsfiddle.net/1j7a9h35/

Check if two options have been selected

I need to know if two options from a select dropdown list have been chosen so I can take the text and make a button that has that text inside of it show up. Right now the button shows with some text before the options have been clicked but doesn't show up again if closed and options have been chosen.
If someone has answered this question please let me know I couldn't find anything to help me.
Here's my code:
$(document).ready(function () {
var valueFrom = $('#revenueFrom option:selected').text();
var valueTo = $('#revenueTo option:selected').text();
if ($('#revenueFrom option').data('clicked', true) && $('#revenueTo option').data('clicked', true)) {
$('#annual-revenue-button').text("");
$('#annual-revenue-button').append(valueFrom + "To:" + valueTo + " " + "×");
$('#annual-revenue-button').show('fast');
};
});
$('.search-popup').click(function () {
$(this).hide('fast');
});
button{
background-color:whitesmoke;
border-radius: 20px;
display:none;
}
button:hover{
background-color:lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<button class="search-popup btn" id="annual-revenue-button" type="button"></button>
<form class="form-inline revenue">
<div class="form-group">
<label>Annual Revenue</label>
<select name="revenueFrom" class="form-control" id="revenueFrom">
<option value="" selected disabled>From:</option>
<option value="0">$0</option>
<option value="1">$500,000</option>
<option value="2">$1 Million</option>
<option value="3">$2.5 Million</option>
<option value="4">$5 Million</option>
</select>
<select name="revenueTo" class="form-control to" id="revenueTo">
<option value="" selected disabled>To:</option>
<option value="0">$0</option>
<option value="1">$500,000</option>
<option value="2">$1 Million</option>
<option value="3">$2.5 Million</option>
<option value="4">$5 Million</option>
</select>
</div>
</form>
You need to set a .change() event listener on the select elements.
When one of them has been changed, check the values of those select elements are not empty, and then show your button.
$(document).ready(function () {
$('#revenueFrom, #revenueTo').change(function(){
if ($('#revenueFrom').val() && $('#revenueTo').val()) {
var valueFrom = $('#revenueFrom option:selected').text();
var valueTo = $('#revenueTo option:selected').text();
$('#annual-revenue-button').html("From: " + valueFrom + " To: " + valueTo + " ×").show('fast');
};
});
});
$('.search-popup').click(function () {
$(this).hide('fast');
});
button{
background-color:whitesmoke;
border-radius: 20px;
display:none;
}
button:hover{
background-color:lightgray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<button class="search-popup btn" id="annual-revenue-button" type="button"></button>
<form class="form-inline revenue">
<div class="form-group">
<label>Annual Revenue</label>
<select name="revenueFrom" class="form-control" id="revenueFrom">
<option value="" selected disabled>From:</option>
<option value="0">$0</option>
<option value="1">$500,000</option>
<option value="2">$1 Million</option>
<option value="3">$2.5 Million</option>
<option value="4">$5 Million</option>
</select>
<select name="revenueTo" class="form-control to" id="revenueTo">
<option value="" selected disabled>To:</option>
<option value="0">$0</option>
<option value="1">$500,000</option>
<option value="2">$1 Million</option>
<option value="3">$2.5 Million</option>
<option value="4">$5 Million</option>
</select>
</div>
</form>
You need to add Multiple and add [] after name=revenueFrom So an array with all of the elements is being passed on form submission.
This post may also be of use to you how to access multiple select array data in javascript
Note this function:
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;
}
It would also be possible to make an event listener that looks for change on the select and appends a new element somewhere else with the selected data if that's what you needed, feel free to update your question if you need a more specific answer.

Making a selection in a select box and displaying the chosen answer into another

I need your help,
I am unsure as to how to go about the following:
If I select the color green into the first select box, I would need the selected option to be automatically selected into the 2nd select box.
How do you accomplish this using just javascript alone.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<span>Category:</span>
<br>
<select id="select1">
<option value=""></option>
<option value="RED">RED</option>
<option value="BLUE">BLUE</option>
<option value="GREEN">GREEN</option>
<option value="YELLOW">YELLOW</option>
</select>
<br>
<span>Your selection was:</span>
<br>
<select id="select2">
<option value=""></option>
<option value="RED">RED</option>
<option value="BLUE">BLUE/option>
<option value="GREEN">GREEN</option>
<option value="YELLOW">YELLOW</option>
</select><b></b>
</body>
</html>
You can iterate through the options until you find the same value:
document.getElementById("select1").onchange = function() {
var selected = this.value;
var select2 = document.getElementById("select2");
//find the index in the second select
for (var i = 0; i < select2.options.length; i++) {
if (select2.options[i].value == selected) {
select2.options[i].selected = true;
}
}
}
Demo: http://jsfiddle.net/HJm7E/
If two select tags have same options:
var select1 = document.getElementById('select1');
var select2 = document.getElementById('select2');
select1.addEventListener('change', function(){
select2.selectedIndex = this.selectedIndex;
});
Fiddle
Note that this simple solution will be wrong for selects that have different options. In this case this will work:
select1.addEventListener('change', function(){
for(var i = 0; i < select2.options.length; i++){
if(select2.options[i].value === this.options[this.selectedIndex].value)
select2.options[i].selected = true;
}
});
Updated fiddle
<!DOCTYPE html>
<html>
<head>
<script>
function doOnload() {
var slt1 = document.getElementById("select1");
var slt2 = document.getElementById("select2");
slt1.onchange = function() {
slt2.options[slt1.selectedIndex].selected = true;
};
}
</script>
</head>
<body onload="doOnload()">
<span>Category:</span>
<br>
<select id="select1">
<option value=""></option>
<option value="RED">RED</option>
<option value="BLUE">GREEN</option>
<option value="GREEN">GREEN</option>
<option value="YELLOW">YELLOW</option>
</select>
<br>
<span>Your selection was:</span>
<br>
<select id="select2">
<option value=""></option>
<option value="RED">RED</option>
<option value="BLUE">GREEN</option>
<option value="GREEN">GREEN</option>
<option value="YELLOW">YELLOW</option>
</select><b></b>
</body>

while loop is not working in javascript code?

In this code I'm trying to generate dynamic text fields based on the input of select field which handled by addInput(divname) function using on change event but the while loop inside addInput function is not working and when i remove while loop its working. i have to generate selected no. of text fields... and also the text fields should change when i select different number...
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="adduniv.php" method="post">
University Name: <input type="text" name="college">
No. of branches:
<div id="dynamicInput">
<select name="branches" id="branches" onchange="if (this.selectedIndex) addInput('dynamicInput');;" ">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
</div>
<script>
var counter = 0;
var limit = 3;
function addInput(divName)
{
var k=parseInt(document.getElementById("branches"));
var newdiv;
while(k>0)
{
newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
k--;
}
}
</script>
<input type="submit" value="submit" />
</form>
</body>
</html>
var k=parseInt(document.getElementById("branches"))
You can't parseInt a DOM element.
Suspect you meant
var k=parseInt(document.getElementById("branches").value,10)
with thanks to the comment from Shikiryu re: specifying the radix explicitly.
document.getElementById("branches") returns a DOM-Node, but what you need to do, is to get the value of this DOM-Node. So try the following to generate k.
var k=parseInt(document.getElementById("branches").value);
change the line
var k=parseInt(document.getElementById("branches"));
to
var k=parseInt(document.getElementById("branches").value);
i think you forgot to add .value to document.getElementById("branches")
parseInt(document.getElementById("branches"));
will result in NaN as far as I can tell. You are trying to parse a whole DOM node as an integer, what did you expect? You might want to get the value property from it:
parseInt(document.getElementById("branches").value, 10);
Ok, I know the problem was solved, but I would try do this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Creating input fields</title>
<script>
function addInput(nr_branches) {
var nCounter = 0;
//-- Cleaning all elements
var divB = document.getElementById('divBranches');
if(divB.hasChildNodes()) {
while(divB.childNodes.length >= 1) {
divB.removeChild(divB.firstChild);
}
}
while(nCounter < nr_branches) {
//-- Create a input field
var input = document.createElement("input");
input.type = 'text';
input.name = 'branche_nr_' + nCounter;
input.placeholder = 'Branche Nr.' + nCounter;
//document.getElementById("divBranches").innerHTML = "<input type='text' name='branche_nr_'"+ nCounter +" placeholder='Branche Nr."+ nCounter +"' />";
document.getElementById('divBranches').appendChild(input);
nCounter++;
}
}
</script>
</head>
<body>
<form name="frm" action="adduniv.php" method="post">
<input type="text" name="college" placeholder="University Name" />
<select name="branches" id="branches" onchange="addInput(this.value)">
<option value="0">-select your branche-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<div id="divBranches"></div>
<input type="submit" value="submit" />
</form>
</body>
</html>

Dynamic/ dependent input box

How can i make a input box that appears only when i select a value from a drop down box?
thank you,
Sebastian
EDIT-1:
thanks guys for the help.
but the example from sushil bharwani is best for me, because i also need to display a text with the text box.
but with that example i have a problem. both the text and the text box look like they are in the same cell, so they are messing up my layout for the form.
Got any ideas?
thanks,
You'll want to define the select's onchange attribute to check the text (or value) of the selected option:
<script type="text/javascript">
function checkSelect(el) {
if (el.options[el.selectedIndex].text.length > 0)
document.getElementById('text1').style.display = 'block';
else
document.getElementById('text1').style.display = 'none';
}
</script>
<select onchange="checkSelect(this)">
<option></option>
<option>Val 1</option>
</select>
<input type="text" id="text1" style="display:none" />
For further details, you can read more about HTML DOM objects and how to access them via javascript:
http://www.w3schools.com/jsref/default.asp
Consider that the textbox should show when choice 2 is selected
The dropdown box
<select id="dropBox" size="1" onChange="dropBoxChng();">
<option value="1">Choice 1</option>
<option value="2">Choice 2</option>
<option value="3">Choice 3</option>
<option value="4">Other</option>
</select>
the input box
<input type="text" id="txtBox" style="display:none">
the onchange function
function dropBoxChng(){
if(document.getElementById('dropBox').value == 2){
document.getElementById('txtBox').style.display = 'block';
}
}​
Demo here
<html>
<head>
<style type="text/css">
input {
font-family: Arial, Sans-Serif;
font-size: 13px;
margin-bottom: 5px;
display: block;
padding: 4px;
border: solid 1px #85b1de;
width: 300px;
background-color: #EDF2F7;
}
option {
color: white;
background-color: blue;
}
.even {
background-color: red;
color: blue;
}
</style>
<script>
function replaceElement(){
var select=document.getElementById('mySelectMenu');
var chosenoption=select.options[select.selectedIndex];
var oChild= document.getElementsByTagName('input');
var br1= document.getElementsByTagName('br');
var temp=br1.length;
for(var i=0; i<temp; i++){
alert("remove input box " + i);
myform.removeChild(oChild[0]);
alert("remove br " + i);
myform.removeChild(br1[0]);
}
for(var i=0; i<chosenoption.value; i++){
alert("add br " + i);
var br2 = document.createElement('br');
myform.appendChild(br2);
alert("add input box " + i);
var oNewChild=document.createElement('input');
oNewChild.type='text';
oNewChild.size=6;
myform.appendChild(oNewChild);
}
}
</script>
</head>
<body>
<form id="myform">
<select id="mySelectMenu" onchange="replaceElement()">
<option value="1">1</option>
<option value="2" class="even">2</option>
<option value="3">3</option>
<option value="4" class="even">4</option>
<option value="5">5</option>
</select>
</form>
</body>
</html>
http://bytes.com/topic/javascript/answers/88791-show-hide-text-form-field-based-drop-down-selection

Categories

Resources