How to display a hidden image when a certain <option> is selected? - javascript

Is it possible to get a hidden image to show when a certain option from a dropdown input box is selected by the user and then the submit button is pressed, by using either Jquery or Javascript?
I am unsure how to obtain the option that the user selected?
This is the current code that i have to hide the images:
<form>
Please select which type of training program you would like: <select name="program">
<option id="hiit"selected>HIIT High Intensity Training</option>
<option id="cardio">Cardio Vascular</option>
<option id="strength">Strength Training</option>
<option id="toning">Toning</option>
</select>
Please select which area you are wanting to target: <select id="body">
<option id="upper"selected>Upper</option>
<option id="core">Core</option>
<option id="lower">Lower</option>
<option id="fb">Full body</option>
</select>
<br><br><input type="button" value="Submit" onclick="choice"> <br>
</form>
<br>
<!-- program choices -->
<img src ="cardio.jpg" width ="350" height="200" id="cardio" class="pics">
<img src ="hiit.jpg" width = "350" height="200" id="hiit" class="pics">
<img src ="strength.jpg" width = "350" height="200" id="strength" class="pics">
<img src ="toning.jpg" width = "350" height="200" id="toning" class="pics">
<script>
//hide pictures
$('.pics').css("display","none");
</script>

First, I changed up some of your html. As charlietfl said, id's have to be unique. So, I made all the ids you gave to the options the values instead. I also changed your input of type="button" to a button with type="submit". I then went to the initial form tag and added an onsubmit attribute where the function revealImage() will be triggered.
The Jquery function is quite simple. It first hides all the images then takes the value selected from the first select option, and reveals the corresponding picture. My code specifically has your imgs' ids equal to the value plus "Id", but you can make your image ids completely different and use a switch-case statement to reveal the specific image with the value the user gave. Look here to learn more.
Finally, I removed your initial javascript of hiding the images and just went to the css and set the images' displays to none.
I also added some css to the images as otherwise they wouldn't show up (as I don't have your image sources). Just delete that and add your sources.
Here are some links to help you understand some of the things I did in case you're confused:
Why ID's must be unique.
Show / Hide
Jquery val()
function revealImage(){
$(".pics").hide();
var value = $("#program").val();
var picId = value + "Pic";
$("#" + picId).show();
return false;
}
.pics:nth-of-type(1){
background-color:red;
}
.pics:nth-of-type(2){
background-color:blue;
}
.pics:nth-of-type(3){
background-color:green;
}
.pics:nth-of-type(4){
background-color:yellow;
}
.pics {
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="return revealImage();">
Please select which type of training program you would like:
<select id="program">
<option value="hiit">HIIT High Intensity Training</option>
<option value="cardio">Cardio Vascular</option>
<option value="strength">Strength Training</option>
<option value="toning">Toning</option>
</select>
Please select which area you are wanting to target:
<select id="body">
<option value="upper">Upper</option>
<option value="core">Core</option>
<option value="lower">Lower</option>
<option value="fb">Full body</option>
</select>
<br><br>
<button type="submit"> Submit </button><br>
</form>
<br>
<!-- program choices -->
<img src="" width ="350" height="200" id="cardioPic" class="pics">
<img src="" width = "350" height="200" id="hiitPic" class="pics">
<img src="" width = "350" height="200" id="strengthPic" class="pics">
<img src="" width = "350" height="200" id="toningPic" class="pics">

Somewhat similar to #Tuneer's answer. I left your markup alone as much as possible:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Hide elements with CSS:
<style>
img.pics{
display: none;
}
</style>
</head>
<body>
<div>
Please select which type of training program you would like:
<select name="program" id="program">
<option id="hiit" selected="selected">HIIT High Intensity Training</option>
<option id="cardio">Cardio Vascular</option>
<option id="strength">Strength Training</option>
<option id="toning">Toning</option>
</select>
Please select which area you are wanting to target:
<select id="body">
<option id="upper" selected="selected">Upper</option>
<option id="core">Core</option>
<option id="lower">Lower</option>
<option id="fb">Full body</option>
</select>
<input type="button" value="Submit" id="submit">
Altered IDs here to be data- attributes. You cannot have the same id value on more than one element, but you are free to use the same value multiple times in data- attributes:
<!-- program choices -->
<img src ="cardio.jpg" width ="350" height="200" data-idval="cardio" class="pics" alt="cardio">
<img src ="hiit.jpg" width = "350" height="200" data-idval="hiit" class="pics" alt="hiit">
<img src ="strength.jpg" width = "350" height="200" data-idval="strength" class="pics" alt="strength">
<img src ="toning.jpg" width = "350" height="200" data-idval="toning" class="pics" alt="toning">
<script src="jquery.min.js" type="text/javascript"></script>
<script>
Attach simple click handler to button. This code ensures that all images are initially hidden, and then finds the image with the data- attribute matching the id of the selected program. The selected image element then has CSS applied to display it.
$('#submit').click(function(){
$('.pics').css("display","none");
$('img[data-idval="'+$('#program > option:selected').attr('id')+'"]').css({'display':'block'});
});
</script>
</div>
</body>
</html>

Related

Using JSON to retrieve different id from data base

I have an HTML img tag with an empty src and I use JSON and jquery to retrieve the src of the img from the database when the user hovers over a parent span that contain the img tag. The problem is when I retrieve the src with JSON everything is fine and the image src is retrieved but I a loop set for this span in the very same page, so when the first image is already retrieved it's src is applied for the other looped span images. It is like retrieving the same id of the first image for the other different looped images that suppose to have different id for different content image contents.
here's is my code :
$(document).ready(function(){
$('#key').hover(function(){
var id=$('#im').attr('value');
$.post('getjson.php',{id:id},function(data){
$('img').attr('src',data.user_img);
},'json');
});
});
Here is the HTML
{loop="data"} <span class="foo" id="key">{$value.user_key}</span> <span class="foo">
<img alt="ther is an image here" src="" value="{$value.id}" id="im"/></span>
The problem is that you have duplicated IDs on your page. So, $('#key') will always return the first DIV with the id key, the same for $('#im'). Instead this $('img') will select all images on your page. Here is a demo to illustrate the problem:
console.log("$('#key') count:"+$('#key').length);
console.log("$('#img') count:"+$('#key').length);
console.log("$('img') count:"+$('img').length);
$('#key').hover(function(){
console.log("ID hovered: "+$('#im').attr('value'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="key"> Div 1
<img src="" id="im" value="1" />
</div>
<div id="key"> Div 2
<img src="" id="im" value="2" />
</div>
<div id="key"> Div 3
<img src="" id="im" value="3" />
</div>
<div id="key"> Div 4
<img src="" id="im" value="4" />
</div>
To solve that you need to use another selector, for example, use a class:
$(document).ready(function(){
$('.my-selector').hover(function(){
//This will select all images inside 'this' (hovered .key)
var img = $('img', this);
$.post('getjson.php',{id : img.attr('value')},function(data){
img.attr('src',data.user_img);
},'json');
});
});
HTML:
{loop="data"} <div class="my-selector"> <!-- add parent div -->
<span class="foo" id="key">{$value.user_key}</span>
<span class="foo">
<img alt="ther is an image here" src="" value="{$value.id}" id="im"/>
</span>
</div>
Try changing
$('img').attr('src',data.user_img);
to
$("img[value='"+ id +"']").attr('src',data.user_img);
It is because you are setting the source to all images on the page.
$('img') should be replaced with $('#key')
in your case the code should be :
$(document).ready(function(){
$('#key').hover(function(){
var img = this;
var id=$('#im').attr('value');
$.post('getjson.php',{id:id},function(data){
$(img).attr('src',data.user_img);
},'json');
});
});

Easier way to show link from dropdown using Jquery

This is my first attempt at JQuery, I am building a world clock using an embedded iframe from http://www.timeanddate.com - the concept is the user selects the city from the dropdown and it will show the correct time for that city
<div>
<select>
<option value="n136" selected>London</option>
<option value="n240">Sydney</option>
<option value="n179">New York City</option>
</select>
</div>
<div class ="n136 time"><iframe src="https://freesecure.timeanddate.com/clock/i50ppgou/n136/tluk/fcf90/tct/pct/ftb/bo2/pa10/th1" frameborder="0" width="80" height="38" allowTransparency="true"></iframe></div>
<div class ="n240 time"><iframe src="https://freesecure.timeanddate.com/clock/i50ppgou/n240/tluk/fcf90/tct/pct/ftb/bo2/pa10/th1" frameborder="0" width="80" height="38" allowTransparency="true"></iframe></div>
<div class ="n179 time"><iframe src="https://freesecure.timeanddate.com/clock/i50ppgou/n179/tluk/fcf90/tct/pct/ftb/bo2/pa10/th1" frameborder="0" width="80" height="38" allowTransparency="true"></iframe></div>
JQuery
$(document).ready(function() {
$("select").change(function() {
$(this).find("option:selected").each(function() {
if ($(this).attr("value") == "n136") {
$(".time").not(".n136").hide();
$(".n136").show();
} else if ($(this).attr("value") == "n240") {
$(".time").not(".n240").hide();
$(".n240").show();
} else if ($(this).attr("value") == "n179") {
$(".time").not(".n179").hide();
$(".n179").show();
} else {
$(".time").hide();
}
});
}).change();
});
It works.
FIDDLE
The problem is I have 10 more world times to add in, this will become a really large script and will load 13 world times, hiding 12, this seems really bad practice, I think it could be vastly improved if only one IFrame is loaded, then when the user selects a city from the dropdown the value change part of the URL of the Iframe (as if the n*** number is a variable) to the div class as each of them are the correct codes for each city. That would be much more efficent.
However I seem to have hit my limit with JQuery, if anyone could help out or even get me started it would be greatly appreciated.
Use the keyword this in your selector and change the src of one iframe:
HTML:
<div>
<select>
<option value="n136" selected>London</option>
<option value="n240">Sydney</option>
<option value="n179">New York City</option>
</select>
</div>
<div class="n136 time">
<iframe src="https://freesecure.timeanddate.com/clock/i50ppgou/n136/tluk/fcf90/tct/pct/ftb/bo2/pa10/th1" id="timeDisplay" frameborder="0" width="80" height="38" allowTransparency="true"></iframe>
</div>
JS:
$(document).ready(function() {
$("select").change(function() {
$("#timeDisplay")[0].src = "https://freesecure.timeanddate.com/clock/i50ppgou/" + $(this).attr("value") + "/tluk/fcf90/tct/pct/ftb/bo2/pa10/th1";
}).change();
});
Fiddle: http://jsfiddle.net/p8ARq/610/
Try this. The whole idea is to change the src attribute of the iframe tag based on appending the selected value from the dropdown.
$(document).ready(function() {
$("select").change(function() {
var value = $(this).val();
$('iframe').attr("src","https://freesecure.timeanddate.com/clock/i50ppgou/" + value + "/tluk/fcf90/tct/pct/ftb/bo2/pa10/th1")
});
});
Working example : http://jsfiddle.net/DinoMyte/p8ARq/612/
Do something like this
==HTML==
<div>
<select>
<option value="n136" selected>London</option>
<option value="n240" >Sydney</option>
<option value="n179">New York City</option>
</select>
</div>
<iframe id="AllTime" src="" frameborder="0" width="80" height="38" allowTransparency="true"></iframe>
==JS==
<script>
var f=$("iframe#AllTime"),s=$("select"), k=s.find("option:selected").val();
//When Zone Change Do this
s.change(function() {
var n=$(this).val();
f.attr("src","https://freesecure.timeanddate.com/clock/i50ppgou/"+n+"/tluk/fcf90/tct/pct/ftb/bo2/pa10/th1");
});
//At first Do this
f.attr("src","https://freesecure.timeanddate.com/clock/i50ppgou/"+k+"/tluk/fcf90/tct/pct/ftb/bo2/pa10/th1");
</script>
==Another JS Approach==
<script>
var f=$("iframe#AllTime"),s=$("select"), k=s.find("option:selected").val();
//When Zone Change Do this
function ChangeTimeZone(t){
f.attr("src","https://freesecure.timeanddate.com/clock/i50ppgou/"+t+"/tluk/fcf90/tct/pct/ftb/bo2/pa10/th1");
}
//User change time zone
s.change(function() {
var n=$(this).val();
ChangeTimeZone(n);
});
//At first Do this
ChangeTimeZone(k);
</script>

selection menu for iframe src using javascript

I found out how to use javascript to change the iframe src, but when I made a selection menu that allows you to choose the url to load in, it only loads the first option in the menu, even when you select a different url. I got it to work once, but I made a few changes and it wouldn't let me go all the way back with undo. Here's what I've got:
<iframe src="http://jquery.com/" id="myFrame" width="500" height="500" scrolling="no" frameborder="0"></iframe>
<div>
<select id="selected2">
<option value="http://linux.com">1</option>
<option value="http://microsoft.com">2</option>
<option value="http://apple.com">3</option>
</select>
<button onclick="loadPages()">Click Me</button>
<script>
function loadPages() {
var loc = dataCap;
document.getElementById('myFrame').setAttribute('src', loc);
}
var dataCap = document.getElementById("selected2").value;
</script>
The thing is that you're only getting the value the first time around, when your script executes. In order to get the currently selected value, you need to get the value right when you click the button, inside of the onclick function.
http://jsfiddle.net/v74ypgwk/1/
<iframe src="http://jquery.com/" id="myFrame" width="500" height="500" scrolling="no" frameborder="0"></iframe>
<div>
<select id="selected2">
<option value="http://linux.com">1</option>
<option value="http://microsoft.com">2</option>
<option value="http://apple.com">3</option>
</select>
<button onclick="loadPages()">Click Me</button>
<script>
var urlSelect = document.getElementById('selected2'),
myFrame = document.getElementById('myFrame');
function loadPages() {
var loc = urlSelect.value;
// You can also do -> myFrame.src = loc;
myFrame.setAttribute('src', loc);
}
</script>

Load src of iframe using drop down menu and then change

I have the following code
<script type="text/javascript">
function newSrc() {
var e = document.getElementById("MySelectMenu");
var newSrc = e.options[e.selectedIndex].value;
document.getElementById("MyFrame").src=newSrc;
}
</script>
<iframe name="content" src="" style="position: absolute; left: 0px; top: 28px;" allowtransparency="true" border="0" scrolling="yes" width="100%" frameborder="0" height="90%" id="MyFrame"></iframe>
<select id="MySelectMenu">
<option value="http://www.example.com">Example Site 1</option>
<option value="http://www.example2.com">Example Site 2</option>
</select>
<button onClick="newSrc();">Load Site</button>
This works well, it loads the source of the iframe depending on what option is selected from the menu. Now, what I'd like to do, after the option is chosen from the drop down and the Load Site button is clicked, is load the source from the option into the iframe, and then redirect the iframe ONCE after say...1 second.
So if Example Site 2 is chosen, the user clicks Load Site, http://www.example2.com is loaded, and the iframe is then redirected to http://www.example2.com/admin.
Thanks
Just trying to help! Here's a solution (working example you can play with the code http://jsbin.com/cakuh/1/), it's just a sketch but you should understand what to do:
<iframe name="content" src="" style="position: absolute; left: 0px; top: 28px;" allowtransparency="true" border="0" scrolling="yes" width="100%" frameborder="0" height="90%" id="MyFrame"></iframe>
<select id="MySelectMenu">
<option value="http://www.games.com">Games</option>
<option value="http://www.bbc.com">BBC</option>
</select>
<button>Load Site</button>
$(function(){
$('button').on('click', function(){
var src = $("#MySelectMenu option:selected").attr('value'),
myTimeout = null;
// first we de-attach and re-attach an event load
$('iframe[name="content"]').off('load').on('load', function(){
myTimeout = setTimeout(function(){
clearTimeout(myTimeout);
$('iframe[name="content"]').off('load');
// you see, we concat '/admin' to the src
$('iframe[name="content"]').attr('src', src + '/admin');
}, 1000);
});
// this will change the iframe src and load the page, triggering the iframe load event
$('iframe[name="content"]').attr('src', src);
});
});

Javascript img tag src switch function not working

I have a small app the uses 3 images as buttons, the images are different colors, above the image buttons there is a big pair of glasses, depending on what color button you press the color of the glasses will change to match the color of the button that was pressed. The problem is I am getting a "Cannot set src to null" error.
Here is a jsfiddle: http://jsfiddle.net/vAF8S/
Here is the function
//Functions that change the glasses image
function changeColor(a){
var img = document.getElementById("imgG");
img.src=a;
}
you have two Id's for the tag. you should have only one ID. change your html.
<section id="banner" >
<img id="imgG" src="images/orangeG.png"><br>
<img id="wcolorButton" src="images/whiteT.png" />
<img id="bcolorButton" src="images/blueT.png" />
<img id="ocolorButton" src="images/orangeT.png" onClick="changeColor('images/whiteG.png')" />
</section>
FIDDLE
you are getting this error because you have applied ID twice to the same element
use this HTML
<section id="banner" >
<img class="glasses" id="imgG" src="images/orangeG.png"><br>
<img class="wcolorButton" src="images/whiteT.png" />
<img class="bcolorButton" src="images/blueT.png" />
<img class="ocolorButton" src="images/orangeT.png" onClick="changeColor('images/whiteG.png')" />
</section>

Categories

Resources