Toggle class from dropdown menu - javascript

I try to toggle a class by selecting a option in the dropdown menu, i've tried using a alert() to check if it works but i cant seem to get it to work.
HTML:
<html>
<body>
<select id="dropdown">
<option value="1">Steinkjer</option>
<option value="2">Verdal</option>
</select>
</body>
</html>
Javascript:
$('#dropdown option:selected').click(function(){
var getText = $('#dropdown option').text();
alert($('.overlay-'+getText));
});
Please help me solve this issue.

$('#dropdown option:selected') is not a live object. Your code binds the click handler to the selected option on page load. You should either use event delegation or better listen to change event of the select element.
$('#dropdown').on('change', function() {
// Get text content of the selected option
var getText = $('option:selected', this).text();
// Get current value of the select element
// var getValue = this.value;
console.log(getText);
console.log($('.overlay-'+getText));
});

You need to:
Check document.ready is executed
Assign the change event
To bind some events to DOM elements, requires a document.ready, to
ensure the DOM element is sure created at the time you associate the
event.
A page can't be manipulated safely until the document is "ready.": https://learn.jquery.com/using-jquery-core/document-ready/
Check this snippet:
$(document).ready(function() {
$('#dropdown').change(function() {
var getText = $('#dropdown option:selected').html();
$("#test").removeClass();
$("#test").toggleClass("overlay-" + getText);
});
});
.overlay-Steinkjer {
background-color: red;
}
.overlay-Verdal {
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<select id="dropdown">
<option value="1">Steinkjer</option>
<option value="2">Verdal</option>
</select>
<p id="test">test paragraph</p>
</body>
</html>

Related

How do I get the value of an entire HTML dropdown

I need to get the value of an entire element and all its child elements, so that I can create a duplicate of the element. Is there any way to do this with plain js?
<!DOCTYPE html><html>
<select id="select">
<option>Bulldog</option>
<option>Pitbull</option>
</select>
<!--The entire dropdown with all its child option elements should be duplicated into the div element:-->
<div id="div"></div>
</html>
i think better to give the value for each options,
and maybe this js can help u
with HTML
<!DOCTYPE html><html>
<select id="select">
<option value="Bulldog">Bulldog</option>
<option value="Pitbull">Pitbull</option>
</select>
<!--The entire dropdown with all its child option elements should be duplicated into the div element:-->
<div id="div"></div>
</html>
and with JS :
var j = document.getElementById("select");
var i;
var value = "List Value: ";
for (i = 0; i < j.length; i++) {
value = value + "\n" + j.options[i].text;
}
console.log(value)
Use cloneNode:
document.body.appendChild(document.querySelector('#select').cloneNode(true));
it clones the element then append the clone to the page body. you don't need to get the element's value.
hope this helps a bit.
This code below shows you the result by cloning the element as a whole and appending to the the element id="div". Let me know if this is what you needed.
<!DOCTYPE html>
<html>
<body>
<select id="select">
<option>Bulldog</option>
<option>Pitbull</option>
</select>
<!--The entire dropdown with all its child option elements should be duplicated into the div element:-->
<div id="div"></div>
</body>
</html>
<script>
var x = document.querySelector("#select").cloneNode(true);
document.getElementById("div").appendChild(x);
</script>

How to detect option content change in dropdown using jquery?

I have a dropdown field, options of which will be changed dynamically.
Is there a way to capture the event, whenever the set of options inside the dropdown is changed?
I do not want to capture the option change i.e
$(".dropdown").on("contentChange", function(){
//do something
})
Rather, I want to capture the event, when the set of options inside the dropdown gets modified.
How can i attach a handler, which will get trigger functions when option set changes.
It is possible to watch DOM changes, in newset DOM specification we have MutationObserver to observe DOM. Working exampe
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
//create observer
var observer = new MutationObserver(function(mutations, observer) {
console.log("Options have been changed");
});
//set to observe childs ( options )
observer.observe(document.querySelector(".dropdown"), {
subtree: true,
childList:true,
attributes:true
});
//test change
$('button').on("click",function(){
$(".dropdown").prepend("<option>New added option</option>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropdown">
<option>First</option>
<option>Second</option>
<option>Third</option>
<option>Fourth</option>
</select>
<button>Test button options change</button>
You can use also event DOMSubtreeModified. Event work on major browsers but is DEPRECATED . Working example:
//add event
$(".dropdown").on("DOMSubtreeModified", function(e){
console.log('Options have been changed');
});
//change option example after button click
$('button').on("click",function(){
$(".dropdown").prepend("<option>New added option</option>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropdown">
<option>First</option>
<option>Second</option>
<option>Third</option>
<option>Fourth</option>
</select>
<button>Test button options change</button>
I added some example options modification after button click. Event will be called on any DOM change inside select.
You can add your custom event to DOM document and simulte it when content change using jquery .trigger().
$("button").click(function(){
$("select > option:first").text("A1").trigger("contentChange");
});
$("select > option").on("contentChange", function(){
console.log("Content changed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Change content</button>
<select>
<option>A</option>
<option>B</option>
<option>C</option>
</select>

Change jquery code from targeting a value to link

Hi i got this html code with a drop down list where i select the option blue or green, and it works great with the jquery below.
<select id="styleSelect">
<option value="styleblue">Blue</option>
<option value="stylegreen">Green</option>
</select>
jquery
$("#styleSelect").change(function() {
updateStyleSheet($(this).val());
});
My question is how to change this code into a clickable link instead of an option value, i already now the html code should be like this
<div id="styleSelect">
click here
click here
</div>
But how should the jquery look like?
$("#styleSelect a").click(function(e) {
e.preventDefault();
updateStyleSheet($(this).attr('href'));
});
You can do:
$("#styleSelect a").click(function(e) {
e.preventDefault(); //stop link
var href = this.href;
});
$("#styleSelect a").click(function(e) {
e.preventDefault();
updateStyleSheet($(this).attr('href'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="styleSelect">
click here
click here
</div>

How to create dynamic content in a web page according to the option selected in drop down menu

I have a webpage where i have a dropdown menu with default option not selected. When the user selects an option then i want display textboxes related to that option. How can i do this. For example i have these images
Really depends on how many options you have in the list box and if the textboxes are shared between the options.
You could created hidden DIVs which are then shown when an option is selected. You would need to create a JavaScript function which is fired using the onChange event attached to the drop down.
If you were sharing the textboxes then given them specific classes which you can show/hide in the Javascript function, this is relatively simple if you use something like jQuery.
Add an event handler for selection changed like so:
$('#yourSelectId').change(function() {
var selectedVal = $('#yourSelectId option:selected').attr('value');
});
Then make some hidden divs visible depending on the selected value( $.('.class').hide() ).
Use divs whose visibility is set to be hidden, and make it visible on select event. You can use multiple divs for atheistic purpose, associated with a select event.
An example can be found in post 2 at -
http://www.codingforums.com/showthread.php?t=167172
This is quite simple. All textboxes are hidden and with an event on your dropdown menu, you just show the right div.
HTML :
<select id='dropdown' onchange='showDiv()'>
<option>Select</option>
<option value="div1">Div 1</option>
<option value="div2">Div 2</option>
</select>
<br /><br />
<div id="div1" style='display: none;'>Div 1</div>
<div id="div2" style='display: none;'>Div 2</div>
JS
<script type="text/javascript">
function showDiv() {
var div = document.getElementById("dropdown").value;
if(document.getElementById(div) != null) {
hideAllDiv();
document.getElementById(div).style.display = "block";
}
}
function hideAllDiv() {
document.getElementById("div1").style.display = "none";
document.getElementById("div2").style.display = "none";
}
</script>
The code above is ugly but you can do it better with jquery and some css.
Edit :
Example with Jquery
<select id='dropdown'>
<option>Select</option>
<option value="div1">Div 1</option>
<option value="div2">Div 2</option>
</select>
<br /><br />
<div class='div' id="div1">Div 1</div>
<div class='div' id="div2">Div 2</div>
<style type="text/css">
.div { display: none; }
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#dropdown").change(function() {
$(".div").hide();
$("#" + $(this).val()).show();
});
});
</script>

Cloning div and changing attributes

I performed various research but I din't find a solution for my problem. I created a drop down select with css to change color of background, but then when I try to clone it with Javascript, the new copy doesn't change attributes in selection so it keep the original color. Just try it, add some copy and try to change the colors.
I'm new here, i'm not very able to add code so here's to try:
http://jsfiddle.net/gabry501/FUyA3/
or github
https://github.com/gabry501/Test-Color/blob/master/test.html
HEAD
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function cloning() {
var container = document.getElementById('fine');
var clone = document.getElementById('contenitore').cloneNode(true);
container.appendChild (clone);
}
STYLE
select option,
select {
background-color:white;
width:200px;
height:200px;
}
select option[value="1"],
select.o1
{
background-color:blue;
}
select option[value="2"],
select.o2
{
background-color:red;
}
select option[value="3"],
select.o3
{
background-color:orange;
}
BODY
<div style="width:1100px;
height:250px;" id="contenitore">
SCRIPT
<script>$('select[id$=-status][id^=id_item-]').children().each(
function (){
if($(this).val() == 0){
$(this).css('backgroundColor','white');
}
if($(this).val() == 1){
$(this).css('backgroundColor','green');
}
if($(this).val() == 2){
$(this).css('backgroundColor','red');
}
if($(this).val() == 3){
$(this).css('backgroundColor','orange');
}
}
);</script>
<script>
$('select[id$=-status][id^=id_item-]').change(function (){
var color = $(this).find('option:selected').val();
$(this).removeClass('o1 o2 o3').addClass('o' + $(this).find('option:selected').val());
}).change();
It seems you are depending on a listener to modify the style. Listeners added using addEventListener are not included in a cloned element, you have to attach them seperately.
Note that listeners added inline, or using attachEvent are cloned.
cloneNode() copies only the data of the element in question. it does not copy over the event listeners. You need to do that manually..
Use the jQuery clone() method..
function cloning() {
var container = document.getElementById('fine');
var clone = $(document.getElementById('contenitore')).clone(true);
$(container).append(clone);
}
Check Fiddle
PS : Also you code looks really messy . You can scale it down..
UPDATE
I have made a few changes to the code .
1.) Removed the click event from HTML and added that to the script.
2.) Removed the ID's and replaced by a className as ID's in a document are supposed to
be Unique.
3.) Removed extra styles and replaced with a simple class Name.
4.) Better to have separate files for style and script than including it in HTML.
5.) If you want it to work , move the styles and the script to the corresponding tags I
have marked..
HTML
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style type="text/css">
// Add the Styles here
</style>
</head>
<body>
<div style="width:1100px; height:250px;" class="contenitore">
<select name="item-0-status">
<option value="" disabled="disabled" class="optionGroup">SELECT
COLOR</option>
<option value="1"> BLUE</option>
<option value="2"> RED </option>
<option value="3"> ORANGE</option>
</select>
</div> <!--Contenitore -->
<div id="fine"></div>
<br>
<div id="bottone">
<input id="btn" type="button" Value="ADD">
</div>
<script type="text/javascript">
// Script Comes Here
</script>
</body>
</html>
Javascript
$(function() {
$('select[name="item-0-status"]').change(function() {
$(this).removeClass('o1 o2 o3').addClass('o' + $(this).val());
}).change();
$('#btn').on('click', function() {
var container = document.getElementById('fine');
var clone = $(document.getElementsByClassName('contenitore')[0]).clone(true);
$(container).append(clone);
});
});​
Styles
#bottone
{
float:left;
text-align:left;
clear:left;
margin-top:20px;
}
select option,select
{
background-color:#FFF;
width:200px;
height:200px;
}
.o1
{
background-color:blue;
}
.o2
{
background-color:red;
}
.o3
{
background-color:orange;
}​
UPDATED FIDDLE
You have to use $('.el').live('change', fn) instead of $('.el').change(fn) because you're adding an element after the DOM is loaded.
See this jsfiddle: http://jsfiddle.net/FUyA3/1/
try deep cloning - i.e $(selector).clone(true)....then events will also be cloned

Categories