Dropdown menu to change background image does nothing - javascript

This is my first question on Stack Overflow (so sorry if I do something wrong)
Anyway, I'm trying to create a drop down menu that changes the background image of the website. However, when selecting the options, nothing happens.
EDIT My WORKING code for this is:
function changeTheme()
{
var e = document.getElementById("bg");
var strUser = e.options[e.selectedIndex].text;
if (strUser == "default")
{
document.body.style.backgroundImage = "url(Thresh_BG.png)";
}
if (strUser == "darkstar")
{
document.body.style.backgroundImage = "url(dark star.png)";
}
}
<div id="bg">
<form>
<select name="bg" id="bg" onchange="changeTheme();">
<option value="default">Default</option>
<option value="darkstar">Dark Star Thresh</option>
</select>
</form>
</div>

First, you have id collision in your HTML. You may change the id of your div to be anything other than bg; let's say bg1.
Then, you need to access the value of an option rather than its text, so it will be:
var strUser = e.options[e.selectedIndex].value;

Firstly, i would declare your variable outside the function with a more specific name than 'e'.
Also, you should add inner [single] quotes to your image .
It's always a good idea to include the full path even if it's local on your server. Makes it easier to spot an error. I include a jsbin witn my own images (they are used in the below snippet also)
Hope this helps
Welcome to stackoverflow!
var selecte = document.getElementById("bg");
function changeTheme() {
var strUser = selecte.options[selecte.selectedIndex];
if (strUser.value == "default") {
document.body.style.backgroundImage = "url('http://www.rachelgallen.com/images/purpleflowers.jpg')";
}
if (strUser.value == "darkstar") {
document.body.style.backgroundImage = "url('http://www.rachelgallen.com/images/yellowflowers.jpg')";
}
};
<form>
<select id="bg" onchange="changeTheme();">
<option value="default">Default</option>
<option value="darkstar">Dark Star Thresh</option>
</select>
</form>

for startes, I'm pretty sure you need more quotes.
Try changing it like this:
***Code***
if (strUser == "default")
{
document.body.style.backgroundImage = "url('Thresh_BG.png')";
}
if (strUser == "darkstar")
{
document.body.style.backgroundImage = "url('dark star.png')";
}
If you use the URL like that, you'll need to make sure that the background-images are in the same folder as the HTML. (Which is bad practice?). Better make a 'content' folder and make an 'images' folder there. Of course you would have to update your URL's to match the new location of your images. (relative, of course).
If I were you, I'd use a switch statement too (if you want to upgrade your webpage and you have more than two options, it's going to be hard to put multiple if-statements.
Something like this:
switch(strUser)
case "default":
document.body.style.backgroundImage = "url('Thresh_BG.png')";
break;
case "darkstar":
document.body.style.backgroundImage = "url('dark star.png')";
break;
***more options here***
default: break;
Edit
I also see you have two ID's the same, which is also bad practice as your Javascript doesn't know which one to pick. So you might want to change that.
Another small remarkt, are you sure you need the 'text' value of the select? You might want to ask for the value instead of the text.

function changeTheme(e)
{
var e = document.getElementById("bg");
var strUser = e.options[e.selectedIndex].value;
if (strUser == "default")
{
// document.body.style.backgroundImage = "url('img_tree.png')";
document.body.style.backgroundImage = "url('http://kenrockwell.com/nikon/d5300/sample-images/DSC_0024.jpg')";
}
else if (strUser == "darkstar")
{
document.body.style.backgroundImage = "url('https://www.w3schools.com/css/trolltunga.jpg')";
}
}
please check the jsfiddle link:
https://jsfiddle.net/jayesh24/bdxLvvbo/

here my working code check it
function changeTheme() {
console.log('work');
var e = document.getElementById("bg").value;
if (e == "default") {
document.body.style.backgroundImage = "url(1.jpg)";
}
if (e == "darkstar") {
document.body.style.backgroundImage = "url(2.jpg)";
}
}
<html>
<body background="1.jpg">
<div id="abc">
</div>
<form>
<select name="bg" id="bg" onchange="changeTheme();">
<option value="default">Default</option>
<option value="darkstar">Dark Star Thresh</option>
</select>
</form>
</body>
</html>

Related

Change Attribut when Specific Option is Selected in Dropdown List

So there is my following code :
index.html
<img id="crypto-pic" src="./assets/img/cryptos/btc.png" alt="crypto" height="15" width="15">
<select id="input-crypto" class="form-control">
<option value="bitcoin">Bitcoin</option>
<option value="ethereum">Ethereum</option>
...
...
...
</select>
script.js :
if($("#input-crypto option:selected").text() == bitcoin){
$('#crypto-pic').attr('src', './assets/img/cryptos/btc.png');
};
if($("#input-crypto option:selected").text() == ethereum){
$('#crypto-pic').attr('src', './assets/img/cryptos/eth.png');
};
The fact is that when Ethereum is selected in the list, the image don't change to eth.png.
Can you help me please, thanks.
I'd use an onChange event, and a switch statement for less code and more flexibility
$("#input-crypto").on("change", function(){
var imgSrc;
switch($(this).val()) {
case "ethereum":
imgSrc = './assets/img/cryptos/eth.png';
break;
case "anotherOption1":
imgSrc = './assets/img/cryptos/xxx.png';
break;
case "anotherOption2":
imgSrc = './assets/img/cryptos/xxx.png';
break;
default:
imgSrc = './assets/img/cryptos/btc.png';
}
$('#crypto-pic').attr('src', imgSrc);
});
You have missed single or double quotes around bitcoin and ethereum. Also if you are running the scripts without any function call or listener, it wont work.
For your better understanding, track the change of selection using .change() function and then check the latest selected value.
$("#input-crypto").change(function(){
if($("#input-crypto").val() == "bitcoin"){
$('#crypto-pic').attr('src', './assets/img/cryptos/btc.png');
};
if($("#input-crypto").val() == "ethereum"){
$('#crypto-pic').attr('src', './assets/img/cryptos/eth.png');
};
});
You can use .on() function to achieve it.
$('#input-crypto').on('change', function () {
var selectedOption = $(this).val();
if (selectedOption == "bitcoin") {
$('#crypto-pic').attr('src', './Content/img/cryptos/btc.png');
}
if (selectedOption == "ethereum") {
$('#crypto-pic').attr('src', './assets/img/cryptos/eth.png');
}
});

Vanilla JS - function to hide and show a div by clicking a button

I am having an issue; where when I click a button that takes the value from a drop-down list, it is supposed to show the div assigned to his matching value.
So far, my code do as intended, it shows the corresponding div, but then it reverts and hides it back 3 seconds after. It could be a simple mistake, your help is appreciated.
At the head:
var e = document.getElementById("graph_req_ID");
var indexValue = e.options[e.selectedIndex].value;
var strValue = e.options[e.selectedIndex].text;
function getGraphReq(){
if (strValue == "Default") {
graph3.style.display = "block";
} else {
graph3.style.display = "none";
}
}
My button:
<button onclick="getGraphReq()"></button>
The hidden div:
<div id="graph3">
<h4>this content should show after clicking the button</h4>
</div>
function getGraphReq(){
var e = document.getElementById("graph_req_ID");
var indexValue = e.options[e.selectedIndex].value;
var strValue = e.options[e.selectedIndex].text;
if (strValue == "Default") {
graph3.style.display = "block";
} else {
graph3.style.display = "none";
}
}
<select id="graph_req_ID">
<option value="Default">Default</option>
<option value="Default">foo</option>
</select>
<button onclick="getGraphReq()">Click me</button>
<div id="graph3">
<h4>this content should show after clicking the button</h4>
</div>
I moved those variables into the function. Then when you execute the function it will assign correct values to the variables. Is this the expected output you need.
Not sure what the issue with your code, but is that the intended behaviour?
var e = document.getElementById("graph_req_ID");
var indexValue = e.options[e.selectedIndex].value;
function getGraphReq() {
var strValue = e.options[e.selectedIndex].text;
if (strValue == "Default") {
graph3.style.display = "block";
} else {
graph3.style.display = "none";
}
}
getGraphReq();
<select id='graph_req_ID'>
<option value='Default'>Default</option>
<option value='Other' selected>Other</option>
</select>
<button onclick="getGraphReq()">getGraphReq</button>
<div id="graph3">
<h4>this content should show after clicking the button</h4>
</div>
If the element should not be visible onload and only by the click event then:
<div id="graph3" style="display:none">
Your code worked for me. Possibly something else in the file causing your issue. Hard to tell with what you posted.

Code to detect option value does not work as expected

I was attempting to do some string comparisons in javascript. I have seen several tutorials and examples but they do not seem to work. I am missing something fundamental?
Attempt 1
function addAspect(aspect) {
var print = document.createElement('p');
var ptext;
if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}
Doesnt work.
Then I found this example to which all readers said it worked fine
function addAspect() {
var print = document.createElement('p');
var ptext;
var aspect = String(document.getElementById("aspectResult").value);
if (aspect == "Option1") ptext = document.createTextNode("This is option1");
}
Doesnt work.
I also tried .toString() as well as the '===' exact match comparison.
Full code
<html>
<head>
<script type="text/javascript">
function addAspect()
{
var print = document.createElement('p');
var ptext;
var aspect = document.getElementById("aspectResult").value;
if (aspect == "Option1"){
ptext = document.createTextNode("This is option1");
}
print.appendChild(ptext);
document.getElementById("mainBlock").appendChild(print);
}
</script>
</head>
<body>
<form>
<select id="aspectResult">
<option value="Option1">Option1</option>
</select>
<input type="button" value="Check" onclick="addAspect()"/>
</form>
<span id="mainBlock">&nbsp</span>
</body>
</html>
Any suggestions?
First, a small introduction to how dropdowns work:
<select id="aspectResult">
<option value="Option1">Option1</option>
</select>
To read the selected value from the dropdown, you should do this:
var dropdown = document.getElementById('aspectResult'),
selectedValue = dropdown.options[dropdown.selectedIndex].value;
Then, you create the <p> element with a text node inside:
var p = document.createElement('p'),
txt;
if (selectedValue == 'Option1') {
txt = document.createTextNode('This is option 1');
}
Afterwards, you can append the newly created paragraph to the container of your choice:
var container = document.getElementById('mainBlock');
if (txt) {
p.appendChild(txt);
container.appendChild(p);
}
All together now!
If you are trying to add the ptext to the paragraph, you need to add two lines to the end:
function addAspect(aspect) {
var prnt = document.createElement('p');
var ptext;
if( aspect == "Option1" ) {
ptext = document.createTextNode("This is option1");
prnt.appendChild(ptext); // Add the text to the paragraph
document.body.appendChild(prnt); // Add the paragraph to the document
}
}
Your function creates a text node but then does nothing with it, so you code appears to do nothing at all. You need to append the text node to an element somewhere in the DOM:
document.body.appendChild(ptext);
Your full code appears to be working fine in IE9, Firefox 4 and Chrome 11. See http://jsbin.com/ekura5/.

How can I disable an <option> in a <select> based on its value in JavaScript?

I have a <select> with a number of <option>s. Each has a unique value. I need to disable an <option> with a given defined value (not innerHTML).
Anyone have an idea how?
JavaScript, in 2022
You can use querySelectorAll, and forEach off of the resulting NodeList to do this same thing more easily in 2022.
document.querySelectorAll("#foo option").forEach(opt => {
if (opt.value == "StackOverflow") {
opt.disabled = true;
}
});
Do be mindful of string-comparisons, however. 'StackOverflow' and 'stackoverflow' are not the same string. As such, you can call .toLowerCase() on strings before comparing, or even go with a case-insensitive regular expression comparison like the this:
if ( /^stackoverflow$/i.test(option.value) ) {
option.disabled = true;
}
Pure Javascript (2010)
With pure Javascript, you'd have to cycle through each option, and check the value of it individually.
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}
Without enabling non-targeted elements:
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}
###jQuery
With jQuery you can do this with a single line:
$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");
Without enabling non-targeted elements:
$("option[value='stackoverflow']").attr("disabled", "disabled");
​
Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});
Without enabling non-targeted elements:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled");
}
});
Set an id to the option then use getElementById and disable it when x value has been selected, like so:
<body>
<select class="pull-right text-muted small"
name="driveCapacity" id=driveCapacity onchange="checkRPM()">
<option value="4000.0" id="4000">4TB</option>
<option value="900.0" id="900">900GB</option>
<option value="300.0" id ="300">300GB</option>
</select>
</body>
<script>
var perfType = document.getElementById("driveRPM").value;
if(perfType == "7200"){
document.getElementById("driveCapacity").value = "4000.0";
document.getElementById("4000").disabled = false;
}else{
document.getElementById("4000").disabled = true;
}
</script>
For some reason other answers are unnecessarily complex, it's easy to do it in one line in pure JavaScript:
Array.prototype.find.call(selectElement.options, o => o.value === optionValue).disabled = true;
or
selectElement.querySelector('option[value="'+optionValue.replace(/["\\]/g, '\\$&')+'"]').disabled = true;
The performance depends on the number of the options (the more the options, the slower the first one) and whether you can omit the escaping (the replace call) from the second one. Also the first one uses Array.find and arrow functions that are not available in IE11.
Use a straightforward selector:
document.querySelector('select[name="theName"] option[value="theValue"]').disabled = true;
Here with JQuery, if anybody search it:
var vals = new Array( 2, 3, 5, 8 );
select_disable_options('add_reklamaciq_reason',vals);
select_disable_options('add_reklamaciq_reason');
function select_disable_options(selectid,vals){
var selected = false ;
$('#'+selectid+' option').removeAttr('selected');
$('#'+selectid+' option').each(function(i,elem){
var elid = parseInt($(elem).attr('value'));
if(vals){
if(vals.indexOf(elid) != -1){
$(elem).removeAttr('disabled');
if(selected == false){
$(elem).attr('selected','selected');
selected = true ;
}
}else{
$(elem).attr('disabled','disabled');
}
}else{
$(elem).removeAttr('disabled');
}
});
}
I would like to give you also the idea to disable an <option> with a given defined value (not innerhtml). I recommend to it with jQuery to get the simplest way. See my sample below.
HTML
Status:
<div id="option">
<select class="status">
<option value="hand" selected>Hand</option>
<option value="simple">Typed</option>
<option value="printed">Printed</option>
</select>
</div>
Javascript
The idea here is how to disable Printed option when current Status is Hand
var status = $('#option').find('.status');//to get current the selected value
var op = status.find('option');//to get the elements for disable attribute
(status.val() == 'hand')? op[2].disabled = true: op[2].disabled = false;
You may see how it works here:
https://jsfiddle.net/chetabahana/f7ejxhnk/28/
You can also use this function,
function optionDisable(selectId, optionIndices)
{
for (var idxCount=0; idxCount<optionIndices.length;idxCount++)
{
document.getElementById(selectId).children[optionIndices[idxCount]].disabled="disabled";
document.getElementById(selectId).children[optionIndices[idxCount]].style.backgroundColor = '#ccc';
document.getElementById(selectId).children[optionIndices[idxCount]].style.color = '#f00';
}
}

Dynamicaly Changing the <textarea > size,style

How can i change the field size diynamicaly?
I have a select field and there are 3 options with different values.
So if the user selects one of them in the you see the values.
But how can i change the size that the values from option field fits in the
function changeText()
{
var select = document.getElementById("surl");
var textfield = document.getElementById("turl");
var bold = document.getElementById("burl");
var link = document.getElementById("linkText");
if(bold.style.display == "none")
bold.style.display = "";
//if(link.innerHtml)
bold.innerHtml = select.value;
//if(link.innerHTML !="")
link.innerHTML= select.value;
textfield.value = select.value;
}
<b>Sample: </b><select id="surl" onchange="changeText();" style="visibility: visible;" name="linkText">
<option>Select LinkText</option>
<option value="<a href='http://www.doesntexist.dsdsd/'>Want sign? http://www.doesntexist.dsdsd</a>">
Variant1
</option>
<option value="<a href='http://www.doesntexist.dsdsd/'>Wanna killme? http://www.doesntexist.dsdsd</a>">
Variant 2
</option>
</select>
<br />
<div class="succes">
<span id="burl" style="display: none"><br /><a id="linkText" href="http://www.doesntexist/"></a></span>
</div>
</p>
<p>
<textarea id="turl" style="">
text...
</textarea>
</p>
Sorry, I must’ve misunderstood your problem.
So you want to resize a textarea dynamically based on what, its contents? You could use the jQuery autoResize plugin for this…
A quick 'n' dirty jQuery solution would be the following:
$('input#foo-option-1').bind('change, click', function() {
if ($(this).is(':checked')) {
$('textarea').css('height', '150px');
}
});
$('input#foo-option-2').bind('change, click', function() {
if ($(this).is(':checked')) {
$('textarea').css('height', '250px');
}
});
$('input#foo-option-3').bind('change, click', function() {
if ($(this).is(':checked')) {
$('textarea').css('height', '350px');
}
});
Of course, this code isn’t very DRY. Moreover, modifying CSS properties through JavaScript is never a very good idea — it’s better to add classes dynamically through JS and specify the actual CSS in your CSS files (duh).
For example:
<script type="text/javascript">
document.getElementById("textarea_id").style.width = "300px";
document.getElementById("textarea_id").style.width = "200px";
</script>
First of all i thought there are more devs who can help; any way here is the answer
first create a function which calculates the strlen
function strlen(strVar)
{
return(strVar.length)
}
Second create a var tfcount
var tfcount = strlen(select.value);
and finaly
textfield.style.width = tfcount < 110 ? tfcount = 110 : 3.5*tfcount+"px";
textfield.style.height = tfcount < 110 ? tfcount = 110 : tfcount/2.5+"px";

Categories