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');
}
});
Related
I would like to check if the mark I selected and input value are the same or not, but the alert in js works even though when they are same. Here is my code! Thanks for your support!
HTML
<select id="mark">
<option value="o">o</option>
<option value="x">x</option>
</select>
<input type="text" name="block%s" id="block" onchange="check()">
JS
var mark = document.getElementById("mark").value;
var block = document.getElementById("block").value;
function check() {
if (block != mark) {
alert ('Your mark is wrong');
return false;
} else {
return true;
}
}
You need to put these variables inside function, otherwise there values are determined at the beginning and won't change afterwards.
function check(){
var mark=document.getElementById("mark").value;
var block=document.getElementById("block").value;
if( block != mark) {
alert ('Your mark is wrong');
return false;
}
else{
return true;
}
}
<select id="mark">
<option value="o">o</option>
<option value="x">x</option>
</select>
<input type="text" name="block%s" id="block" onchange="check()">
First of all create the function check() .
You can get value of options by selectedIndex or selectedValue
var e = document.getElementById("mark");
var strUser = e.options[e.selectedIndex].value;
after that compare the value of selectedValue and input text and display appropriate message according to need in alert
Your JavaScript code should be like this : (The block var declared after the function)
<script>
var mark=document.getElementById("mark").value;
function check() {
var block = document.getElementById("block").value;
console.log(mark + '-' + block)
if (block != mark) {
alert ('Your mark is wrong');
return false;
} else {
return true;
}
}
</script>
The function check should include all variables. Here, Try this:
function check(){
var mark=document.getElementById("mark").value;
var block=document.getElementById("block").value;
if(block != mark) {
alert ('Your mark is wrong');
return false;
}
else{
alert ('Your mark is right');
return true;
}
}
Variables should be inside function
Try following:
HTML
<input type="text" name="block%s" id="block" onchange="check(this)">
Javscript
function check(inputBox) {
var markBox = document.getElementById("mark");
var mark = markBox[markBox.selectedIndex].value;
var block = inputBox.value;
if (block != mark) {
alert ('Your mark is wrong');
return false;
} else {
return true;
}
}
You can also use onblur of input box to call check() when user leaves the input box.
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>
I created JavaScript bellow the $titleBlock, and when I load the page, it's not affecting the select-box. What should I change?
$titleBlock->addCell(
'<select id="my-select" size="1" class="text" name="user_id">
"'.$option_str.'"
</select>'
);
<script type="text/javascript">
var mySelect = document.getElementById('my-select');;
var setBgColor = function (select) {
select.style.color = select.options[select.selectedIndex].style.color;
};
mySelect.onchange = function () {
setBgColor(this);
document.form_buttons.submit();
};
if(-1 != mySelect.selectedIndex) {
setBgColor(mySelect);
};
</script>
what do you see in log? when
if(-1 != mySelect.selectedIndex) {
console.log(mySelect.selectedIndex);
setBgColor(mySelect);
}
If nothing then that means you are not at all getting handle of select box try to put the script in onload and then try that should work
I am trying to create a normal javascript switch that'll give me an alert message and image based on what the user has selected from a drop down menu
here's what I have so far
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<h1>How are you feeling?</h1>
<img id="feelimg" src="Images/questionSun.jpg" alt="question sun">
<select id="feeling" onChange="changeFeeling();">
<option value="question">Question</option>
<option value="happy">Happy</option>
<option value="sad">Sad</option>
<option value="cool">Cool</option>
<option value="unsure">Unsure</option>
</select>
<script type="text/javascript">
var curFeel = document.getElementById('feeling').value;
function changeFeeling(){
switch (curFeel) {
case 'question': {
document.getElementById("feelimg").src = "Images/questionSun.jpg";
alert("Please make a selection or go back to bed!");
break;
}
case 'happy': {
document.getElementById("feelimg").src = "Images/happySun.jpg";
alert("I am glad you are happy");
return curFeel;
break;
}
case 'sad': {
document.getElementById("feelimg").src = "Images/sadSun.jpg";
alert("I am sorry you are sad");
break;
}
case 'cool': {
document.getElementById("feelimg").src = "Images/coolSun.jpg";
alert("It's great you are feeling cool!");
break;
}
case 'unsure': {
document.getElementById("feelimg").src = "Images/unsureSun.jpg";
alert("I hope you get past that soon!");
break;
}
}
}
</script>
</body>
</html>
No matter what I do it is stuck on case question. It needs to be javascript. I am not allowed to use jquery for this particular problem.
Just move your var declaration inside your function.
The way you have done the var was getting populated with the value once the javascript gets loaded, moving it to the function it will be populated at the onChange event and then the switch works nice.
<script type="text/javascript">
var curFeel = document.getElementById('feeling').value;
function changeFeeling(){
curFeel = document.getElementById('feeling').value;
switch (curFeel) {
case 'question': {
document.getElementById("feelimg").src = "Images/questionSun.jpg";
alert("Please make a selection or go back to bed!");
break;
}
case 'happy': {
document.getElementById("feelimg").src = "Images/happySun.jpg";
alert("I am glad you are happy");
return curFeel;
break;
}
case 'sad': {
document.getElementById("feelimg").src = "Images/sadSun.jpg";
alert("I am sorry you are sad");
break;
}
case 'cool': {
document.getElementById("feelimg").src = "Images/coolSun.jpg";
alert("It's great you are feeling cool!");
break;
}
case 'unsure': {
document.getElementById("feelimg").src = "Images/unsureSun.jpg";
alert("I hope you get past that soon!");
break;
}
}
}
</script>
Another way that I would recomend is to not use this global variable and just use the parameter using the onchange like that:
<select id="feeling" onChange="changeFeeling(this);">
<option value="question">Question</option>
<option value="happy">Happy</option>
<option value="sad">Sad</option>
<option value="cool">Cool</option>
<option value="unsure">Unsure</option>
</select>
<script type="text/javascript">
function changeFeeling(curFeel){
switch (curFeel.value) {
case 'question': {
document.getElementById("feelimg").src = "Images/questionSun.jpg";
alert("Please make a selection or go back to bed!");
break;
}
case 'happy': {
document.getElementById("feelimg").src = "Images/happySun.jpg";
alert("I am glad you are happy");
return curFeel;
break;
}
case 'sad': {
document.getElementById("feelimg").src = "Images/sadSun.jpg";
alert("I am sorry you are sad");
break;
}
case 'cool': {
document.getElementById("feelimg").src = "Images/coolSun.jpg";
alert("It's great you are feeling cool!");
break;
}
case 'unsure': {
document.getElementById("feelimg").src = "Images/unsureSun.jpg";
alert("I hope you get past that soon!");
break;
}
}
}
</script>
Make your switch variable event.target.value and it will work how you want it to.
To access a global var from inside a function
var curFeel;
function changeFeeling(){
curFeel = event.target.value;
switch (curFeel) {
case 'question': {
....
}
}
}
That way the variable curFeel will be whatever the selected value is globally.
Heres a Codepen
I think Diego Garcia has provided the answer, but I'd like to suggest a simple improvement to the code generally for you to collect a few bonus points (should they be available).
var curFeel; // Value is not being used before changeFeeling function call, so you only need declare it rather than assign a value
function changeFeeling(){
var picture, message; // Declare variables to contain the decided upon image and alert message
var pictureFiles = 'Images/'; // Where your image files are kept, so you don't repeat a dozen times below
curFeel = document.getElementById('feeling').value;
switch (curFeel) {
case 'question': {
picture = "questionSun.jpg";
message = "Please make a selection or go back to bed!";
break;
}
case 'happy': {
picture = "happySun.jpg";
message = "I am glad you are happy";
break;
}
case 'sad': {
picture = "sadSun.jpg";
message = "I am sorry you are sad";
break;
}
case 'cool': {
picture = "coolSun.jpg";
message = "It's great you are feeling cool!";
break;
}
case 'unsure': {
picture = "unsureSun.jpg";
message = "I hope you get past that soon!";
break;
}
}
// Set image and alert message!
document.getElementById("feelimg").src(pictureFiles + picture);
alert(message);
}
Reasons Why:
The above is easier to read
In the event that the ID of the picture element, or the location of the image files, changes you only need to change it in one place rather than a dozen
And the same if the behaviour around the message alert changes, e.g. instead of using the alert() function, the message is inserted into a div element on the page instead for example (only one change required rather than a dozen)
Hope this helps.
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';
}
}