Dynamic/ dependent input box - javascript

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

Related

html form using javaScript to call out some function

I'm a beginner and I'm try to set up a form. I have written the html/css code. What I wanted to do is to click on a level of study such as Bachelors, I want all the courses under bachelors to display in the second box (choose course) while hiding the rest of the courses in the box.
label {
font-family: sans-serif;
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<label for="school-select">Choose levels of study:</label>
<select id="level-select">
<option value="">--Please choose an option--</option>
<option value="bachelor">Bachelors</option>
<option value="postgraduates">Postgraduates</option>
<option value="phd">PhD</option>
</select>
</form>
<br>
<form id="form2" action="#">
<label for="course-select">Choose course:</label>
<select id="cour">
<optgroup label="Bachelors">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>
<optgroup label="Postgraduates">
<option>computer</option>
<option>biology</option>
<option>accounting</option>
</optgroup>
<optgroup label="PhD">
<option>business</option>
<option>fisheries</option>
<option>agric</option>
</optgroup>
</select>
</form>
Here, I've come up with a simple solution to this. I've changed your html a little bit. I've set the same values as their optgroup's label so that we can choose the specific optgroup for being shown. So the solution is simple:
Hide all the options of the second box.
Show the one by courses.querySelector('[label="' + value + '"]'); this, where value is your first box's selected value.
Have a look at the code snippet below:
function getLevels() {
var value = document.getElementById("level-select").value;
if (value) {
var courses = document.querySelector("#cour");
var all_options = courses.querySelectorAll('optgroup');
var show_courses = courses.querySelector('[label="' + value + '"]');
all_options.forEach(function (element) {
element.style.display = "none";
});
show_courses.style.display = "block";
}
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<label for="school-select">Choose levels of study:</label>
<select id="level-select" onchange="getLevels()">
<option value="">--Please choose an option--</option>
<option value="Bachelors">Bachelors</option>
<option value="Postgraduates">Postgraduates</option>
<option value="PhD">PhD</option>
</select>
</form>
<br>
<form id="form2" action="#">
<label for="course-select">Choose course:</label>
<select id="cour">
<option selected>--Choose Course--</option>
<optgroup label="Bachelors">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>
<optgroup label="Postgraduates">
<option>computer</option>
<option>biology</option>
<option>accounting</option>
</optgroup>
<optgroup label="PhD">
<option>business</option>
<option>fisheries</option>
<option>agric</option>
</optgroup>
</select>
</form>
Just add onClick event in <option> tag?
<option onClick="myFunction()">Microbiology</option>
<script>
function myFunction() {
//do what you want..
}
</script>```
Add a onchange event to the select field, and push the value to a function like;
<select id="level-select" onchange="setLevel(this.value)">
Hide all option groups in css;
#cour optgroup {
display:none;
}
Give all option groups a unique ID containing the value of the first select, like;
<optgroup label="Bachelors" id="course_bachelor">
And now the function for the onchange event could be something like this;
function setLevel (val) {
var elements = document.getElementsByTagName('optgroup');
// Loop through all elements and check if they are hidden or shown
for(var i=0; i < elements.length; i++) {
if (elements[i].id === 'course_' + val) {
elements[i].style.display = 'block';
} else {
elements[i].style.display = 'none';
}
}
}
label {
font-family: sans-serif;
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<label for="school-select">Choose levels of study:</label>
<select id="level-select">
<option value="">--Please choose an option--</option>
<option value="bachelor">Bachelors</option>
<option value="postgraduates">Postgraduates</option>
<option value="phd">PhD</option>
</select>
<br>
<label for="course-select">Choose course:</label>
<select id="cour">
</select>
</form>
var select = document.getElementById("level-select");
select.onchange(() => {
if(select.value == 'bachelor') {
document.getElementById("cour").value == "<optgroup label="Bachelors">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>"
}
})
Do this for all the conditions.
You'll need to use some Javascript to do this. Here's one solution that could work for you.
I've updated some of your html names (first dropdown values to exactly match the 'optgroup' labels in your second dropdown). Also added some CSS to have the options for the courses dropdown to not show until you've selected a valid option, which prevents the user from, say, going back to change the first dropdown value while the second dropdown value stays the same. Always 'idiot-proof' your UI:
//grab both dropdowns and store in variable
var levelSelectDropdown = document.querySelector('#level-select');
var coursesDropdown = document.querySelector('#cour');
//create an on 'change' event for first dropdown
levelSelectDropdown.addEventListener('change', levelDropdownChange);
function levelDropdownChange(e){
var selectedLevelOfStudy = e.target.value;
var coursesGroups = coursesDropdown.querySelectorAll('optgroup');
//this basically hides the 'default' empty option that's auto-selected
//by default
coursesDropdown.querySelector('option[value="default"]').style.display = 'none';
//loop through all 'optgroup' items in second dropdown (coursesGroups)
coursesGroups.forEach(function(element){
//default course dropdown to first element (this essentially resets
//the course dropdown each time level of study dropdown is changed
coursesDropdown.selectedIndex = 0;
//make sure all optgroups are hidden
element.style.display = 'none';
//only display optgroup whose label matches the value selected
//from first dropdown
if(element.getAttribute('label') == selectedLevelOfStudy){
element.style.display = 'block';
}
})
}
label {
font-family: sans-serif;
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
#cour optgroup {
display:none;
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<label for="school-select">Choose levels of study:</label>
<select id="level-select">
<option value="">--Please choose an option--</option>
<option value="bachelors">Bachelors</option>
<option value="postgraduates">Postgraduates</option>
<option value="phd">PhD</option>
</select>
</form>
<br>
<form id="form2" action="#">
<label for="course-select">Choose course:</label>
<select id="cour">
<option value="default"></option>
<optgroup label="bachelors">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>
<optgroup label="postgraduates">
<option>computer</option>
<option>biology</option>
<option>accounting</option>
</optgroup>
<optgroup label="phd">
<option>business</option>
<option>fisheries</option>
<option>agric</option>
</optgroup>
</select>
</form>
label {
font-family: sans-serif;
font-size: 1rem;
padding-right: 10px;
}
select {
font-size: .9rem;
padding: 2px 5px;
}
<h2>This is a form</h2>
<p>Online Application:</p>
<form id="form1" action="#">
<script lang="javascript">
function onLevelofStudyChange()
{
var selectedLevel=document.getElementById("level-select").value;
var course = document.querySelector("#cour");
var alloption = course.querySelectorAll('optgroup')
var getByLabel = course.querySelector('[label="'+selectedLevel+'"]');
//Hide all Optgroups
alloption.forEach(function(element){
element.style.display = "none";
});
if(getByLabel!=null)
getByLabel.style.display = "block";
}
</script>
<label for="school-select">Choose levels of study:</label>
<select id="level-select" onchange="onLevelofStudyChange()">
<option value="">--Please choose an option--</option>
<option value="bachelor">Bachelors</option>
<option value="postgraduates">Postgraduates</option>
<option value="phd">PhD</option>
</select>
</form>
<br>
<form id="form2" action="#">
<label for="course-select">Choose course:</label>
<select id="cour">
<option>--Please Choose course--</option>
<optgroup label="bachelor" style="display:none">
<option>Microbiology</option>
<option>chemistry</option>
<option>physics</option>
</optgroup>
<optgroup label="postgraduates" style="display:none">
<option>computer</option>
<option>biology</option>
<option>accounting</option>
</optgroup>
<optgroup label="phd" style="display:none">
<option>business</option>
<option>fisheries</option>
<option>agric</option>
</optgroup>
</select>
</form>
Try this, it should work also note I have changed Optgroup label inorder to match the value of first dropdown

get the selected value of the select box

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>

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.

Change select box options upon selecting option in first select box

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>

How to use multiple conditional in jquery? Use both IF OR in jquery

I am trying IF with OR in jquery but only "Returns" is working. "In Process" is not working. Help needed.
$('.target').change(function() {
if (($(this).find('option:selected').val() == 'Returns') || ($(this).find('option:selected').val() == 'In Process')) {
$(".answer").show('slow');
}
else{
$(".answer").hide('slow');
}
});
Use .val() to get the selected value of a select element. Have a look below, it's working perfectly fine
$('.target').change(function() {
if ($(this).val() == 'Returns' || $(this).val() == 'In Process') {
$(".answer").show('slow');
}
else{
$(".answer").hide('slow');
}
});
.answer{
height:50px;
border:1px solid #333;
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="target">
<option value="">select</option>
<option value="Returns">Returns</option>
<option value="In Process">In Process</option>
</select>
<br>
<div class="answer"></div>
You can create an array of all correct values and if selected value exists in array, show answer else hide.
You can also use .toggle(expression) to control visibility.
Sample:
$('.target').change(function() {
var valid = ["Returns", "In Process"];
var value = $('option:selected', this).val().trim();
$(".answer").toggle(valid.indexOf(value) > -1)
});
.answer {
height: 50px;
border: 1px solid #333;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="target">
<option value="">select</option>
<option value="Returns">Returns</option>
<option value="In Process">In Process</option>
</select>
<br>
<div class="answer">Answer</div>

Categories

Resources