Change select box options upon selecting option in first select box - javascript

In my javascript program I have created two select boxes and When the first option in the select box is selected,I want to display a selection of 3 images name in the images select box. When the second option is selected, I want to display a selection of corresponding 3 images name in the images box. For that I did below coding. but it's not working. can anyone help me to solve ?
code:
<!DOCTYPE html>
<html>
<head>
<title>selectbox</title>
<style>
div.event {
padding-left: 40%;
padding-top: 5%;
}
#mySelect{
width: 60px;
height: 50px;
text-align: center;
}
</style>
</head>
<body>
<form name="myForm">
<div class="event">
<select id="mySelect" multiple size="3" onchange="myFunction()">
<option value="name" disabled="disabled">Name</option>
<option value="animals">Animals</option>
<option value="flowers">Flowers</option>
</select>
<select id="mySelect2" multiple size="4">
<option disabled="disabled">Images</option>
</select>
</div>
</form>
<script>
var selectbox2 = document.getElementById('mySelect2');
function myFunction() {
if (document.getElementById('mySelect').value == "Animals"){
selectbox2.append('<option>Tiger</option>');
selectbox2.append('<option>Lion</option>');
selectbox2.append('<option>Bear</option>');
}
else if (document.getElementById('mySelect').value == "Flowers"){
selectbox2.append('<option>Rose</option>');
selectbox2.append('<option>Lotus</option>');
selectbox2.append('<option>Lily</option>');
}
}
</script>
</body>
</html>

Your first select values are written in lower case, but your if tests are testing for capitals.
Second, the append() method is not standard and you should be using .appendChild() instead. But, with either one, you can't append strings. For strings, you must set the .innerHTML property.
If you want to use .append() or .appendChild(), you need to be appending a "DOM node", which can be created like this:
var option = document.create("option");
option.value = "something";
Lastly, don't use inline HTML event attributes (onclick, onchange, etc.). There are many reasons why. Instead do all your JavaScript work in a JavaScript area and follow modern standards for event handling (.addEventListener()).
<!DOCTYPE html>
<html>
<head>
<title>selectbox</title>
<style>
div.event {
padding-left: 40%;
padding-top: 5%;
}
#mySelect{
width: 60px;
height: 50px;
text-align: center;
}
</style>
</head>
<body>
<form name="myForm">
<div class="event">
<select id="mySelect" multiple size="3">
<option value="name" disabled="disabled">Name</option>
<option value="animals">Animals</option>
<option value="flowers">Flowers</option>
</select>
<select id="mySelect2" multiple size="4">
<option disabled="disabled">Images</option>
</select>
</div>
</form>
<script>
// Get a reference to the first drop down:
var selectbox1 = document.getElementById('mySelect');
// Set up the event handling for the first select:
selectbox1.addEventListener("change", myFunction);
var selectbox2 = document.getElementById('mySelect2');
function myFunction() {
if (document.getElementById('mySelect').value == "animals"){
selectbox2.innerHTML = '<option disabled="disabled">Images</option><option>Tiger</option><option>Lion</option><option>Bear</option>';
}
else if (document.getElementById('mySelect').value == "flowers"){
selectbox2.innerHTML = '<option disabled="disabled">Images</option><option>Rose</option><option>Lotus</option><option>Lily</option>';
}
}
</script>
</body>
</html>

This may help you. I've just added some simple feature.
<!DOCTYPE html>
<html>
<head>
<title>selectbox</title>
<style>
div.event {
padding-left: 40%;
padding-top: 5%;
}
#mySelect {
width: 60px;
height: 50px;
text-align: center;
}
</style>
</head>
<body>
<form name="myForm">
<div class="event">
<select id="mySelect" multiple size="3" onchange="myFunction()">
<option value="name" disabled="disabled">Name</option>
<option value="animals">Animals</option>
<option value="flowers">Flowers</option>
</select>
<select id="mySelect2" multiple size="4">
<option disabled="disabled">Images</option>
</select>
</div>
</form>
<script>
var selectbox2 = document.getElementById('mySelect2');
function myFunction() {
if (document.getElementById('mySelect').value == "animals") {
selectbox2.options.length = 1;
let tiger = document.createElement('option');
tiger.text = 'Tiger';
selectbox2.add(tiger);
let lion = document.createElement('option');
lion.text = 'Lion';
selectbox2.add(lion);
let bear = document.createElement('option');
bear.text = 'Bear';
selectbox2.add(bear);
} else if (document.getElementById('mySelect').value == "flowers") {
selectbox2.options.length = 1;
let rose = document.createElement('option');
rose.text = 'Rose';
selectbox2.add(rose);
let lotas = document.createElement('option');
lotas.text = 'Lotas';
selectbox2.add(lotas);
let lilly = document.createElement('option');
lilly.text = 'Lilly';
selectbox2.add(lilly);
}
}
</script>
</body>
</html>

Related

JavaScript not changing display css value

I am a novice at Web Design and JavaScript. I have searched on here a bit and have tried multiple solutions I thought would work and so far nothing. I am working on an assignment for school. I am trying to use JavaScript to display a div which contains a form. I have two different divs set to display: none in my CSS file. Based on the value of a drop down I want to display the correct form. I tried to input a script and tried the onchange call as well, nothing happens with either. I don't even see errors in developer mode.
window.onload = function() {
document.getElementById("choice").onchange = function() {
var selection = this.value;
if (selection == "helpRequest")
document.getElementById('divHelpRequest').style.display = 'block';
if (selection == "feedback")
document.getElementById('formDiv').style.display = 'block';
}
}
<form name="surveyChoice" method="post" id="choice">
<fieldset>
<legend>Which Form do you Require</legend>
<select size="1" name="choice" id="choice">
<option>Select your form</option>
<option value="feedback">General Feedback</option>
<option value="helpRequest" onchange="function();">Help Request</option>
</select>
</fieldset>
</form>
Added two thing here.
First you have to use elem = e.target; to asimilate the this var from jquery. e means the event that trigger the onchange and target is the elment that trigger it.
Then i added an else to your if so we can handdle both div and disappear the one that wasn;t selected
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
window.onload = function() {
document.getElementById("choice").onchange = function(e) {
elem = e.target;
var selection = elem.value;
if (selection == "helpRequest")
document.getElementById('divHelpRequest').style.display ='block';
else {
document.getElementById('divHelpRequest').style.display ='none';
}
if (selection == "feedback")
document.getElementById('formDiv').style.display = 'block';
else {
document.getElementById('formDiv').style.display = 'none';
}
}
}
#divHelpRequest,
#formDiv {
display: none;
width: 100px;
height: 100px;
}
#divHelpRequest {
background-color: blue;
}
#formDiv {
background-color: red;
}
<head>
<title>
WSD Portal
</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/mystyle.css">
<script>
</script>
</head>
<form name="surveyChoice" method="post" id="choice">
<fieldset>
<legend>Which Form do you Require</legend>
<select size="1" name="choice" id="choice">
<option>Select your form</option>
<option value="feedback">General Feedback</option>
<option value="helpRequest" onchange="function();">Help Request</option>
</select>
</fieldset>
<div id="divHelpRequest"></div>
<div id="formDiv"></div>
Id should be always unique, also you can check the code below.
window.onload = function() {
document.getElementById("choice").onchange = function() {
var selection = this.value;
if (selection == "helpRequest")
document.getElementById('divHelpRequest').style.display = 'block';
if (selection == "feedback")
document.getElementById('formDiv').style.display = 'block';
}
}
<form name="surveyChoice" method="post">
<fieldset>
<legend>Which Form do you Require</legend>
<select size="1" name="choice" id="choice">
<option>Select your form</option>
<option value="feedback">General Feedback</option>
<option value="helpRequest">Help Request</option>
</select>
</fieldset>
</form>
<div id="formDiv" style="display:none;">
<h2>I am from form formDiv</h2>
</div>
<div id="divHelpRequest" style="display:none;">
<h2>I am from form divHelpRequest</h2>
</div>
This should work:
window.onload=function(){
document.getElementById("choice").onchange=function(input) {
var selection = input.target.value
console.log(selection);
if (selection == "helpRequest")
document.getElementById('divHelpRequest').style.display='block';
if (selection == "feedback")
document.getElementById('formDiv').style.display='block';
}
}
#divHelpRequest{
width: 100%;
height: 50px;
background-color: green;
display: none;
}
#formDiv{
width: 100%;
height: 50px;
background-color: blue;
display: none;
}
<form name="surveyChoice" method="post" id="choice">
<fieldset>
<legend>Which Form do you Require</legend>
<select size="1" name="choice" id="choices">
<option>Select your form</option>
<option value="feedback">General Feedback</option>
<option value="helpRequest" onchange="function();">Help Request</option>
</select>
</fieldset>
<div id="divHelpRequest"></div>
<div id="formDiv"></div>
This snippet:
var selection = input.target.value gets the value of your input buttons, I think you were stuck here.

Button doesn't perform action when adding Item to list

I am trying to make an application using the MVC design in javascript where I am getting the input from a textbox and insert it into a listbox.
From my point of view, the MVC should be correctly implemented but there is something wrong when I'm creating an onclick event for the 'Add' button. Nothing happens when it's pressed.
There must be something that I am missing here...Can I get some guidance??
function Model(){
this.addValue = function(songName){
var opt = document.createElement("option");
var name = songName.value;
name = name.toString();
opt.text = name;
opt.value = name;
document.getElementById("lstBox").options.add(opt);
return clear();
}
function clear(){
document.getElementById('text').value = '';
document.getElementById('artist').value = '';
document.getElementById('genre').value = '';
document.getElementById('type').value = '';
}};
This is my Controller:
function Controller(view, model){
this.addItem = function(song){
model.addValue(song);
};
};
And View:
function View(){
var songName = document.getElementById('text'),
artistName = document.getElementById('artist'),
genre = document.getElementById('genre'),
type = document.getElementById('type'),
addBtn = document.getElementById('click'),
listBox = document.getElementById('lstBox');
this.control = function(controller){
addBtn.onclick = controller.addItem(songName);
}};
This is the HTML for textboxes and Listbox:
<html>
<head>
<title>Application</title>
<script src="View.js"></script>
<script src="Model.js"></script>
<script src="Controller.js"></script>
</head>
<body>
<!-- Song Input view -->
<h1>Music List</h1>
<fieldset class="settingsView">
<legend><b><i>Insert Song</i></b></legend><br>
<label for="text">Insert song name:</label><br>
<input type="text" id='text'/><br><br>
<label for="artist">Artist:</label><br>
<input type="text" id="artist"/><br><br>
<label for="genre">Genre</label>
<select id="genre">
<option style='display: none'>
<option value="Pop">Pop</option>
<option value="Rock">Rock</option>
<option value="Dubstep">Dubstep</option>
<option value="Hip-Hop">Hip-Hop</option>
</select><pre></pre>
<label for="type">Type:</label>
<select id="type">
<option style='display: none'>
<option value="mp3">MP3</option>
<option value="mp4">MP4</option>
<option value="wmv">WMA</option>
<option value="mpg">WAV</option>
</select><br><br><br>
<button class="bttn" type="button" id="click">Add</button><br>
<style>
.settingsView{
width: 270px;
float: left;
}
.bttn{
width: 200px;
height: 30px;
margin: 0 auto;
display: block;
}
</style>
</fieldset>
<label for="listText">Song List:</label><br>
<select class="listBox" size="10" name="listBox" id="lstBox" multiple>
<option selected>Nothing to see
<option>Michael Jackson
<option>Skrillex
<option>Matilda has Worms
<option>Schnitzel Blast
</select>
<style>
.listBox{
width: 400px;
height: 500px;
position: relative;
}
</style>
</fieldset> -->
</body>
<script>
var model = new Model();
var view = new View();
var controller = new Controller(view, model);
view.control(controller);
</script>
</html>
You're using document.getElementsById() - there is no getElementSById -notice the S.
There is document.getElementById() which will return a single element.
There is also document.getElementsByTagName() and document.getElementsByClassName(). Both of these will return an HTMLCollection - and array-like object of elements.
Looking at your code, it seems all you need to do is change getElementsById to getElementById
As a final note - the browser console is your friend. Your console would 100% have shown you a bunch of error messages saying document.getElementsById() is not a function - when developing with JS ALWAYS refer to your console.
You also have an issue with how you're assigning your onclick.
It should be like this:
addBtn.onclick = function(){ controller.addItem(songName)};
Here is a working fiddle for you - only change really was the above
https://jsfiddle.net/Lfbhmwhe/

Selecting only the options not wrapped inside span to move to next select list

This is related to my earlier question here:
how to get autocomplete result come up in existing select list
But then the style display none does not work in ie. I am using only IE.
I was able to workaround the issue and was able to hide the option items inside spans.
But the problem now is suppose i enter 160 for ids I get the three option in the left select list.
Now when I use the '>>' button all the hidden items also move.How do I select only the three options that came after filter and not all.
My html code is like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete Extension - Auto Select Option</title>
<script type="text/javascript" src="scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.fn.hideOption = function () {
jQuery(this).wrap('<span class="hideOption" style="display: none;" />');
}
$.fn.showOption = function () {
if (jQuery(this).parent('span.hideOption').length)
jQuery(this).unwrap();
}
$("#txtid").on("keyup", function () {
var val = $(this).val();
$("#idLeftValues option").each(function () {
if ($(this).attr("id").indexOf(val) == -1)
$(this).hideOption();
else
$(this).showOption();
});
});
$("#btnidLeft").click(function () {
var selectedItem = $("#idRightValues option:selected ").hasClass("hideOption");
$("#idLeftValues").append(selectedItem);
});
$("#btnidRight").click(function () {
var selectedItem = $("#idLeftValues option:selected");
$("#idRightValues").append(selectedItem);
});
$("#btnidLeftAll").click(function () {
$("#idRightValues option").prop('selected', true);
var selectedItem = $("#idRightValues option:selected");
$("#idLeftValues").append(selectedItem);
});
$("#btnidRightAll").click(function () {
$("#idLeftValues option").prop('selected', true);
var selectedItem = $("#idLeftValues option:selected");
$("#idRightValues").append(selectedItem);
});
});
</script>
<style type="text/css">
.innercontainer > DIV {
float: left;
padding: 4px;
}
.containerid {
padding: 8px;
float: left;
width:600px;
font-weight:bold;
}
#row3 SELECT, #row3 INPUT[type="text"]
{
width: 140px;
}
.lstBtns
{
width: 30px;
text-align: center;
}
.lbBtn
{
width:25px;
text-align:center;
padding-left:0px;
}
</style>
</head>
<body>
<div class="contid">
<span>
id:
<input id="txtid" type="text" /></span>
<br />
<div id="row3" class="innercontainer">
<div>
<select id="idLeftValues" size="8" multiple>
<option id="140546">140546</option>
<option id= "150978" >150978</option>
<option id= "160968">160968 </option>
<option id= "160978">160978</option>
<option id= "160988">160988</option>
<option id= "170978">170978</option>
<option id= "170979">170979</option>
<option id= "170980">170980</option>
<option id= "170981">170981</option>
<option id= "170982">170982</option>
<option id= "170991">170991</option>
<option id= "170992">170992</option>
<option id= "170993">170993</option>
</select>
</div>
<div class="lstBtns">
<br />
<input type="button" id="btnidRight" class="lbBtn" value=" >" />
<input type="button" id="btnidRightAll" class="lbBtn" value=">>" />
<input type="button" id="btnidLeft" class="lbBtn" value=" <" />
<input type="button" id="btnidLeftAll" class="lbBtn" value="<<" />
</div>
<div>
<select id="idRightValues" size="8" multiple>
</select>
</div>
</div>
</div>
The fiddle link is here
http://jsfiddle.net/0808/GumFy/

Unable to fetch the value of a combo box

I am trying to access the text property of the selected option of a combo box. The following code is where I have reached so far but I am not able to recognize the error in my code.
<!DOCTYPE html>
<html >
<head>
<link rel="stylesheet" href="dijit/themes/claro/claro.css">
<style type="text/css">
table,td
{
border: 1px solid black;
}
td
{
height:30px;
vertical-align:center;
padding:15px;
}
.tableClass
{
border:1px;
border: 1px solid black;
}
</style>
<script src='dojo/dojo.js' data-dojo-config='parseOnLoad: true'></script>
<script>
//require(["dojo/parser", "dijit/form/FilteringSelect", "dojo/store/Memory"]);
</script>
<script type="text/javascript">
dojo.require("dijit.form.ComboBox");
function alterEntries()
{
//alert("in");
document.getElementById('overlayName').value = dijit.byId('stateSelect').value;
dojo.style("description", {
display:"block",
});
dojo.style("overlayName", {
display:"block",
});
}
function submitEntries(ovlName,overlayDescription)
{
var textOfOvl = getSelectedText(ovlName);
alert("overlayName " + ovlName + " overlayDescription " + overlayDescription);
}
function getSelectedText(elementId)
{
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
{
alert("null");
return null;
}
return elt.options[elt.selectedIndex].text;
}
</script>
</head>
<body class="claro">
<select id="stateSelect" data-dojo-type="dijit.form.ComboBox">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
</select>
<input name="overlayName" type="text" value="overlayName" id="overlayName" style="display:none">
<textarea name="description" cols="50" rows="3" id="description" style="display:none"></textarea>
<p>
<button onclick="alterEntries();">EDIT</button>
<button onclick="submitEntries(document.getElementById('overlayName').value,document.getElementById('description').value);">SUBMIT</button>
</p>
</body>
</html>
I am breaking my head trying to figure out what is going wrong.Can someone please hep me out.Many thanks!
your get selected text should look like this in order to get the displayed text:
function getSelectedText(el){
var text = dijit.byId(el).get('displayedValue'),
value = dijit.byId(el).get('value');
alert(text);
return text;
}
I recomend you to check out the basic dijit tutorials, document.getElementById will yield a very different reult than dijit.byId when working with dijits.
this is also a slight correction in your input
<input name="overlayName" type="hidden" value="stateSelect" id="overlayName">
also i recomend you to use
dojo.byId('textId');
instead of document.getElementById
Your code is very-very strange. As I can understand it at line
<input name="overlayName" type="text" value="overlayName" id="overlayName" style="display:none">
value attribute must be set to stateSelect, but not to overlayName.
And to see any working result in browser change implementation of submitEntries function:
function submitEntries(ovlName,overlayDescription)
{
var textOfOvl = getSelectedText(ovlName);
alert(textOfOvl);
}
See working modification of your code.

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