change background of next div depending on selected item - javascript

EDIT : It seems like I didn't make myself clear, sorry about that, so I update the code.
I have many "select", with different IDs and same class:
<div class="objvalide">
<select id="obj1-1" class="swit">
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div class="switchy-container">
<div class="switchy-bar">
<div class="switchy-slider" draggable="true" style="left: 0px;"></div>
</div>
</div>
</div>
<div class="objvalide">
<select id="obj1-2" class="swit">
<option selected="selected" value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div class="switchy-container">
<div class="switchy-bar">
<div class="switchy-slider" draggable="true" style="left: 0px;"></div>
</div>
</div>
</div>
... and more ...
Here's the JS I have so far:
$(function() {
$('.swit').switchy();
$('.swit').change(function() {
var select = $(this);
var id = select.attr('id'); //alert(id); <- Works fine, I get the correct ID
/* what do I hav to do here in order to have .switchy-bar bg change color only for this particular .objvalide > .switchy-container > .switchy-bar ? */
});
});
At the beginning, all options are "0".
Each and every .switchy-bar background is white.
When I select option value "1" in obj1-2 for instance, I need the background of its .switchy-bar to be red. If I select option value "2", background of its .switchy-bar has to be green.
The other select and background must remain untouched.
Thanks

$('.swit').on('change', function() {
var myVal = $(this).val();
switch (myVal){
case '1': $(this).siblings().children('.switchy-bar').css('background', '#000');
break
case '2': $(this).siblings().children('.switchy-bar').css('background', '#f00');
break
default: $(this).siblings().children('.switchy-bar').css('background', '#fff');
}
})
http://codepen.io/gmrash/pen/LpoGYG?editors=101

select[0].style.backgroundColor=bgColor
If you want to change the background of selected option,
var a= select[0].selectedIndex;
select[0][a].style.backgroundColor=bgColor

Use the click event to fire a function that makes the necessary changes. Use the this selector to ensure your changes only happen on the element that triggered the function.
If you want to make the changes happen to the parent/child (parent in your case) element of the triggering element, you can always traverse the DOM relative to this using JQuery methods this.parent()/this.children(). For instance, if you want to change the background-color of a <select> element based on the clicked <option>, you can do that in the following way using JQuery:
var backgroundcolor = ["red", "green", "white"];
$('option').click(function() {
$(this).parent().css("background-color", backgroundcolor[$(this).val()]);
});
Here, the array is created in order with the colors corresponding to each option.

Please use addClass("color-1") and removeClass("color-1"). That is the only solution for this and do what do want in that class.
Sol-1 (Without animate background)
In css
.color-1{
//Do stuff
}
This will Help You.
Also
Sol-2 (With animate background)
var record= $(this).find('switchy-bar');
record.animate(
{backgroundColor: '#FFF'},
{duration: 'fast', complete: function() {
//Here You can animate with new color. and old animation will be overwritten
record.css('backgroundColor', '');
}}
);

Related

Show/hide section based on option value without using jQuery

i need to show/hide different div based on the selected option of a dropdown menu. I've tried all the solutions explained in the previous tickets. When they use jQuery libraries, the show/hide action works, but they get in conflict with other page elements (ex. image sliders and counter bar are hidden). All the others solutions don't work, despite the one explained in this ticket (How can I show a hidden div when a select option is selected?). It works well, but only with two values. I need to extend this method to more than two values.
i write here the working code.
function showDiv(divId, element)
{
document.getElementById(divId).style.display = element.value == 1 ? 'block' : 'none';
}
#hidden_div {
display: none;
}
<select id="test" name="form_select" onchange="showDiv('hidden_div', this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
<div id="hidden_div">This is a hidden div</div>
P.S.: I'm not an expert in javascript. Thanks again.
I have modified the solution you referred to and it seems to be working (if I understand your question correctly):
HTML:
<select id="test" name="form_select" onchange="showDiv(this)">
<option value="hidden_div1">Show div 1</option>
<option value="hidden_div2">Show div 2</option>
<option value="hidden_div3">Show div 3</option>
<option value="hidden_div4">Show div 4</option>
</select>
<div id="hidden_div1">This is hidden div 1</div>
<div id="hidden_div2">This is hidden div 2</div>
<div id="hidden_div3">This is hidden div 3</div>
<div id="hidden_div4">This is hidden div 4</div>
CSS:
div[id*="hidden_div"] {
display: none;
}
javascript:
// When the page loads, make sure the already selected div is shown.
window.onload = function afterPageIsLoaded() {
showDiv();
}
function showDiv(element) {
// Create an array of all the hidden divs elements.
const hiddenDivs = [...document.querySelectorAll("div[id*='hidden_div']")];
// Loop over them and hide every one of them.
hiddenDivs.map(hiddenDiv => hiddenDiv.style.display = 'none');
// Get the selected id from the select.
const id = document.getElementById('test').value;
// Get the selected div and display it.
document.getElementById(id).style.display = 'block';
}
Link to the jsFiddle: https://jsfiddle.net/1jpad5x4/
If I misinterpreted your question or something is not clear, let me know!

Trying to update the DOM with dropdown select

I want the content displayed to be manipulated by selecting a dropdown option. Here's what I have so far. It doesn't work.
HTML - here's an example of my dropdown.
<select id="dropdown">
<option value="Week1" id="Week1drop">Week 1 - Greetings, Common Adjectives & Planets</option>
</select>
The div below will be hidden by default using {display: none} in CSS.
<div id="week1">
<h1>Greetings, Common Adjectives & Planets</h1>
</div>
JavaScript - Below I've got an event listener to check for a change to the dropdown, which whill call the UpdateDom Function.
The function should be identifying that the user has selected Week1 on the dropdown and using Jquery .show() to make the Div visible.
document.getElementById("dropdown").addEventListener("change", updateDom);
function updateDOM () {
if (document.getElementById('dropdown').value == "Week1") {
$("#week1").show();
}
}
I hope this makes sense, does anyone know where I'm going wrong?
Apart from the typo you found yourself, if you have jQuery, USE it.
Also options do not have IDs
$("#dropdown").on("change", function() {
$("#week1").toggle(this.value == "Week1"); // same as $(this).val()
}).change(); // initialise on load
#week1 {
display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdown">
<option value="">Please select</option>
<option value="Week1">Week 1 - Greetings, Common Adjectives & Planets</option>
</select>
<div id="week1">
<h1>Greetings, Common Adjectives & Planets</h1>
</div>

Hide elements in jQuery based on select value

I am building a filtering tool using a select element. When you choose something from the drop down, it should filter the divs below to show only the div for that item.
I am targeting the divs using the select value which is also the class of the div the item is in. So for example, if you choose shirts in the drop down the value would be item-shirts and a div below would have a class of item-shirts.
I have figured out how to hide everything that doesn't have the class of the selected item when something is selected. But I can't figure out how to unhide everything when something else is selected. Any help would be greatly appreciated!
Here is my HTML
<select>
<option value="item-shirts">Shirts</option>
<option value="item-shoes">Shoes</option>
<option value="item-shoes">Pants</option>
</select>
<div class="item-section item-shirt></div>
<div class="item-section item-shoes></div>
<div class="item-section item-pants></div>
Here is my jQuery
$('select').on("change", function() {
var value = $('select').val();
if($('.item-section').hasClass(value)) {
$('.item-section.'+value).siblings().hide();
} else {
$('.item-section.'+value).siblings().show();
}
This is similar to adding an active class to a list/group of elements. Typically what you do is loop through all the elements removing the active class (even though it's only applied to one element), then add the active class to the specific element. In your case you might want to hide all DIVs, then show the specific DIV.
var $sections = $( '.item-section' );
$('select').on( 'change', function ( e ) {
$sections.hide();
$( '.' + this.value ).show();
} );
.item-section {
margin: 2rem 0;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="item-shirts">Shirts</option>
<option value="item-shoes">Shoes</option>
<option value="item-pants">Pants</option>
</select>
<div class="item-section item-shirts">Shirt</div>
<div class="item-section item-shoes">Shoes</div>
<div class="item-section item-pants">Pants</div>
Note: You had a few errors in your markup that I changed to make everything work. i.e. Duplicate values for your <option> tags and some missing quotes.
I've done a couple performance improvements too.
You also don't need $( 'select' ).val() inside of your event handler. The context of the handler is the <select> element so you can use the this.value instead and skip jQuery querying the DOM to do the same.
I've also cached the .item-section elements so you're not querying the DOM over and over again on each change of the select.
There was no need to test for hasClass(). All you need to do is get the value from the selected option and show the <div> having that class. I added an extra empty option so that when you select it, it will show all <div>s.
$('select').on("change", function() {
var value = $('select').val();
if (value) {
$(".item-section").hide();
$("." + value).show();
} else {
$(".item-section").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value=""></option>
<option value="item-shirt">Shirts</option>
<option value="item-shoes">Shoes</option>
<option value="item-shoes">Pants</option>
</select>
<div class="item-section item-shirt">Shirts</div>
<div class="item-section item-shoes">Shoes</div>
<div class="item-section item-pants">Pants</div>

Show a div on option selection

I have a selection menu (drop down list).
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
& the following div which located in somewhere in my page.
<div id="somediv">This is a string.</div>
I want to display the above div upon selecting the second item of the menu (id="two").
I have 2 questions: (1) What is the best way to keep this div hidden by default? I will just add display:none; to its styling, but maybe there is a better solution? (2) How can I make the div show up when the option of id="two" is selected? Any answer would be greatly appreciated.
So I wrote a simple jquery script that does what you described. Let me know if it fixes your problem. You can also do this with javascript, but I think jquery works for this just fine.
http://codepen.io/Francisco104/pen/vEPRgp
$('select').change(function(){
decide($(this));
});
var decide = function (elem) {
var touch = elem;
if (touch.val() === 'anything') {
return $('#somediv').css('display', 'block');
}
};
For hiding it by default, using style="display: none"is the easiest. You could do it using jquery $('div#somediv').hide(); but I don't see any benefit to that other than you possibly wanting to keep the show/hide logic together.
Here are two simple solutions using a change() event.
If div#somediv should be shown permanently when option#two has been selected:
$("select").change(function() {
if ($(this).val() == 'anything') $('div#somediv').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display: none">This is a string.</div>
If div#somediv should be shown while option#two is selected and disappear if the user selects another option:
$("select").change(function() {
$('div#somediv').toggle($(this).val() == 'anything');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv" style="display: none">This is a string.</div>
You should probably give an id to the select as well, to make the jQuery selector less brittle.
So, I'd have a class for the div, let's say, is-hidden and my CSS will have .is-hidden { display: none; }. Then, do the following.
HTML:
<div id="somediv" class="is-hidden">This is a string.</div>
JS:
$div = $("#somediv");
$("select").on("change", function() {
$div.is(".is-hidden") || $div.addClass("is-hidden");
//Option 1
if ($(this).find(":selected")[0].id === "two") {
$div.removeClass("is-hidden");
}
//Option 2 (same as above, but a bit shorter)
$(this).find(":selected")[0].id === "two" && $div.removeClass("is-hidden");
});
Here is what you can do:
in your html file:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<select>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
You'll need to import the JQuery library (which I show you there right above the <select> element) so that you can execute your script.
In your css file:
#somediv {
display: none;
}
and finally here is the script that will show the dive when "plane" is selected
$('select').change(function(){
$('#somediv').css('display','block');
});
Take a look at this JSFIDDLE I made for you.
1) You can hide the div initially giving the css property display:none; or by setting its display property using javascript which will run in initial load.
2) You can listen to the onchange event of the selectfield and check if value is 'anything' then show the div by changing its display style property to block and hidden in other cases.
document.getElementById("somediv").style.display='none';
var showHideDiv=function(selectField){
var divElement=document.getElementById("somediv");
if (selectField.value=='anything')
divElement.style.display='block';
else
divElement.style.display='none';
}
<select onchange='showHideDiv(this)'>
<option id="one" value="something">Car</option>
<option id="two" value="anything">Plane</option>
</select>
<div id="somediv">This is a string.</div>
The simplest way to hide within HTML
<div hidden>content</div>
To display an hidden div
$(document).ready(function(){
$("select").change(function () {
$( "select option:selected").each(function(){
if($(this).attr("value")=="anything"){
$("#somediv").show();
}
});.
});
Display none works.
Have you tried keying into the onchange event? http://www.w3schools.com/jsref/event_onchange.asp?

Select First Element by jQuery

This is My HTML Dom
<dd>
<div class="Addable Files">
<div style="margin:5px;">
<select name="Kind" id="kind">
<option value="1" >K1</option>
<option value="2" >K2</option>
<option value="3" >K3</option>
</select>
<div class="customfile">
<span aria-hidden="true" class="customfile-button button">Browse</span>
<input type="file" name="Files" class="fileupload customfile-input">
</div>
<select name="yap">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
</div>
<input type="button" value="new" style="margin-top:5px;" class="AddNewE button red" id="AddFiles">
</dd>
And my Script:
//Add new Addable div
$('.AddNewE').click(function () {
var Target = $('.Addable.Files:first');
var CloneTarget = $(Target).clone();
CloneTarget.insertAfter('.Addable.Files:last');
$(Target).find('select').each(function () {
$(this).css('color', 'red');
});
});
So I expect when I click add button just first two select (two select of first div) be Red and all other selects don't changed, but I see weird behavior, In first Add everything is OK, but then in each Add all selects be red except second one, I think Target is first div and also I select Target's Select elements so why all selects be Red? where is my problem?
EDIT
I am sorry about wrong script, but this is my actual script:
//Add new Addable div
$('.AddNewE').click(function () {
var Target = $('.Addable.Files:first');
var CloneTarget = $(Target).clone();
CloneTarget.insertAfter('.Addable.Files:last');
$(CloneTarget).css('color', 'green');
$(Target).find('select').each(function () {
$(this).css('color', 'red');
});
});
This is achievable just by changing your function slightly. Try:
$('.AddNewE').click(function () {
var Target = $('.Addable.Files');
var CloneTarget = $(Target).first().clone();
CloneTarget.insertAfter('.Addable.Files:last');
$('select').css('color', 'gray');
$(Target).find('select').each(function () {
$(this).css('color', 'red');
});
});​
To summarise the points I have changed, I have edited your Target variable to target all of the .Files items, then changed the CloneTarget to only clone the first .Files target. That way, when it comes to changing them all to red you're actually changing all the existing .Files items except the new one you're adding.
Demo: http://jsfiddle.net/usZPN/
Your select is on .Addable.Files:first which selects the first select with that name, didn't you want to select the first div underneath like so: .Addable.Files > div:first-child?
I guess the following fiddle solves your purpose.
http://jsfiddle.net/meetravi/9ehAF/
I am finding a bug in the code you have written in the following line.
$('.select').css('color', 'gray');
There is no select class in your code rather the code should be
$('select').css('color', 'gray');
Worksforme in http://jsfiddle.net/Y2XhV/, although I'm not sure which <div> you want to clone: the one with the margin or the one with the 2 classes? Your selectors are for the latter case. Yet, there are some small improvements to your code making it simpler:
//Add new Addable div
$('.AddNewE').click(function () {
var $Target = $('.Addable.Files:first');
var $CloneTarget = $Target.clone();
$CloneTarget.insertAfter('.Addable.Files:last');
$Target.find('select').css('color', 'red');
});
You don't need to recreate new jQuery objects from Target when you already have one, and .css() doesn't need a each.

Categories

Resources