Easier way to show link from dropdown using Jquery - javascript

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>

Related

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

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>

using if/else statement in html

I am new to building websites, so can anyone please help me?
I want to use an if/else statement in html to display text and some movies on my website. Below I have added my html code, but it sees the if/else statement as a text and not as a code. How can I get this if/else statement to work, using the temperature output from my js code with openweather API?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://s3.amazonaws.com/codecademy-content/courses/ltp/css/bootstrap.css">
<link rel="stylesheet" href="main.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type='text/javascript' src='app.js'></script>
</head>
<body>
<input type="text" value="In which city are you?" id="city">
<button id="search">Submit</button>
<p id="demo"></p>
<p>The weather outside is: </p>
<div class= "weather">
Fill in your location first
</div>
<p>What will you be making for dinner tonight?</p>
<div class="inspiration">
Give me some inspiration!
<div class="recipe">
if (Math.round(data.main.temp) == null) {
<p>Fill in your location first</p>
} else {
if (Math.round(data.main.temp) < -5) {
<p> Oh man.. It is way too cold! Stay inside the whole day and have a nice and hot turkey soup. Make sure you don’t freeze </p>
<iframe width="392" height="220" src="https://www.youtube.com/embed/SdJfxGo5PQM?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
} else if (Math.round(data.main.temp) === -5 - 5){
<p>wow look at that weather, it is quite cold.. With those temperatures a chicken and fries curry would be nice don’t you think? </p>
<iframe width="392" height="220" src="https://www.youtube.com/embed/PfoOxeTXdXA?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
} else if (Math.round(data.main.temp) === 5 - 15) {
<p> Today is a good day, don’t you think? Some cheeseburger cups would taste great!</p>
<iframe width="392" height="220" src="https://www.youtube.com/embed/k-2KdH6k0nA?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
} else if (Math.round(data.main.temp) === 15 - 25) {
<p> With those temperatures it is not a bad idea to have a BBQ! Here is a recipe for hummus to have as a side dish!</p>
<iframe width="4392" height="220" src="https://www.youtube.com/embed/XN4aSh-Dj4Y?rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
} else if (Math.round(data.main.temp) === 25-35) {
<p> Damn it's hot! I can hardly think of anything to have for dinner to cool down. </p>
<p> Just go get some ice cream please. </p>
} else {
<p>Those temperatures are insane! Are you in a sauna?</p>
}
}
</div>
</div>
</div>
</body>
</html>
this is my js code
$(document).ready(function(){
$('#search').click(function(){
var city = $('#city').val();
console.log(city);
$.getJSON( "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=9334f947893792dcb9b2e2c05ae23eb0", function( data ) {
$('.weather').html(Math.round(data.main.temp)+ ' degrees Celcius');
});
});
});
JavaScript code needs to be defined inside <script> tags otherwise it won’t work.
Just put this code in the same function below your jQuery code. And create an empty <div> tag with any ID in place of the <p> and <iframe> then populate them with jQuery. Then depending on your condition change its innerHTML (using the jQuery function html()). Example:
$(document).ready(function()
{
$('#search').click(function()
{
var city = $('#city').val();
console.log(city);
$.getJSON( "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=metric&appid=9334f947893792dcb9b2e2c05ae23eb0", function( data )
{
$('.weather').html(Math.round(data.main.temp)+ ' degrees Celcius');
});
});
if (Math.round(data.main.temp) < -5)
{
$("#YOU_CHOSEN_ID").html("<p> Oh man.. It is way too cold! Stay inside the whole day and have a nice and hot turkey soup. Make sure you don’t freeze </p>
<iframe width='392' height='220' src='https://www.youtube.com/embed/SdJfxGo5PQM?rel=0&showinfo=0' frameborder='0' allowfullscreen></iframe>")
}
});
I used one condition. Add the rest like I did with this one.
If you’re still facing problems let me know so I can help you.

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 working in an opposite manner

I have been trying to use a "select" list along with javascript. I did a Javascript function that hide or show parts of html code but it's working in the opposite way and i can't figure out where I went wrong coz the code seems to be straight forward.
my JS function is
<script type="text/javascript" language="javascript">
function toggle(id) {
if(document.getElementById(id).value=='IELTS' || document.getElementById(id).value=='TOEFL')
{
if(document.getElementById('dv1').style.display=='block')
{
document.getElementById('dv1').style.display='none';
document.getElementById('dv1').style.visibility='hidden';
}
}
else
{
document.getElementById('dv1').style.display='block';
document.getElementById('dv1').style.visibility='visible';
//alert('Its displaying now');
}
if(document.getElementById(id).value=='Other')
{
if(document.getElementById('dv2').style.display=='block')
{
document.getElementById('dv2').style.display='none';
document.getElementById('dv2').style.visibility='hidden';
}
}
else
{
document.getElementById('dv2').style.display='block';
document.getElementById('dv2').style.visibility='visible';
}
if(document.getElementById(id).value=='none')
{
document.getElementById('dv1').style.display='none';
document.getElementById('dv1').style.visibility='hidden';
document.getElementById('dv2').style.display='none';
document.getElementById('dv2').style.visibility='hidden';
}
}
</script>
The problem is that the FIRST "if" statement is showing/hiding "dv2" instead of "dv1" and the SECOND "if" statement is showing/hiding "dv1" instead of "dv2" although everything is specified such a way that the FIRST "if" statement handles "dv1" and the SECOND "if" statement handles "dv2"
Am I missing something in the way of understanding of how JS works..
Here a style is predefined to make the html code hidden
<style type="text/css">
.toggleClass{
display:none;
visibility:hidden;
}
</style>
</head>
<body>
<form name="myform" >
this is the select where i called the JS function upon change
<select id="exam" name="exam" onchange="toggle('exam')">
<option selected="selected" value="none" >Please Choose</option>
<option value="IELTS">IELTS</option>
<option value="TOEFL">TOEFL</option>
<option value="Other">Other</option>
</select>
<br><br>
this is dv1
<div id="dv1" class="toggleClass">
<table width="50%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="600" bgcolor="#CCCCCC">IELTS and TOEFL</td>
</tr>
</table>
</div>
this is dv2
<div id="dv2" class="toggleClass">
<table width="50%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td height="600" bgcolor="#CCCCCC">Other</td>
</tr>
</table>
</div>
</form>
</body>
</html>
note that it works fine if I swap "dv1" and "dv2"!
Consider this block of code:-
if(document.getElementById(id).value=='Other')
{
if(document.getElementById('dv2').style.display=='block')
{
document.getElementById('dv2').style.display='none';
document.getElementById('dv2').style.visibility='hidden';
}
}
else
{
document.getElementById('dv2').style.display='block';
document.getElementById('dv2').style.visibility='visible';
}
It is evident from here that if you are selecting the 'Other' then in such a case div two will never appear. Because the condition is true where as the else condition mentioned below :-
else
{
document.getElementById('dv1').style.display='block';
document.getElementById('dv1').style.visibility='visible';
//alert('Its displaying now');
}
will display the div1 as you have validated.The script you are seeking for must be like this mentioned below:-
<script type="text/javascript" language="javascript">
function toggle(id) {
if(document.getElementById(id).value=='IELTS' || document.getElementById(id).value=='TOEFL')
{
if(document.getElementById('dv1').style.display=='block')
{
document.getElementById('dv1').style.display='block';
document.getElementById('dv1').style.visibility='visible';
}
}
else
{
document.getElementById('dv1').style.display='none';
document.getElementById('dv1').style.visibility='hidden';
//alert('Its displaying now');
}
if(document.getElementById(id).value=='Other')
{
if(document.getElementById('dv2').style.display=='block')
{
document.getElementById('dv2').style.display='block';
document.getElementById('dv2').style.visibility='visible';
}
}
else
{
document.getElementById('dv2').style.display='none';
document.getElementById('dv2').style.visibility='hidden';
}
if(document.getElementById(id).value=='none')
{
document.getElementById('Table1').style.display='none';
document.getElementById('Table1').style.visibility='hidden';
document.getElementById('Table2').style.display='none';
document.getElementById('Table2').style.visibility='hidden';
}
}
</script>
try this out and leme know if it works.
FIRST: the property of style is set only if there is a inline style of this property.
so in your div you should insert a style attribute
<div id="dv1" class="toggleClass" style="visibility:hidden; display:none">
the same for div2
After that... the logical seems not correct:
if(document.getElementById(id).value=='IELTS' || document.getElementById(id).value=='TOEFL')
this line should be visible the first div (div1) but after this:
document.getElementById('dv1').style.display='none';
document.getElementById('dv1').style.visibility='hidden';
you hide it!

Categories

Resources