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>
Related
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>
I am a total beginner to jquery. and am badly stuck. i would really appreciate if i could get some help with my code.
The scenario is,
- I have a drop down list for the names.
- When i select a name from the list, it should display in the div which is placed beneath the drop down menu. The div will be created automatically via jquery. every item selected from the list will be displayed in its own respective div. The name Sarah should not be included in the drop down list.Its like a stand alone thing. However, when i select an item in the list, the name Sarah is replaced with the selected item.
What i was able to code was --
- I could get the divs with some names associated with it. However, i am unable to target the selected item to its respective div.
I hope it makes sense. I am posting the link to my jsFiddle. Please help.
http://jsfiddle.net/zohana28/0akosx2a/
<div class="part-4">
<select id="sel">
<option value="Cheese">Cheese</option>
<option value="Olives">Olives</option>
<option value="Pepperoni">Pepperoni</option>
<option value="Oregano">Oregano</option>
<option value="Thyme">Thyme</option>
</select>
</div>
<!--end of part 4-->
<div class="main">
<div class="part-2" id="click-1" style="cursor:pointer;">
<div class="part-2-address">
<h4 id="name">sarah</h4>
</div>
</div>
jQuery is:
$(document).ready(function () {
$(document).on('change', '#sel', function (e) {
$('.part-3').html($('.part-2').html());
$('.main').append('<div class = "part-3" > </div>');
var str = $('select option:selected').text();
$('#name').text(str);
console.log(str);
});
return false;
});
thank you in advance.
I've adjusted your Fiddle a bit.
$(document).ready(function () {
$(document).on('change', '#sel', function (e) {
var nameTempl = '<div class="part-2" class="click-1">'
+ '<div class="part-2-address">'
+ '<h4 class="name">{name}</h4></div></div>';
var str = $('select option:selected').text();
$('.main').append(nameTempl.replace(/{name}/, str));
});
return true;
});
For the HTML: I removed the inline-style cursor:pointer; and added it as style for the class .click-1 - previously click-1 and name were ids, I've changed both to be classes. ids have to be unique, so you have to use classes instead.
Though it would be possible to clone() the <div class="part-2" class="click-1"> and then change the name to the current selected option, I just preferred to use the target div as template in the function, with {name} as placeholder to be replaced with the current selected option: nameTempl.replace(/{name}/, str).
Another adjustment that you can change back is - I've set the height:200px; of the .main div to min-height: 200px;, so this container grows when necessary. You can just change this back to height:200px; in case you prefer the yellow div to have a static height like before.
As reference for replace(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
I am trying to make a web page where there is a drop-down box that has a list of colors. Choosing one of the colors will make the sentences(the p's under the code for the drop-down list) change to that color. Everything is fine except that when I choose the color in the drop-down list, the text color does not change.
HTML
<html>
<head>
<script type="text/javascript" src="colorchange.js"></script>
</head>
<body>
<form>
<select>
<!--This is the drop-down list-->
<option id="red" onclick="changeColor()">Red</option>
<option id="orange" onclick="changeColor()">Orange</option>
<option id="yellow" onclick="changeColor()">Yellow</option>
<option id="green" onclick="changeColor()">Green</option>
<option id="blue" onclick="changeColor()">Blue</option>
<option id="purple" onclick="changeColor()">Purple</option>
</select>
</form>
<!--These are the sentences that have to change text color-->
<p>Sentence 1</p>
<p>Sentence 2</p>
<p>Sentence 3</p>
<p>Sentence 4</p>
</body>
</html>
JavaScript - colorchange.js
function changeColor() {
document.getElementById("red")
document.p.style.color = red;
document.getElementById("orange")
document.p.style.color = orange;
document.getElementById("yellow")
document.p.style.color = yellow;
document.getElementById("green")
document.p.style.color = green;
document.getElementById("blue")
document.p.style.color = blue;
document.getElementById("purple")
document.p.style.color = purple;
}
Can someone help me with the code?
There are a few problems with your code.
All if your options call changeColor(), which means that clicking any option will execute all that code. So you need to find some way of separating or specifying the individual color you want.
document.getElementById('red') references the element with the id of red. This line by itself doesn't do anything other than referencing, so you normally need to add to it to do anything. Something like document.getElementById('red').style.color = 'red'. But since the element with the id of red is an <option> inside the dropdown menu, this is not what you want. You want to reference the <p> elements instead, and change their color.
document.p does not reference the <p> elements. document.p references the p property of the object document. This property doesn't exist. In JavaScript, you usually want to use one of these: document.getElementById('id'), document.getElementsByTagName('tag'), or document.getElementsByClassName('class'). Note that with tag name and class name, the Elements is plural, since you're referencing a list of all the elements with that tag or class. So you usually need to narrow things down a bit, or use a loop to execute some code for each item in the list.
This one's not so much a problem, but rather a better way of doing what you're trying to do. Instead of setting ids for the <option>s, just set their values and then in JavaScript, you can just reference the value of the <select> element. A dropdown menu's <select> element will have the value of whichever <option> the user has chosen.
Having said all that, here is how I would write the code to do what you want.
HTML:
<select id="colorChanger">
<option>Choose a color</option>
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="purple">Purple</option>
</select>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
JS:
//add an event listener that calls changeColor() when the menu selection changes
//this is the same as adding onchange="changeColor()" in HTML
document.getElementById('colorChanger').addEventListener('change', changeColor);
function changeColor() {
//store the menu's value (which is the value of the chosen option)
var color = document.getElementById('colorChanger').value;
//store the list of all <p> elements
var list = document.getElementsByTagName('p');
//loop through the list and apply the color to each <p> element
for (var i=0; i<list.length; i++) {
list[i].style.color = color;
}
}
or JS with jQuery:
//add an event listener that calls changeColor() when the menu selection changes
//this is the same as adding onchange="changeColor()" in HTML
$('#colorChanger').on('change', changeColor);
function changeColor() {
//store the menu's value (which is the value of the chosen option)
var color = $('#colorChanger').val();
//apply the color to all <p> elements
//(this is one of the benefits of using jQuery, it's much easier to apply certain changes)
$('p').css('color', color);
}
Here's a fiddle with the JS.
And here's a fiddle with jQuery.
Something along these lines should do it - jQuery and vanilla JS solutions provided. It's also worth noting that this will change the colour of every p tag on the page.
<select id="change-color">
<option value="red">Red</option>
<option value="orange">Orange</option>
<!-- more options as required -->
</select>
// jQuery
// whenever [id=change-color] changes its value
$('#change-color').on('change', function() {
// set every <p> tag to be the colour of the selected options value attribute
$('p').css('color', $select.val());
});
// JS
document.getElementById('change-color').onchange = function() {
document.getElementsByTagName('p').style.color = this.options[ this.selectedIndex ].value;
}
If you don't want to match every p tag, and only some of them, you can do this:
<p class="change-color">Something</p>
<p>Unchanged</p>
// jQuery
$('#change-color').on('change', function() {
// Same as before, except only match <p> with 'change-color' class
$('p.change-color').css('color', $select.val());
});
// JS
document.getElementById('change-color').onchange = function() {
// Get every <p> tag in the document
var ps = document.getElementsByTagName('p');
// Iterate over them
for (var i in ps) {
// If their 'class' attribute contains the change-color class...
if ( -1 !== (' '+ps[i].className+' ').indexOf(' change-color ') ) {
// Change the colour of just this <p> tag and continue looping
ps[i].style.color = this.options[ this.selectedIndex ].value;
}
}
}
Lastly, if you use the final example (vanilla JS, match-by-class) and want to be able to stamp anything with the "change-color" class, you can just do document.getElementsByTagName('*') to get every element on the page, instead of just the <p> tags. Obviously, this will be relatively resource intensive if you have a large number of elements in the page.
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>
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