Javascript onchange with select element - javascript

I am trying to create a dropdown menu and when one option is selected a div appears. All the divs are set to display none, When one option is clicked I would like to change that style to display: block. So far I have used onchange but that only applies to the whole select element and not the specific options.
So what are my choices for changing the display to block when clicking on a certain option of a select element?
This is my code
#card1, #card2, #card3 {
display: none;
}
<select name="" id="" onchange="showOnChange()">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1">card1</div>
<div id="card2">card2</div>
<div id="card3">card3</div>
<script>
function showOnChange() {
document.getElementById('card1').style.display = "block";
}
</script>

I little bit updated your html and js function as well, see below please if work for you:
<select name="" id="" onChange="showOnChange(this)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
And JS part:
function showOnChange(self) {
var allDiv = self.options;
for(var i = 0; i < allDiv.length; i++){
document.getElementById(allDiv[i].value).style.display = "none";
}
document.getElementById(self.value).style.display = 'block';
}

You could get the value from the card that you select and show that id
#card1, #card2, #card3 {
display: none;
}
<select name="" id="" onchange="showOnChange(this)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1">card1</div>
<div id="card2">card2</div>
<div id="card3">card3</div>
<script>
function showOnChange(element) {
var value = element.value
document.getElementById(value).style.display = "block";
}
</script>
Note the this keyword added to the select onchange function

You can catch which option is selected in your onChange and then based on that you can show your div.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<style>
#card1{
display:block;
}
#card2, #card3 {
display: none;
}
</style>
<select name="" id="slct" onchange="showOnChange(event)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1">card1</div>
<div id="card2">card2</div>
<div id="card3">card3</div>
<script>
function showOnChange(e) {
var elem = document.getElementById("slct");
var value = elem.options[elem.selectedIndex].value;
if(value == "card1")
{
document.getElementById('card1').style.display = "block";
document.getElementById('card2').style.display = "none";
document.getElementById('card3').style.display = "none";
}
else if(value == "card2")
{
document.getElementById('card1').style.display = "none";
document.getElementById('card2').style.display = "block";
document.getElementById('card3').style.display = "none";
}
else if(value == "card3")
{
document.getElementById('card1').style.display = "none";
document.getElementById('card2').style.display = "none";
document.getElementById('card3').style.display = "block";
}
}
</script>
</body>
</html>
Please check below link for the jsbin
https://jsbin.com/memilufogi/edit?html,output

you have to pass the value of select in showOnChange function or you can get in the function as well
function showOnChange(val) {
document.getElementById(val).style.display = "block";
}
#card1, #card2, #card3 {
display: none;
}
<select name="" id="" onchange="showOnChange(this.value)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1">card1</div>
<div id="card2">card2</div>
<div id="card3">card3</div>

You could give all your divs a class, so that you can query the DOM by that class and hide them all. Then you look for the div whose ID matches the selected option and show it.
See the attached snippets.
document.getElementById('cardMenu').addEventListener('change', showOnChange);
function showOnChange(evt) {
// capture the target of the change event : select element
var cardMenu = evt.target;
// hide all cards
var cards = document.getElementsByClassName('card');
for (var i = 0; i < cards.length; i++) {
cards[i].style.display = "none";
}
// show the card whose id matches the selected value
document.getElementById(cardMenu.value).style.display = "block";
}
#card1,
#card2,
#card3 {
display: none;
}
<select name="cardMenu" id="cardMenu">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div class="card" id="card1">card1</div>
<div class="card" id="card2">card2</div>
<div class="card" id="card3">card3</div>

CSS
<style>
#card1, #card2, #card3 {
display: none;
}
</style>
HTML
<!-- Pass current selected value -->
<select name="" id="" onchange="showOnChange(this.value)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<!-- Add common class in every property -->
<!-- Class will help to reset all class display none when selected new option -->
<div id="card1" class="div_cls">card1</div>
<div id="card2" class="div_cls">card2</div>
<div id="card3" class="div_cls">card3</div>
JS
<script>
function showOnChange(div_id) {
var div_id = div_id;
/*
Getting lenght of all div
*/
var div_len = document.getElementsByClassName("div_cls").length;
/* run loop and reset all div display to none*/
for(i=0; i< div_len; i++) {
document.getElementsByClassName("div_cls")[i].style.display = "none";
}
// Now set block for current selected option
document.getElementById(div_id).style.display = "block";
}
</script>

Just with javascript:
function showOnChange() {
var whichOp = document.getElementById("sel").selectedIndex;
var c = document.getElementsByClassName("card");
for (len = 0;len < c.length; len++)
c[len].style.display = "none";
c[whichOp].style.display = "block";
}
#card1, #card2, #card3 {
display: none;
margin-top: 10px;
}
<select name="" id="sel" onchange="showOnChange()">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1" class="card">card1</div>
<div id="card2" class="card">card2</div>
<div id="card3" class="card">card3</div>

Related

How to add value into option using javascript

Here is my code for js
function addTag(tag) {
var tags = document.getElementById("tags");
var span = document.createElement("span");
span.textContent = tag.value;
tag.value = "";
span.setAttribute("onclick", "this.remove()");
tags.append(span);
}
function addOption() {
var x = document.getElementById("tag");
var option = document.createElement("option");
option.textContent = tags.textContent;
x.add(option);
}
Once the user click on the tags it will close can should display the value to the option but, I only manage to create a blank space inside the option.
Here is related JS Fiddle
Changed tags span to contain all option spans.
Then made each span inside tags responsible to add itself back to select and remove itself from tags span.
Please see the changes in the code as per above logic.
function addTag(tag) {
var tags = document.getElementById("tags");
var span = document.createElement("span");
span.textContent = tag.value;
tag.value = ""; //clear the field when choose or pressed enter key
span.style.backgroundColor = "#E5E6E7";
span.style.margin = " 5px";
span.style.padding = "5px";
//span will add itself back to select and remove itself from tags
span.setAttribute("onclick", "addOption(this)");
if (span.textContent == "Fast Food") {
$('option[value="Fast Food"]').remove();
} else if (span.textContent == "Vegan") {
$('option[value="Vegan"]').remove();
} else {
$('option[value="Food"]').remove();
}
tags.append(span);
}
function addOption(span) {
var x = document.getElementById("tag");
var option = document.createElement("option");
option.textContent = span.textContent;
x.add(option);
span.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<div class="form-group">
<label class="control-label">Food Type</label><br>
<span id="tags"></span>
<select id="tag" onchange="addTag(this)" class="form-control">
<option value="">-All-</option>
<option value="Fast Food">Fast Food</option>
<option value="Vegan">Vegan</option>
<option value="Food">Food</option>
</select>
</div>
</div>
Since you're using jQuery, we can make use of the event system. This makes for cleaner code.
The main issue with your code is that you were trying to get textContent of tags which *doesn't exist as a variable. Instead it will reference the id="tags" element.
textContent only returns the text value of that element, not its children. In this case it is empty.
// here we use jQuery's event system to define what happens
// for the events below
$(document)
.on("click", ".tag", function(){
removeTag(this);
})
.on("change", "#tag", function(){
addTag(this);
});
function removeTag(tag){
addOption(tag.textContent);
tag.remove();
}
function addTag(tag) {
var tags = document.getElementById("tags"),
span = document.createElement("span");
span.textContent = tag.value;
tag.value = ""; //clear the field when choose or pressed enter key
// could you add the following styles as a class?
span.style.backgroundColor = "#E5E6E7";
span.style.margin = "5px";
span.style.padding = "5px";
span.className = "tag";
// no need to set `onclick` here as we're handling at the top of this code
// we can use the text to find the element
// instead of a repeating if else statment
$('option[value="' + span.textContent + '"]').remove();
tags.append(span);
}
function addOption(text) {
var x = document.getElementById("tag"),
option = document.createElement("option");
option.textContent = text;
// we also need to set the value here
// since we're looking for it in `addTag`
option.value = text
x.add(option);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<div class="form-group">
<label class="control-label">Food Type</label><br>
<span id="tags"></span>
<select id="tag" class="form-control">
<option value="">-All-</option>
<option value="Fast Food">Fast Food</option>
<option value="Vegan">Vegan</option>
<option value="Food">Food</option>
</select>
</div>
</div>
ES6 and improvements
$(document)
.on("click", ".tag", (event) => removeTag(event.currentTarget))
.on("change", "#tag", (event) => addTag(event.currentTarget));
function removeTag(tag){
addOption(tag.textContent);
tag.remove();
}
function addTag(tag) {
let tags = $("#tags"),
span = $('<span class="tag" />');
span.text(tag.value);
tag.value = ""; //clear the field when choose or pressed enter key
// we can use the text to find the element
// instead of a repeating if else statment
$(`option[value="${span[0].textContent}"]`).remove();
tags.append(span);
}
function addOption(text) {
let x = $("#tag"),
option = $('<option />');
option
.text(text)
.val(text);
x.append(option);
}
.tag {
background-color: #E5E6E7;
margin: 5px;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<div class="form-group">
<label class="control-label">Food Type</label><br>
<span id="tags"></span>
<select id="tag" class="form-control">
<option value="">-All-</option>
<option value="Fast Food">Fast Food</option>
<option value="Vegan">Vegan</option>
<option value="Food">Food</option>
</select>
</div>
</div>
You had made some logical mistakes,
You can update the fiddle as follows:
function addTag(tag) {
var tags = document.getElementById("tags");
var span = document.createElement("span");
span.textContent = tag.value;
span.setAttribute("onclick", "removeTag(this);");
tag.options[tag.selectedIndex].remove();
tags.append(span);
}
function removeTag(elm) {
elm.remove();
var x = document.getElementById("tag");
var option = document.createElement("option");
option.textContent = elm.textContent;
x.add(option);
}
#tags span{
background-color: #E5E6E7;
margin:5px;
padding:5px;
cursor: pointer;
}
<div class="col-sm-3">
<div class="form-group">
<label class="control-label">Food Type</label><br>
<span id="tags"></span>
<select id="tag" onchange="addTag(this)" class="form-control">
<option value="">-All-</option>
<option value="Fast Food">Fast Food</option>
<option value="Vegan">Vegan</option>
<option value="Food">Food</option>
</select>
</div>
</div>

Selecting HTML select result in null, when reading the current option

I am trying to hide the elements with class furniture or book if DVD disc is selected. I want to do that dynamically, but in console, it shows, that it Cannot read property 'value' of null However, every option has a value, and that's strange. And of course, because of that, nothing is being changed
HTML select code:
<div class="iRow">
<div class="lclass"> <label for="typeselector">Product Category</label> </div>
<div class="tclass">
<select id="typeselector" name="productoptions">
<option value="DVD">DVD-Disc</option>
<option value="Book">Book</option>
<option value="Furniture">Furniture</option>
</select>
</div>
</div>
JS code:
<script>
var opt = document.getElementById("typeselector");
console.log(opt.value);
if(opt === "DVD-Disc")
{
console.log(document.getElementsByClassName("furniture"));
document.getElementsByClassName("furniture").style.display = "none";
document.getElementsByClassName("book").style.display = "none";
}
</script>
There are several issues:
getElementsByClassName returns a list, therefore, you loop over each element and hide it
There are no elements with such classes in the question
You should compare the value of the select
var opt = document.getElementById("typeselector");
if(opt.value === "DVD")
{
let furnitures = document.getElementsByClassName("furniture");
for(let i = 0; i < furnitures.length; i++)
furnitures[i].style.display = "none";
let books = document.getElementsByClassName("book");
for(let i = 0; i < books.length; i++)
books[i].style.display = "none";
}
<div class="iRow">
<div class="lclass">
<label for="typeselector">Product Category</label>
</div>
<div class="tclass">
<select id="typeselector" name="productoptions">
<option value="DVD">DVD-Disc</option>
<option value="Book">Book</option>
<option value="Furniture">Furniture</option>
</select>
</div>
</div>
<div class="book">Book 1</div>
<div class="book">Book 2</div>
<div class="furniture">furniture 1</div>
<div class="furniture">furniture 1</div>
The right way would be to set a listener on the select:
var opt = document.getElementById("typeselector");
opt.addEventListener("change", function(){
console.log(this.value)
if(this.value === "DVD"){
let furnitures = document.getElementsByClassName("furniture");
for(let i = 0; i < furnitures.length; i++)
furnitures[i].style.display = "none";
let books = document.getElementsByClassName("book");
for(let i = 0; i < books.length; i++)
books[i].style.display = "none";
}
});
<div class="iRow">
<div class="lclass">
<label for="typeselector">Product Category</label>
</div>
<div class="tclass">
<select id="typeselector" name="productoptions">
<option value="DVD">DVD-Disc</option>
<option class="book" value="Book">Book</option>
<option class="furniture" value="Furniture">Furniture</option>
</select>
</div>
</div>
The problem is here:
if(opt === "DVD-Disc")
You need to ask:
if(opt.Value === "DVD")
Also, when the page first loads, the DVD option is first, so it doesn't fire the on change event. If you select Book, then select DVD, the javascript below will fire in the working example:
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function OnSelectionChange(select) {
var opt = document.getElementById("typeselector");
console.log(opt.value);
if (opt.value === "DVD") {
console.log("DVD Selected");
console.log(document.getElementsByClassName("furniture"));
document.getElementsByClassName("furniture").style.display = "none";
document.getElementsByClassName("book").style.display = "none";
}
}
</script>
</head>
<body>
<div class="iRow">
<div class="lclass"> <label for="typeselector">Product Category</label> </div>
<div class="tclass">
<select id="typeselector" name="productoptions" onchange="OnSelectionChange (this)">
<option value="DVD">DVD-Disc</option>
<option value="Book">Book</option>
<option value="Furniture">Furniture</option>
</select>
</div>
</div>
</body>
</html>

How to add another identical dropdown list?

Hi I have this very simple code to go along with a revision timetabler I am creating for a school project. It's just a simple dropwdown list that allows the user to select the subjects they do. How would I add a button that creates another identical list below so the user can add more than 1 subject if they wish?
<!doctype html>
<html>
<head>
<title>Select your subjects</title>
<select id="subject1" name="subject1">
<option value="Maths">Maths</option>
<option value="Physics">Physics</option>
<option value="English">English</option>
<option value="Compting">Computing</option>
</select>
</head>
<body>
</body>
</html>
Something like this?
Note that I've changed the name of the select to be an array[]. So when you're processing the data on the server end, just note you'll be handling an array of element and not subject1, subject2, subject3, etc.
function addCourse() {
document.getElementById("subjects").innerHTML += '\
<br><select name="subject[]">\
<option value="Maths">Maths</option>\
<option value="Physics">Physics</option>\
<option value="English">English</option>\
<option value="Compting">Computing</option>\
</select>';
}
addCourse();
document.getElementById("add").addEventListener("click", addCourse);
<!doctype html>
<html>
<head>
</head>
<body>
<form method="post" action="">
<title>Select your subjects</title>
<div id="subjects">
</div>
</form>
<input type="button" id="add" value="Add Course">
</body>
</html>
I'd actually recommend a dropdown to specify how many lists the user wants. So something like this would be better:
var maxCourses = 5;
var select = document.getElementById("num");
var subjects = document.getElementById("subjects");
var previous = 1;
for (var i = 1; i <= maxCourses; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
select.addEventListener("change", function() {
var diff = select.value - previous;
for (var i = 0; i < Math.abs(diff); i++)
if (diff > 0)
addCourse();
else
removeCourse();
previous = select.value;
});
function addCourse() {
subjects.innerHTML += '\
<select name="subject[]">\
<option value="Maths">Maths</option>\
<option value="Physics">Physics</option>\
<option value="English">English</option>\
<option value="Compting">Computing</option>\
</select>';
}
function removeCourse() {
subjects.removeChild(subjects.lastChild);
}
addCourse();
select {
display: block;
}
<!doctype html>
<html>
<head>
</head>
<body>
<form method="post" action="">
<title>Select your subjects</title>
Number of Courses:
<select id="num"></select><br>
<div id="subjects">
</div>
</form>
</body>
</html>

displaying Multiple select option in diiferent line

I have a multiple select option that display the result in a div container, when click on ctrl+"orange""apple""banana" the result display: "orange, apple, banana" in one line, but i want to display each result in a new single line with a link that goes to different page like this:
Orange - "goes to a link"
Apple - "goes to a link"
Banana - "goes to a link"
Here are my codes below:
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript">
</script>
<select name="" multiple="multiple" id="select-custom-19">    
<option>Add Fruits</option>        
<option value="orange" selected>orange</option> 
<option value="apple">apple</option>
<option value="banana">banana</option>             </select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').text($(this).val());
});
});
</script>
your help will be highly appreciated.
Thanks
You can try adding <br/> element after every selected option. I have used <label> element but you can add link or any other element you want
$(document).ready( function ()
{
$('#select-custom-19').change(function(){
$('#yourfruit').empty();
var values = $(this).val();
for(var i=0; i < values.length ; i++)
{
$('#yourfruit').append('<lable>'+values[i]+'</label><br/>');
}
});
});
JSFiddle Demo
You can iterate throug items and display them, append an anchor (<a />) and use <br /> for a new line.
Make sure to add .empty() to clean the fruits from list before .append() other items to $('#yourfruit'), like in example below.
var fruits = $(this).val();
$('#yourfruit').empty();
for (var fruit in fruits) {
var label = $('<label/> ').text(fruits[fruit]+" - ");
$('#yourfruit').append(label)
.append($('<a class="tab-btn" />').text(fruits[fruit]).attr('href', fruits[fruit] + '.html'))
.append('<br />');
}
$(document).ready(function() {
$('#select-custom-19').change(function() {
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
var fruits = $(this).val();
$('#yourfruit').empty();
for (var fruit in fruits) {
var label = $('<label/> ').text(fruits[fruit] + " - ");
$('#yourfruit').append(label)
.append($('<a class="tab-btn" />').text(fruits[fruit]).attr('href', fruits[fruit] + '.html'))
.append('<br />');
}
});
});
.tab-btn {
color: red;
}
.tab-btn:hover {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; ">
<span id="yourfruit"> </span>
</div>
try below
<script src="jquery-mobile/jquery-1.8.3.min.js" type="text/javascript"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903; color:#000000; margin: 10px; ">
<ul id="yourfruit">
</ul>
</div>
<script type="text/javascript">
$(document).ready( function ()
{
$('#select-custom-19').change(function()
{
/* setting currently changed option value to option variable */
var option = $(this).find('option:selected').val();
/* setting input box value to selected option value */
$('#yourfruit').append('<li>'+$(this).val()+'</li>');
}
);
});
</script>
You may add HTML tags as per your requirements, like <a> or </br>
$(document).ready(function () {
$('#select-custom-19').change(function () {
$('#yourfruit').text("");
if($(this).val() != null)
{
$(this).val().forEach(function (value, index) {
$('#yourfruit').append("<a href='#'>" + value + "</a></br>");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select name="" multiple="multiple" id="select-custom-19">
<option>Add Fruits</option>
<option value="orange" selected>orange</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
</select>
<div style="width:300px; height:70px; background-color:#E1D903;
color:#000000; margin: 10px; "> <span id="yourfruit"> </span>
</div>

HTML select dropdownlist with javascript function

This is how far I got:
<head>
<script type="text/javascript">
function showonlyone(thechosenone) {
var article = document.getElementsByTagName("div");
for(var x=0; x<article.length; x++) {
name = article[x].getAttribute("name");
if (name == 'article') {
if (article[x].id == thechosenone) {
article[x].style.display = 'block';
}
else {
article[x].style.display = 'none';
}
}
}
}
</script>
</head>
<form>
<select>
<option SELECTED>Choose one</option>
<option value="javascript:showonlyone(id1)">First</option> <!-- That's probably wrong -->
<option value="javascript:showonlyone(id2)">Second</option>
</select>
</form>
<div name="article" id="id1" style="display:none;">
First one selected
</div>
<div name="article" id="id2" style="display:none;">
Second one selected
</div>
Here is what it should do:
Create a dropdownlist (with 3 Values)
If you click on "First" it should only show the of the content of <div id="id1">
If you click on "Second" it should only show the of the content of <div id="id2">
I know that this can't work like this. But I do not know how I can get this working.
There might be a easier way than this javascript function but it has to be this way.
Thank you for your help
Use a onchange event handler instead:
Update your <select> to <select onchange="showonlyone(this)">.
Change your <option> values to only the IDs - not JavaScript calls.
Update your JavaScript to accept the HTMLSelectElement (which will be passed-in by the this, above). (Yes, you were correct here.)
From the chosen HTMLSelectElement, ask it for its value.
Here is a fixed, working version: http://jsfiddle.net/YRF6u/
Also included here:
<head>
<script type="text/javascript">
function showonlyone(selector) {
var thechosenone = selector.value;
var article = document.getElementsByTagName("div");
for(var x=0; x<article.length; x++) {
name = article[x].getAttribute("name");
if (name == 'article') {
if (article[x].id == thechosenone) {
article[x].style.display = 'block';
}else{
article[x].style.display = 'none';
}
}
}
}
</script>
</head>
<form>
<select onchange="showonlyone(this)">
<option SELECTED>Choose one</option>
<option value="id1">First</option>
<option value="id2">Second</option>
</select>
</form>
<div name="article" id="id1" style="display:none;">
First one selected
</div>
<div name="article" id="id2" style="display:none;">
Second one selected
</div>
I would not consider this production-ready code, but it should be sufficient enough to solve your current round of questions.

Categories