Show text based on option selected in dropdown - javascript

I have a dropdown like below.
<label for="form_name">Title</label>
<select class="bootstrap-select">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
<div><p>Text1</p></div>
<div><p>Text2</p></div>
<div><p>Text3</p></div>
<div><p>Text4</p></div>
I intend to show Text 1 when Feature 1 is selected, Text 2 when Feature 2 is selected and so on.
Any ideas on how can I do this with JS (or jQuery)?
P.S. Most existing solutions require input field rather than options field or maybe I am too noob. xD

Give the p tags the id as the value of the options, and show the p tag when selected option has the value which is equal to the id of p
$('p').hide();
$('#1').show();
$('select').change(function() {
$('p').hide();
var a = $(this).val();
$("#" + a).show();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="form_name">Title</label>
<select class="bootstrap-select">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
<div>
<p id="1">Text1</p>
</div>
<div>
<p id="2">Text2</p>
</div>
<div>
<p id="3">Text3</p>
</div>
<div>
<p id="4">Text4</p>
</div>

function display(){
var e = document.getElementById("dropDownId");
var index = e.selectedIndex;
if(index==0){
document.getElementById("first").style.display = 'block'
document.getElementById("second").style.display = 'none'
}
else if(index==1){
document.getElementById("first").style.display = 'none'
document.getElementById("second").style.display = 'block'
}
}
<label for="form_name">Title</label>
<select class="bootstrap-select" id="dropDownId" onchange="display()">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
</select>
<div id="first"><p>Text1</p></div>
<div id="second" style="display: none;"><p>Text2</p></div>
Please run this snippet..and check out your solution..

With pure javascript
let select = document.querySelector("select");
let divs = document.querySelectorAll("div");
let result = document.querySelector("#result");
function func1(par){
result.innerText = divs[par - 1].innerText;
}
div:not(#result) {
display:none;
}
<label for="form_name">Title</label>
<select class="bootstrap-select" onchange="func1(this.value)">
<option value="1" selected="selected">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>
<option value="4">Feature 4</option>
</select>
<div><p>Text1</p></div>
<div><p>Text2</p></div>
<div><p>Text3</p></div>
<div><p>Text4</p></div>
<div id="result"></div>

You can use ids on your div that you want to show and change the value of your select with the ids you choosed
$("#select-panel").change(function(){
updateDisplay();
})
function updateDisplay(){
var idToShow = $("#select-panel").find(":selected").val() || "div1";
$(".subcontent").each(function(){
$(this).css("display",$(this).is("#"+idToShow) ? 'block' : 'none');
})
}
updateDisplay();
.subcontent{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select-panel">
<option value="div1">1</option>
<option value="div2">2</option>
</select>
<div id="div1" class="subcontent">Text 1</div>
<div id="div2" class="subcontent">Text 2</div>

Related

How do I know the last unselected option from a multiselect dropdown?

I have a multi select Listbox
<div id="multiselectList">
<select>
<option value="option1">Val 1</option>
<option value="option2">Val 2</option>
<option value="option3">Val 3</option>
<option value="option4">Val 2</option>
<option value="option5">Val 3</option>
</select>
Suppose all the options are selected initially. Now I unselect option2 from multi select list. How can I know which option is currently unselected by the user. I used below code but it was giving me all the unselected values.
var unselectedValue = $("#multiselectList").find('option:not(:selected)');
Can anyone help me in finding the solution?
Thanks in advance
You can use jquery last() for it
https://api.jquery.com/last/
document.querySelector('select').addEventListener('change', () => {
var unselectedValue = $("#multiselectList").find('option:not(:selected)').last();
console.log(unselectedValue.val())
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="multiselectList">
<select multiple>
<option value="option1" selected>Val 1</option>
<option value="option2" selected>Val 2</option>
<option value="option3">Val 3</option>
<option value="option4">Val 4</option>
<option value="option5" selected>Val 5</option>
</select>
Try Using
$(document).ready(function() {
$("#sel").on("click", function(event) {
if(!event.originalEvent.srcElement.selected) {
console.log($(event.originalEvent.srcElement).val());
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="multiselectList">
<select id="sel" multiple>
<option value="option1" selected>Val 1</option>
<option value="option2" selected>Val 2</option>
<option value="option3" selected>Val 3</option>
<option value="option4" selected>Val 4</option>
<option value="option5">Val 5</option>
</select>
Try using
// save array to compare in function check
let lastSelected = [];
// set last selected value on document ready
$(document).ready(() => {
lastSelected = $('select option:not(:selected)')
.map((i, el) => el.value)
.get();
});
$('select').on('change', () => {
const currentSelected = $('select option:not(:selected)')
.map((i, el) => el.value)
.get();
// compare to get recently selected
const selected = lastSelected.filter(
(val) => !currentSelected.includes(val)
);
// compare to get recently unselected
const unselected = currentSelected.filter(
(val) => !lastSelected.includes(val)
);
recentChanges(selected, unselected);
// update last selected
lastSelected = currentSelected;
});
// recentChanges event
function recentChanges(selected, unselected) {
console.log(
(selected.length > 0 ? selected : 'nothing') + ' is selected'
);
console.log(
(unselected.length > 0 ? unselected : 'nothing') + ' is unselected'
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select multiple>
<option value="option1" selected>Val 1</option>
<option value="option2" selected>Val 2</option>
<option value="option3">Val 3</option>
<option value="option4">Val 4</option>
<option value="option5" selected>Val 5</option>
</select>
How can I know which option is currently unselected by the user.
// This is the selected value on page load
let selected = $("#multiselectList option:selected").text()
// On change event
$("#multiselectList select").on("change", function(){
// Keep the previous selection
let prevSelection = selected
// Get the new one
selected = $(this).find('option:selected').text();
// Results
console.log(`${prevSelection} was deselected and ${selected} was selected.`)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="multiselectList">
<select>
<option value="option1">Val 1</option>
<option value="option2">Val 2</option>
<option value="option3" selected>Val 3</option>
<option value="option4">Val 4</option>
<option value="option5">Val 5</option>
</select>
</div>

Change <select> after reading <span> JS

So, I have a form with input and select. What I need to do is put another color in the camps that are required, and I'm trying not to change the html that I already have so I'm doing a function in JS.
For the input is easy cause I do the following function and it changes the color of the input cause the "data-val-required" is in the input.
$('input').each(function () {
var req = $(this).attr('data-val-required');
if (undefined != req) {
$(this).css("background-color", 'rgb(250, 255, 189)');
$(this).attr('title', 'Este campo é obrigatório!');
}
});
But, for the select I can't do the same cause the "data-val-required" is in a span after the <select> . what I want to do is read the <span> and then color the <select> before it.
The html is something like this (the class="col-md-9" is the same for every camps of the form in the view)
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span class="field-validation-error" data-val-required="true">Campo obrigatório</span>
</div>
I tried this but this colors all the <select> camps I have in my code and not just only the ones required.
$('span').each(function () {
var rep = $(this).attr('data-val-required');
if (undefined != rep) {
$('select').css("background-color", 'rgb(250, 255, 189)');
$('select').attr('title', 'Este campo é obrigatório!');
}
});
Is there anyway without changing HTML, to make the function read the span and change just the select before that span?
I'm searching childNodes but I can't seem to do that with class instead of id.
Thank you!
You had to select on direct child '~' ot type SPAN from SELECT with class form-control. For searching the SELECT look for a sibling from your SPAN with the desired class and type of SELECT.
$('select.form-control ~ span').each(function () {
var rep = $(this).attr('data-val-required');
if (undefined != rep) {
let select = $(this).siblings('select.form-control');
select.css("background-color", 'rgb(250, 255, 189)');
select.attr('title', 'Este campo é obrigatório!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span class="field-validation-error" data-val-required="true">Campo obrigatório</span>
</div>
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span>Campo obrigatório2</span>
</div>
Try this.
$('span').each(function() {
var rep = $(this).attr('data-val-required');
if (undefined != rep) {
$(this).siblings('select').css("background-color", 'rgb(250, 255, 189)');
$(this).siblings('select').find('select').attr('title', 'Este campo é obrigatório!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span class="field-validation-error" data-val-required="true">Campo obrigatório</span>
</div>
<div class="col-md-9">
<select class="form-control">
<option selected="selected" value="1">TEXTO 1</option>
<option value="2">TEXTO 2</option>
<option value="3">TEXTO 3</option>
</select>
<span>Campo obrigatório2</span>
</div>

How to modify a html select to display all options with matching data attribute?

I have a html select drop-down listing various cats, each with a data attribute of "color", an associated color, and a button next to the drop-down.
Using pure javascript, I want to be able to click the button, get the "color" attribute of the selected cat, and have the list display all cats with the same color attribute.
Example: I've selected Cat 1 who has a color attribute of "black", I click the button and the drop down displays Cats 1, 3 and 4 as options.
Would I need to implement a for loop, or would for/in statement work?
function filter() {
//onclick modifies the "catList" select to display all cats with the same data-color attribute.
var list = document.getElementByID("catList");
};
<form>
<select id="catList">
<option data-color="black">Cat 1</option>
<option data-color="orange">Cat 2</option>
<option data-color="black">Cat 3</option>
<option data-color="black">Cat 4</option>
<option data-color="orange">Cat 5</option>
</select>
</form>
<button type="button" id="btn" class="menu" onclick="filter()">Filter Cats</button>
Loop over the option list, and add display none, to options that don't have the same data attribute value as with the selected option.
Option 1 (this will hide the other options, and you won't be able to select them, until you refresh the page)
function filter() {
//onclick modifies the "catList" select to display all cats with the same data-color attribute.
var list = document.getElementById("catList");
var option = list.options[list.selectedIndex]
list.querySelectorAll('[data-color]').forEach(function (element) {
if (option.getAttribute('data-color') !== element.getAttribute('data-color')) {
element.classList.add('filter');
}
})
};
.filter {
display: none;
}
<form>
<select id="catList">
<option data-color="black">Cat 1</option>
<option data-color="orange">Cat 2</option>
<option data-color="black">Cat 3</option>
<option data-color="black">Cat 4</option>
<option data-color="orange">Cat 5</option>
</select>
</form>
<button type="button" id="btn" class="menu" onclick="filter()">Filter Cats</button>
Option 2
function filter() {
//onclick modifies the "catList" select to display all cats with the same data-color attribute.
var list = document.getElementById("catList");
var color_filter = document.getElementById("color");
var value = color_filter.options[color_filter.selectedIndex].value;
list.querySelectorAll('[data-color]').forEach(function (element) {
if (value !== element.getAttribute('data-color')) {
element.classList.add('filter');
}else {
element.classList.remove('filter');
}
});
};
.filter {
display: none;
}
<select id="color" onchange="filter()">
<option value="">Select filter</option>
<option value="black">Black</option>
<option value="orange">Orange</option>
</select>
<select id="catList">
<option data-color="black">Cat 1</option>
<option data-color="orange">Cat 2</option>
<option data-color="black">Cat 3</option>
<option data-color="black">Cat 4</option>
<option data-color="orange">Cat 5</option>
</select>
You can try by this way
HTML
<form>
<select id="catList">
<option data-color="black">Cat 1</option>
<option data-color="orange">Cat 2</option>
<option data-color="black">Cat 3</option>
<option data-color="black">Cat 4</option>
<option data-color="orange">Cat 5</option>
<option data-color="black">Cat 6</option>
</select>
</form>
<button type="button" id="btn" class="menu" onclick="filter()">Filter Cats</button>
JS
window.filter = function () {
var action_list = document.getElementById("catList");
var selected_color = action_list.options[action_list.selectedIndex].getAttribute("data-color");
for (var i = action_list.options.length - 1; i >= 0; i--) {
if (action_list.options[i].getAttribute("data-color") != selected_color) {
action_list.remove(i);
}
}
};
Solution 1. see live demo here jsfiddle
Solution 2. see live demo here jsfiddle

update list of <select> from another <select multiple> using jquery

I am trying to update a <select> element when I select one or multiple values from another <select multiple> using jQuery. Here's my multiple select:
<select class="form-control" multiple>
<option value="1">company 1</option>
<option value="2">company 2</option>
<option value="3">company 3</option>
<option value="4">company 4</option>
</select>
I hope this is what you are looking for,
$('select#first').change(function() {
$("select#second option:not(:first-child)").remove();
$(this).find("option:selected").each(function() {
$("select#second").append($(this).clone());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first" class="form-control" multiple>
<option value="1">company 1</option>
<option value="2">company 2</option>
<option value="3">company 3</option>
<option value="4">company 4</option>
</select>
<select name="second" id="second">
<option value=''>Select 2</select>
</select>
Check this script https://jsfiddle.net/gpb5wx8h/5/
Jquery:
function chooseItems(item, placeholder){
$(item).change(function() {
var item = $(this);
console.log(typeof(item.val()));
if(typeof item.val() == 'object'){
$.each(item.val(), function(i,v){
var selectedItem = item.find('option[value="'+ v +'"]'),
selectedText = selectedItem.text();
selectedItem.detach();
$(placeholder).append('<option value="' + v +'">' + selectedText + '</option>')
})
}
})
}
$(document).ready(function() {
chooseItems('.choose-role','.placeholder-role');
chooseItems('.placeholder-role','.choose-role');
})
HTML:
<select class="form-control choose-role" multiple>
<option value="1">company 1</option>
<option value="2">company 2</option>
<option value="3">company 3</option>
<option value="4">company 4</option>
</select>
<select class="form-control placeholder-role" multiple>
</select>
If you want to update select options by fetching data from the server end regarding the selected values in multiple select box then you can perform ajax operation and insert the result to the another select box which is to be updated.

Show a tip for Options with Javascript

I have the following code which adds a bit of text below the select box when an item is selected. However it I can only get it to show the value of the select box. Is there any way I could get this to show a 3rd value?
<script type="text/javascript">
function dropdownTip(value){
console.log(value);
document.getElementById("result").innerHTML = value;
}</script>
<select onChange="dropdownTip(this.value)" name="search_type" style="margin-right:10px; margin-top:2px;">
<option selected="selected" value="1">Client 1</option>
<option value="2">Client 2</option>
<option value="3">Client 3</option>
<option value="4">Client 4</option>
</select>
<div id="result"></div>
For example, I would like to add something like "Always remember to ask for the full name" on client one, and "Never ask for last name" On client 2.
This should work:
<script type="text/javascript">
function dropdownTip(value){
var preamble = 'default preamble';
if(value == 'Client 2') {
preamble = 'Never ask for last name on ';
}
if (value == 'Client one') {
preamble = 'Always remember to ask for the full name';
}
console.log(value);
document.getElementById("result").innerHTML = preamble + value;
}</script>
<select onChange="dropdownTip(this.value)" name="search_type" style="margin-right:10px; margin-top:2px;">
<option selected="selected" value="1">Client 1</option>
<option value="2">Client 2</option>
<option value="3">Client 3</option>
<option value="4">Client 4</option>
</select>
<div id="result"></div>
You could use html5 data-* attributes.
Working demo.
javascript:
window.dropdownTip = function (obj) {
console.log(obj);
console.log(obj.value);
var sel = obj.options[obj.selectedIndex];
console.log(sel.getAttribute('data-desc'));
document.getElementById("result").innerHTML = obj.value;
document.getElementById("result").innerHTML += sel.getAttribute('data-desc');
}
html:
<body>
<select onchange="dropdownTip(this);" name="search_type" id="selector">
<option selected="selected" value="1" data-desc="test 1">Client 1</option>
<option value="2" data-desc="test 2">Client 2</option>
<option value="3" data-desc="test 3">Client 3</option>
<option value="4" data-desc="test 4">Client 4</option>
</select>
<div id="result"></div>
</body>

Categories