trying to set the body background image through selector option - html

I am trying to change my background image when each selected item is chosen through the selector, i am wondering if anyone can help in what i am doing wrong. It is currently setting the selector options to the background when each one is selected and not the body.
<body id="mainBody" background="resources/imgs/background2.jpg" >
<select onchange="changeBackGround();" id="selectBackGround">
<option value="Original">Original</option>
<option value="GreyScale">GreyScale</option>
<option value="Colorful">Colorful</option>
</select>
var changeBackGround = function(){
var mainBody = document.getElementById("selectBackGround");
if(document.getElementById("selectBackGround").value === "Original"){
mainBody.style.backgroundImage = "url('resources/imgs/background2.jpg')";
}else if(document.getElementById("selectBackGround").value === "GreyScale"){
mainBody.style.backgroundImage = "url('resources/imgs/greyscale.jpg')";
}else{
mainBody.style.backgroundImage = "url('resources/imgs/colored.jpg')";
}
mainBody.style.backgroundImage = document.getElementById("selectBackGround").value;
};

Change
var mainBody = document.getElementById("selectBackGround");
to
var mainBody = document.getElementById("mainBody");
You are applying background to mainBody not selectBackground.
var changeBackGround = function(){
var mainBody = document.getElementById("mainBody");
if(document.getElementById("selectBackGround").value === "Original"){
mainBody.style.backgroundImage = "url('resources/imgs/background2.jpg')";
}else if(document.getElementById("selectBackGround").value === "GreyScale"){
mainBody.style.backgroundImage = "url('resources/imgs/greyscale.jpg')";
}else{
mainBody.style.backgroundImage = "url('resources/imgs/colored.jpg')";
}
mainBody.style.backgroundImage = document.getElementById("selectBackGround").value;
};
<body id="mainBody" background="resources/imgs/background2.jpg" >
<select onchange="changeBackGround();" id="selectBackGround">
<option value="Original">Original</option>
<option value="GreyScale">GreyScale</option>
<option value="Colorful">Colorful</option>
</select>

Related

Matching two ID attributes from cloned dependent dropdown list

In this code I have 2 dependent dropdown lists and a button to duplicate/clone the form. The color selection changes based on what is selected in item. When I duplicate the dropdown list the function didn't work. I tried changing the id of the duplicated dropdown list but still can't manage to match the id of 2 dropdown list. Is there any solution? Thanks.
var count = 1;
var duplicate_div = document.getElementById('duplicate_1');
function addRecord() {
var clone = duplicate_div.cloneNode(true);
clone.id = "duplicate_" + ++count;
duplicate_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0];
$(clone).find("*[id]").each(function() {
$(this).val('');
var tID = $(this).attr("id");
var idArray = tID.split("_");
var idArrayLength = idArray.length;
var newId = tID.replace(idArray[idArrayLength - 1], count);
$(this).attr('id', newId);
});
}
$(document).ready(function() {
$("#item_" + count).change(function() {
var val = $(this).val();
if (val == "shirt") {
$("#color_" + count).html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$("#color_" + count).html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$("#color_" + count).html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate" id="duplicate_1">
<br>
<label>item</label>
<select id="item_1">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select id="color_1">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button" onclick="addRecord()">add</button>
Since you've imported jQuery into the project, I suggest you fully use it.
It's recommended to use jQuery's .on method instead of onclick attribute.
The change event will not work on the dynamically created elements.
You should instead use "event delegation".
Last but not least, you can remove the ids if they serve as selectors. You can use jQuery to easily transverse the DOM
Try this
$(document).ready(function() {
var $cloned = $('.duplicate').first().clone(true);
var $container = $('.select-form');
$('#add-button').click(function() {
$container.append($cloned.clone());
})
$('.select-form').on('change', '.item', function() {
var val = $(this).val();
var $color = $(this).closest('.duplicate').find('.color');
if (val == "shirt") {
$color.html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$color.html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$color.html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate">
<br>
<label>item</label>
<select class="item">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select class="color">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button">add</button>

show selected option value info to other select tag [duplicate]

i have the following problem:
I started to create a form with HTML an JS and there are two Dropdowns (Country and City). now i want to make these two dynamic with JQuery so that only the cities of the selected countries are visible.
I've started with some basic JS which worked fine but makes some trouble in IE. Now i'm trying to convert my JS to JQuery for a better compatibility.
My original JS looks like this:
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Germany") {
var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"];
} else if (s1.value == "Hungary") {
var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"];
} else if (s1.value == "Russia") {
var optionArray = ["|", "st. petersburg|St. Petersburg"];
} else if (s1.value == "South Africa") {
var optionArray = ["|", "midrand|Midrand"];
} else if (s1.value == "USA") {
var optionArray = ["|", "downers grove|Downers Grove"];
} else if (s1.value == "Mexico") {
var optionArray = ["|", "puebla|Puebla"];
} else if (s1.value == "China") {
var optionArray = ["|", "beijing|Beijing"];
} else if (s1.value == "Spain") {
var optionArray = ["|", "barcelona|Barcelona"];
}
for (var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
};
and here my Jquery:
http://jsfiddle.net/HvXSz/
i know it is very simple but i can't see the wood for the trees.
It should as simple as
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
Demo: Fiddle
I'm going to provide a second solution, as this post is still up in Google search for 'jquery cascade select'.
This is the first select:
<select class="select" id="province" onchange="filterCity();">
<option value="1">RM</option>
<option value="2">FI</option>
</select>
and this is the second, disabled until the first is selected:
<select class="select" id="city" disabled>
<option data-province="RM" value="1">ROMA</option>
<option data-province="RM" value="2">ANGUILLARA SABAZIA</option>
<option data-province="FI" value="3">FIRENZE</option>
<option data-province="FI" value="4">PONTASSIEVE</option>
</select>
this one is not visible, and acts as a container for all the elements filtered out by the selection:
<span id="option-container" style="visibility: hidden; position:absolute;"></span>
Finally, the script that filters:
<script>
function filterCity(){
var province = $("#province").find('option:selected').text(); // stores province
$("#option-container").children().appendTo("#city"); // moves <option> contained in #option-container back to their <select>
var toMove = $("#city").children("[data-province!='"+province+"']"); // selects city elements to move out
toMove.appendTo("#option-container"); // moves city elements in #option-container
$("#city").removeAttr("disabled"); // enables select
};
</script>
I have created cascading Dropdown for Country, State, City and Zip
It may helpful to someone. Here only some portion of code are posted you can see full working example on jsfiddle.
//Get html elements
var countySel = document.getElementById("countySel");
var stateSel = document.getElementById("stateSel");
var citySel = document.getElementById("citySel");
var zipSel = document.getElementById("zipSel");
//Load countries
for (var country in countryStateInfo) {
countySel.options[countySel.options.length] = new Option(country, country);
}
//County Changed
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
zipSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var state in countryStateInfo[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
Fiddle Demo
I have a handy code. you can just copy it:
Same as above
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn', 'asdasdasd'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Japn': ['tokyo'],
'Shuidong': ['shuidongjie','maomingjie'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
</script>
</head>
<body>1
<label class="page1">Country</label>
<div class="tooltips" title="Please select the country that the customer will primarily be served from">
<select id="country" name="country" placeholder="Phantasyland">
<option></option>
<option>Germany</option>
<option>Spain</option>
<option>Hungary</option>
<option>USA</option>
<option>Mexico</option>
<option>South Africa</option>
<option>China</option>
<option>Japn</option>
<option>Shuidong</option>
<option>Russia</option>
</select>
</div>
<br />
<br />
<label class="page1">Location</label>
<div class="tooltips" title="Please select the city that the customer is primarily to be served from.">
<select id="location" name="location" placeholder="Anycity"></select>
</div>
</body>
</html>
This is an example that I've done. I wish that will be useful for you.
$(document).ready(function(){
var ListNiveauCycle = [{"idNiveau":1,"libelleNiveau":"CL1","idCycle":1},{"idNiveau":26,"libelleNiveau":"Niveau 22","idCycle":24},{"idNiveau":34,"libelleNiveau":"CL3","idCycle":1},{"idNiveau":35,"libelleNiveau":"DAlf3","idCycle":1}];
console.log(ListNiveauCycle);
function remplirListNiveau(idCycle){
console.log('remplirListNiveau');
var $niveauSelect = $("#niveau");
// vider la liste
$niveauSelect.empty();
for (var i = 0; i < ListNiveauCycle.length; i++) {
if(ListNiveauCycle[i].idCycle==idCycle){
var opt1 = document.createElement('option');
opt1.innerHTML = ListNiveauCycle[i].libelleNiveau;
opt1.value = ListNiveauCycle[i].idNiveau;
$niveauSelect.append(opt1);
}
}
}
$("#cycles").change(function(){
remplirListNiveau(this.value)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Cycle</label>
<div class="col-sm-9">
<select class="form-control" id="cycles" required="">
<option value="">-----------</option>
<option value="1">Cycle1</option>
<option value="24">Cycle2</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Niveau</label>
<div class="col-sm-9">
<select id="niveau" class="form-control" required="" name="niveau.id">
</select>
</div>
</div>
</div>

jQuery if in array but exclude some string

I have six option values from database table similar to this: #blog and #hariciURL and #portfolio blah blah blah similar like this.
I have another table have that values, I check if same values in the array that option value will be disabled but except #hariciURL option value never disable.
How can I exclude #hariciURL not disabled from this option menu?
please check codes you can understand what I mean.
sorry, my bad English.
$().ready(function() {
$('#degeriAL option').each(function() { // option menüsündeki tüm değerleri al
//console.log(BolumleriAl);
var BolumleriAl = $(this).val(); // tüm valuelerini bir değişkene ata
var seolink = ("#services", "#hariciURL");
//var seolink = "<?php echo $BolumVarmiSorgula->seolink;?>"; // this original code come from database.
console.log(seolink);
var bolumisimleri = $('#degeriAL option[name]');
var exclude = "#hariciURL"; //this will be never disabled
if ($.inArray(seolink, BolumleriAl) && BolumleriAl !== exclude) { // iki dizi içinde eşleşen varmı diye bak
$('#degeriAL option[value="' + seolink + '"]').prop("disabled", true).addClass("secimMenusuDisabled").addClass(".secimMenusuDisabled" + "(bölüm mevcut)").nextAll(); //option menüdeki dizi içinde olan tüm değerlerini veritabanından gelenlerle karşılaştır ve eşleşenleri option menü içinden disabled yap
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="degeriAL" name="bolumLink" class="form-control form-control-sm" required="">
<option value="" required="">Bölüm Seçiniz...</option>
<option value="#featured-services"> Diğer Hizmetler </option>
<option value="#about"> Hakkımızda </option>
<option value="#services"> Hizmetler </option>
<option value="#call-to-action"> Tıklama Eylemi </option>
<option value="#blog"> Blog </option>
<option value="#skills"> Yatay İstatistik Çizelgesi </option>
<option value="#facts"> Rakamsal İstatistik </option>
<option value="#portfolio"> Ürünler </option>
<option value="#clients"> Referansların Logoları </option>
<option value="#testimonials"> Müşteri Görüşleri </option>
<option value="#team"> Bizim Takım & Çalışanlar </option>
<option value="#contact"> İletişim / Form / Harita </option>
<option value="#hariciURL"> Harici Link </option>
</select>
$('#degeriAL option').each(function() {
var BolumleriAl = $(this).val();
var seolink = "<?php echo $BolumVarmiSorgula->seolink;?>";
var bolumisimleri = $('#degeriAL option[name]');
var Exclude = "#hariciURL"; //this will be never disabled
if (jQuery.inArray(seolink, BolumleriAl)) {
$('#degeriAL option[value="' + seolink + '"]').prop("disabled", true).addClass("secimMenusuDisabled").addClass(".secimMenusuDisabled" + "(that already exist, you can not add more than one)").nextAll();
}
});
What you most likely want is
since the seolinks seems to be a string, you need to split it so that it becomes an array.
check that the BolumleriAl is not the same as the Exclude
if they are different then check if it is found in the seolinks array and if so then disable it
you are already iterating over the option elements so no need to use a selector to find the element to disable. Just use this.
$('#degeriAL option').each(function() {
var BolumleriAl = $(this).val();
var seolink = "<?php echo $BolumVarmiSorgula->seolink;?>".split(' ');
var Exclude = "#hariciURL"; //this will be never disabled
if (BolumleriAl !== Exclude && $.inArray(BolumleriAl, seolink) > -1) {
$(this).prop("disabled", true)
.addClass("secimMenusuDisabled")
//.addClass(".secimMenusuDisabled" + "(that already exist, you can not add more than one)");
}
});
According to what I understoud from your question, I think your if condition was inverted.
Also, you should use the value given by $.each function
var seolink = "<?php echo $BolumVarmiSorgula->seolink;?>";
var Exclude = "#hariciURL"; //this will be never disabled
$('#degeriAL option').each(function(i,v) {
Exclude = v != Exclude && $.inArray(seolink, v) ? $('#degeriAL option[value="' + seolink + '"]').prop("disabled", true).addClass("secimMenusuDisabled").text('that already exist, you can not add more than one') : "#hariciURL";
});
You are looping through the options, so you can just check if the option value, BolumleriAl, is not the excluded one.
Also, You can move the variables seolink and Exclude out of the loop, as these do change not every time.
var seolink = "https://example.com";
var Exclude = "#hariciURL"; //this will be never disabled
var Bölümler = ['test3', 'test7'];
$('#degereriAL').children('option').each(function() {
var currentValue = $(this).val();
if (currentValue == Exclude || $.inArray(currentValue, Bölümler) > -1) {
// The value is excluded (#hariciURL)
// OR the value is in the Bölümler array
} else {
$(this)
.prop("disabled", true)
.addClass("secimMenusuDisabled");
}
});
select {
min-width: 10em;
}
select option[disabled] {
color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="degereriAL" size="8">
<option value="https://example.com">Test</option>
<option value="#hariciURL">Test 2</option>
<option value="test3">Test 3</option>
<option value="test4">Test 4</option>
<option value="test5">Test 5</option>
<option value="test6">Test 6</option>
<option value="test7">Test 7</option>
<option value="test8">Test 8</option>
</select>

Get value from dropdownlist and create another dropdown list

I have created a dropdownlist and it looks like this
<select id="mySelect">
<option value="one">Do one</option>
<option value="two">Do two</option>
</select>
Firstly I would like NOT to have a submit button. The second thing I was searching is that when I select the first choice to appear another dropdown list and when i choose the second to appear a text input for the user to type something. Thank you and sorry for the English!
If you do not want to import any jQuery you can still do it with pure JavaScript.
Here is a demo
Just include the below script in your file as,
function myFun(){
var val = document.getElementById("mySelect");
var input = document.getElementById("myIn");
var sel = document.getElementById("myOtherSelect");
var sub = document.getElementById("mySubmit");
if(val.value == "one"){
sel.style.display = "block";
input.style.display = "none";
sub.style.display = "none";
}else if(val.value == "two"){
input.style.display = "block";
sub.style.display = "block";
sel.style.display = "none";
}else{
input.style.display = "none";
sub.style.display = "block";
sel.style.display = "none";
}
}
Now add the onchange event on your select as,
<select id="mySelect" onchange="myFun()">
<option value="emp" selected>Choose something</option>
<option value="one">Do one</option>
<option value="two">Do two</option>
</select>
<select id="myOtherSelect">
<option value="three">Do three</option>
<option value="four">Do four</option>
</select>
<input type="text" id="myIn">
<input type="submit" id="mySubmit">
Use jQuery to do something simple like:
$('#mySelect').on('change', function() {
$('#input').html('<input name="myname" value="'+this.value +'">');
})
JSFiddle

HTML Selection script between two droplists

I have two droplist in html built using tag.
<select name="List1" id="List1" onclick="GetVal()">
<option value="1" selected="selected">Mercurio</option>
<option value="2">Venus</option>
<option value="3">Tierra</option>
<option value="4">Marte</option>
</select>
<select name="List2" id="List2">
<option value="1" selected="selected">Hg</option>
<option value="2">Ve</option>
<option value="3">Ti</option>
<option value="4">Ma</option>
</select>
I have written a script such as the selection of an element from List2 relies on the selection of the corresponding element of List1.
<script language="javascript" type="text/javascript">
// <!CDATA[
function GetVal() {
var LSelect1 = document.getElementById('List1');
var LSelect2 = document.getElementById('List2');
switch (LSelect1.selectedIndex)
{
case 1:
LSelect2.selectedIndex = 1;
break;
case 2:
LSelect2.selectedIndex = 2;
break;
case 3:
LSelect2.selectedIndex = 3;
break;
default:
LSelect2.selectedIndex = 4;
}
}
// ]]>
</script>
However, the function works wrongly for the first element of the List1. Why?
selectedIndex is 0-based. A simpler way to do things might be like this:
<script language="javascript" type="text/javascript">
// <!CDATA[
function GetVal() {
var LSelect1 = document.getElementById('List1');
var LSelect2 = document.getElementById('List2');
LSelect2.selectedIndex = LSelect1.selectedIndex;
}
// ]]>
</script>