How to add value into option using javascript - 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>

Related

Document.write method

So, I'm trying to make a JS action where it should display the selected items from the list, I can only select one but I want to select more than one and view it in a list
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
<script>
var output = '';
let issues = document.getElementById("issue");
for (i = 0; i < issues.length; i++) {
output += document.write("<li>" + issues[i].text + </li>").innerHTML = issues;
}
</script>
</ul>
</body>
You need to use an event listener to listen for a change of selection and you need to update the html of the element. You rarely ever want to use document.write in an application.
const issueSelect = document.getElementById("issue");
// listen for a change
issueSelect.addEventListener("change", selChanged);
function selChanged() {
var output = '';
let issues = issueSelect.options;
// loop over the options
for (var i = 0; i < issues.length; i++) {
// is it selected?
if (issues[i].selected) {
// yes, build a list item
output += "<li>" + issues[i].value + "</li>";
}
}
// set the list's content
document.getElementById("issue-type").innerHTML = output;
}
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
</body>
How I would have coded it
const issueSelect = document.getElementById("issue");
// listen for a change
issueSelect.addEventListener("change", selChanged);
function selChanged() {
const selectedOpts = issueSelect.querySelectorAll("option:checked");
const output = [...selectedOpts].map(opt => `<li>${opt.value}</li>`).join('');
document.getElementById("issue-type").innerHTML = output;
}
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
</body>
Here is one solution and I commented each line.
let output = '';
let issues = document.querySelector("#issue");
let issue_types = document.querySelector("#issue-type");
issues.addEventListener("change", function(e) { //change event listener to check for when the select is changed
issue_types.innerHTML = ""; //empties destination div
let options = e.target.selectedOptions; //grabs the selected options
options = Array.from(options).map(({ value }) => value); //converts the selected options to an array of values
options.forEach(function(opt){ //loops through the options
let li = document.createElement("li"); //creates a LI element
li.innerHTML = opt; //sets the innerHTML of the list item to the option
issue_types.appendChild(li) //appends the list to the destination UL
});
});
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>

Adding values from dropdown to table javascript

Whenever the user clicks on a value in the drop down, I want to create a table with the values in it. When you unchecked the checkbox, it should dissapper from the table. The problem that I have is that, it keeps appending the selection like this:
This is how it should look like:
This is my asp code. I also would like to target a specific table by it's ID. because I'll have about 20 dropdown in this page.
<asp:ListBox ID="ddlRolePosition" AutoPostBack="false" runat="server"
SelectionMode="Multiple" class="selectpicker show-tick form-control show-tick"
multiple data-validation-event="change" style="display: none;">
</asp:ListBox>
<table>
<tbody>
</tbody>
</table>
$("[id$=ddlRolePosition]").change(function() {
if (!$("[id$=ddlRolePosition]").val()) {
}
else {
var markup = "<tr><td>" + $("[id$=ddlRolePosition]").val() + "</td></tr>";
$("table tbody").append(markup);
}
});
You can:
Wrap the select and table elements so you can access many on a single page
Grab the selected options via select.selectedOptions
Added an empty() method that mimics jQuery.fn.empty
Added a triggerEvent() method that mimics jQuery.fn.trigger
// Add event listeners
Array.from(document.querySelectorAll('.preview-combo select')).forEach(combo => {
combo.addEventListener('change', onComboChange);
});
// Pre-select some options...
let combo = document.querySelectorAll('.preview-combo select');
combo[0].options[0].selected = true; // First combo, first option
combo[0].options[1].selected = true; // First combo, second option
combo[1].options[1].selected = true; // Second combo, second option
combo[1].options[2].selected = true; // Second combo, third option
// Fire change events (for initial loading only)
Array.from(combo).forEach(combo => triggerEvent(combo, 'change'))
function onComboChange(e) {
let select = e.target, table = select.parentElement.querySelector('table'),
values = Array.from(select.selectedOptions).map(opt => opt.value);
appendRows(table, values);
}
function appendRows(table, values) {
let tbody = empty(table.querySelector('tbody'));
values.forEach((value) => {
let tr = document.createElement('tr'), td = document.createElement('td');
td.textContent = value; tr.appendChild(td); tbody.appendChild(tr);
});
return table;
}
function triggerEvent(el, eventName) {
var event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, false);
el.dispatchEvent(event);
return el;
}
function empty(el) {
var range = document.createRange();
range.selectNodeContents(el);
range.deleteContents();
return el;
}
.preview-combo {
display: inline-block;
}
.preview-combo select {
width: 100px;
}
<div class="preview-combo">
<select multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table class="selected-values">
<tbody><tr><td><em>Results</em></td></tr></tbody>
</table>
</div>
<div class="preview-combo">
<select multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table class="selected-values">
<tbody><tr><td><em>Results</em></td></tr></tbody>
</table>
</div>
jQuery + Bootstrap
Here is an example with jQuery.
(($) => {
$.fn.selectedValues = function() {
return this.find('option:selected').map((i, opt) => opt.value).get();
};
})(jQuery);
$('select').selectpicker(); // Convert to a picker.
// Add event listeners
$('.preview-combo select').on('change', onComboChange);
// Pre-select some options...
let $combo = $('.preview-combo select');
$combo.get(0).options[0].selected = true; // First combo, first option
$combo.get(0).options[1].selected = true; // First combo, second option
$combo.get(1).options[1].selected = true; // Second combo, second option
$combo.get(1).options[2].selected = true; // Second combo, third option
// Fire change events (for initial loading only)
$('.preview-combo select').trigger('change');
function onComboChange(e) {
let $sel = $(e.target);
populateTable($sel.closest('.preview-combo').find('table'), $sel.selectedValues());
}
function populateTable($table, values) {
return $table.find('tbody').empty().append(values.map(value => {
return $('<tr>').append($('<td>').text(value));
}));
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm">
<div class="preview-combo">
<select multiple class="form-control">
<option value="1">Audit Assistant</option>
<option value="2">Audit Expert</option>
<option value="3">Auditor</option>
</select>
<table class="selected-values">
<tbody><tr><td><em>Results</em></td></tr></tbody>
</table>
</div>
</div>
<div class="col-sm">
<div class="preview-combo">
<select multiple class="form-control">
<option value="1">Audit Assistant</option>
<option value="2">Audit Expert</option>
<option value="3">Auditor</option>
</select>
<table class="selected-values">
<tbody><tr><td><em>Results</em></td></tr></tbody>
</table>
</div>
</div>
</div>
</div>
I'd approach this differently and rather keep an array of selected items and then pass those to a function that should generate the rows of the table.
See example below that can be applied:
let target = document.querySelector('#target');
function generateRows(items) {
// clear the rows
target.innerHTML = '';
let rows = '';
for(let i = 0; i <items.length; i++) {
rows += `<tr><td>${items[i]}</td></tr>`;
}
// append once
target.innerHTML = rows;
}
document.querySelector('.select').onchange = function (e) {
let items = [];
for (var i= 0; i < e.currentTarget.options.length; i++) {
let opt = e.currentTarget.options[i];
if (opt.selected) {
items.push(opt.value);
}
}
// pass the selected items to function to generate the rows
generateRows(items);
};
<select class="select" multiple style="width: 100px;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table>
<tbody id="target">
<tr><td>rows here</td></tr>
</tbody>
</table>

adding and removing text to a span populated from a dropdown

Here is my jsfiddle:
The end result I am wanting is that once you make a selection from each dropdown, the selection appears in the first line of text, and then get's reversed in the 2nd line of text. However, the apostrophe S needs to remain in the first spot. So for example, if you selected "Mother" from the first dropdown, and "Father" from the 2nd drop down, the two lines of text should look like this:
My Mother's Father
My Father's Mother
I don't know how to swap the apostrophe S so that it remains so that it comes first.
I tried using:
document.getElementById('third').innerHTML = strUser2 + "'s";
but that causes the apostrophe s to appear before I have anything selected.
That's because to run two functions before selecting. Remove them and try.
function functionOne() {
var e = document.getElementById("dropdown_1");
var strUser = e.options[e.selectedIndex].value;
document.getElementById('first').innerHTML = strUser;
document.getElementById('fourth').innerHTML = strUser.replace("'s", '');
}
document.getElementById("dropdown_1").onchange = functionOne;
function functionTwo() {
var e = document.getElementById("dropdown_2");
var strUser = e.options[e.selectedIndex].value;
var strUser2 = e.options[e.selectedIndex].value;
document.getElementById('second').innerHTML = strUser;
document.getElementById('third').innerHTML = strUser2+ "'s";
}
document.getElementById("dropdown_2").onchange = functionTwo;
span#first,
span#second,
span#third,
span#fourth {
min-width: 40px;
display: inline-block;
border-bottom: solid 1px;
height: 18px;
vertical-align: bottom;
}
<select class="text_select" id="dropdown_1" name="dropdown_1">
<option value="">- Select -</option>
<option value="Father's">Father's</option>
<option value="Mother's">Mother's</option>
<option value="Sister's">Sister's</option>
<option value="Brother's">Brother's</option>
</select>
<select class="text_select" id="dropdown_2" name="dropdown_2">
<option value="">- Select -</option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
<option value="Sister">Sister</option>
<option value="Brother">Brother</option>
</select>
<br /><br />
<label class="row_1">My <span id="first"></span> <span id="second"></span></label>
<br />
<label class="row_2">My <span id="third"></span> <span id="fourth"></span></label>
I would change the values in the option tags, but keep the display the same. Ex: <option value="Father">Father's</option>
Then append 's after the values you want to have 's.
Also don't execute each function by default, only execute them onchange. That way you'll never get something like 's when the page loads.
I would then make sure - Select - is the first option (selected) for both option tags, but make them disabled so the user cannot choose those as options.
--note--
I would strongly recommend using textContent as supposed to innerHTML to avoid possible code injection, depending on what you're using this for.
function functionOne(){
var e = document.getElementById("dropdown_1");
var strUser = e.options[e.selectedIndex].value;
document.getElementById('first').textContent = strUser + "'s";
document.getElementById('fourth').textContent = strUser;
}
document.getElementById("dropdown_1").onchange = functionOne;
function functionTwo(){
var e = document.getElementById("dropdown_2");
var strUser = e.options[e.selectedIndex].value;
var strUser2 = e.options[e.selectedIndex].value;
document.getElementById('second').textContent = strUser;
document.getElementById('third').textContent = strUser2 + "'s";
}
document.getElementById("dropdown_2").onchange = functionTwo;
span#first, span#second, span#third, span#fourth{
min-width:40px;
display:inline-block;
border-bottom:solid 1px;
height:18px;
vertical-align:bottom;
}
<select class="text_select" id="dropdown_1" name="dropdown_1">
<option value="" disabled selected>- Select -</option>
<option value="Father">Father's</option>
<option value="Mother">Mother's</option>
<option value="Sister">Sister's</option>
<option value="Brother">Brother's</option>
</select>
<select class="text_select" id="dropdown_2" name="dropdown_2">
<option value="" disabled selected>- Select -</option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
<option value="Sister">Sister</option>
<option value="Brother">Brother</option>
</select>
<br /><br />
<label class="row_1">My <span id="first"></span> <span id="second"></span></label>
<br />
<label class="row_2">My <span id="third"></span> <span id="fourth"></span></label>
Simple solution:
Remove the apostrophe's from the list values and add on the string only if defined:
document.getElementById('first').innerHTML = strUser+(strUser ? "'s" : "");
document.getElementById('third').innerHTML = strUser2+(strUser2 ? "'s" : "");
Fiddle here
EDIT - New solution:
Full code solution keeping the 2 lines from populating until both dropdowns are selected, as requested:
var firstSelect = false;
var secondSelect = false;
var dd1 = document.getElementById("dropdown_1");
var dd2 = document.getElementById("dropdown_2");
function clearAllContainers(){
document.getElementById('first').innerHTML = '';
document.getElementById('second').innerHTML = '';
document.getElementById('third').innerHTML = '';
document.getElementById('fourth').innerHTML = '';
}
function updateAllContainers(){
var strUser = dd1.options[dd1.selectedIndex].value;
document.getElementById('first').innerHTML = strUser+(strUser ? "'s" : "");
document.getElementById('fourth').innerHTML = strUser;
var strUser2 = dd2.options[dd2.selectedIndex].value;
document.getElementById('second').innerHTML = strUser2;
document.getElementById('third').innerHTML = strUser2+(strUser2 ? "'s" : "");
}
function functionOne(){
if(dd1.options[dd1.selectedIndex].value){
firstSelect = true;
}else{
firstSelect = false;
}
if(secondSelect && dd1.options[dd1.selectedIndex].value != ''){
updateAllContainers();
}else{
clearAllContainers();
}
}
functionOne()
document.getElementById("dropdown_1").onchange = functionOne;
function functionTwo(){
if(dd2.options[dd2.selectedIndex].value){
secondSelect = true;
}else{
secondSelect = false;
}
if(firstSelect && dd2.options[dd2.selectedIndex].value != ''){
updateAllContainers();
}else{
clearAllContainers();
}
}
functionTwo()
document.getElementById("dropdown_2").onchange = functionTwo;
<select class="text_select" id="dropdown_1" name="dropdown_1">
<option value="">- Select -</option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
<option value="Sister">Sister</option>
<option value="Brother">Brother</option>
</select>
<select class="text_select" id="dropdown_2" name="dropdown_2">
<option value="">- Select -</option>
<option value="Father">Father</option>
<option value="Mother">Mother</option>
<option value="Sister">Sister</option>
<option value="Brother">Brother</option>
</select>
<br /><br />
<label class="row_1">My <span id="first"></span> <span id="second"></span></label>
<br />
<label class="row_2">My <span id="third"></span> <span id="fourth"></span></label>
Updated fiddle for final solution is here.
I looked at your Javascript file on JSFiddle. The solution is very simple. First you'll have to remove apostrophe s from the content of <span id="fourth"></span>
You can do that easily by slicing off last two characters from the content of that span. Here is how you need to do it.
document.getElementById('fourth').innerHTML = strUser.slice(0, strUser.length - 2);
Now, the next part is to add apostrophe s in the content of <span id="third"></span>.
But you'll have to make sure that if the content of the span is empty then it should not append apostrophe s.
For that you can check whether on not the content is empty and if not empty then you can append apostrophe s.
Here is how you can do it.
document.getElementById('third').innerHTML = (strUser)? strUser + '\'s':strUser;
Here is the overall modified code of your Javascript file.
function functionOne(){
var e = document.getElementById("dropdown_1");
var strUser = e.options[e.selectedIndex].value;
document.getElementById('first').innerHTML = strUser;
document.getElementById('fourth').innerHTML = strUser.slice(0, strUser.length - 2);
}
functionOne();
document.getElementById("dropdown_1").onchange = functionOne;
function functionTwo(){
var e = document.getElementById("dropdown_2");
var strUser = e.options[e.selectedIndex].value;
//var strUser2 = e.options[e.selectedIndex].value;
document.getElementById('second').innerHTML = strUser;
document.getElementById('third').innerHTML = (strUser)? strUser + '\'s':strUser;
}
functionTwo()
document.getElementById("dropdown_2").onchange = functionTwo;

Javascript onchange with select element

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>

Updating two select boxes with same information

I have two select boxes. Only the second select is being updated.
If I remove the ff.add the tf.add works.
function copyToFrame(selectedOption) {
if (selectedOption == "New") {
var tf = document.getElementById("sCopyToFrame");
var option = document.createElement("option");
document.getElementById('copyToFrameCounter').value = parseInt(document.getElementById('copyToFrameCounter').value) + 1;
option.text = "Frame " + document.getElementById('copyToFrameCounter').value;
tf.add(option);
var ff = document.getElementById("sCopyFromFrame");
ff.add(option);
}
}
<INPUT type="hidden" id="copyToFrameCounter" value="0">
<p> Copy to frame:
<select id="sCopyToFrame" onchange="copyToFrame(this.value);">
<option selected disabled hidden style='display: none' value=''></option>
<option>New</option>
</select>
</p>
<p> Copy from frame:
<select id="sCopyFromFrame">
<option selected disabled hidden style='display: none' value=''></option>
<option></option>
</select>
</p>
If you want to add new option to both of the drop downs, you need two elements
function copyToFrame(selectedOption){
if(selectedOption == "New"){
var tf = document.getElementById("sCopyToFrame");
var tf_option = document.createElement("option");
document.getElementById('copyToFrameCounter').value = parseInt(document.getElementById('copyToFrameCounter').value) + 1;
tf_option.text = "Frame " + document.getElementById('copyToFrameCounter').value;
tf.add(tf_option);
var ff = document.getElementById("sCopyFromFrame");
var ff_option = tf_option.cloneNode(true);
ff.add(ff_option);
}
}
function copyToFrame(selectedOption) {
if (selectedOption == "New") {
var tf = document.getElementById("sCopyToFrame");
var ff = document.getElementById("sCopyFromFrame");
var option = document.createElement("option");
var optionCopy = document.createElement("option");
var cTFC = parseInt(document.getElementById('copyToFrameCounter').value) + 1 || 0;
option.text = "Frame " + cTFC;
optionCopy.text = "Frame " + cTFC;
tf.add(option);
ff.add(optionCopy);
}
}
<input type="hidden" id="copyToFrameCounter" value="0">
<p> Copy to frame:
<select id="sCopyToFrame" onchange="copyToFrame(this.value);">
<option selected disabled hidden style='display: none' value=''></option>
<option>New</option>
</select>
</p>
<p> Copy from frame:
<select id="sCopyFromFrame">
<option selected disabled hidden style='display: none' value=''></option>
<option></option>
</select>
</p>

Categories