I am a beginer in javascript and I want to change an image based upon options in my dropdown (select)
I find this tutorial, but I am having some problems.
In this tutorial they replace iljbild by the name of the picture files you are going to use
if you want to use the code as it is the names of the picture files have got to be of the same type as in the example, ie the only thing telling the files apart should be a number, e g pict0.gif, pict2.gif etc.
if you are using jpg images you will have to replace gif by jpg.
set the WIDTH and the HEIGHT of the images
if you change the (length of the) words in the selection list you will also have to change the number after charAt (here it is 8)
it's what i did by replacing iljbid by:
http://upload.wikimedia.org/wikipedia/commons/1/1e/Stonehenge.jpg
but it doesn't work.
The tutorial expect you to have a list of images with a named convention. That is {prefix}{number}.{extension}. For exmaple:
image0.jpg
image1.jpg
image2.jpg
and so on...
The prefix on all images must be the same, and the extension on all images must be the same. This is a simple tutorial to get the effect done.
It can be expanded once you have more JavaScript knowledge.
Also, that tutorial is really bad (don't mean to disrespect, but it is really lacking. Copying and pasting the example itself into JSFiddle throws errors everywhere).
The tutorial is from 1998. That is 16 years old. I strongly suggest you to look for newer tutorials. (2010+)
Here is an example replica of the tutorial that works:
http://jsfiddle.net/VmWD9/
HTML
<img src="http://www.flowsim.se/picts/selec01.jpg" width="70" height="70" name="myImage" />
<form method="" action="" name="myForm">
<select size="8" name="switch" onchange="switchImage();">
<option value="1">Image 1</option>
<option value="2">Image 2</option>
<option value="3">Image 3</option>
<option value="4">Image 4</option>
<option value="5">Image 5</option>
<option value="6">Image 6</option>
<option value="7">Image 7</option>
</select>
</form>
JavaScript
// This is the code to preload the images
var imageList = Array();
for (var i = 1; i <= 7; i++) {
imageList[i] = new Image(70, 70);
imageList[i].src = "http://www.flowsim.se/picts/selec0" + i + ".jpg";
}
function switchImage() {
var selectedImage = document.myForm.switch.options[document.myForm.switch.selectedIndex].value;
document.myImage.src = imageList[selectedImage].src;
}
Though nowadays people use JavaScript libraries such as jQuery or MooTools to acomplish things like that. I do find that it is better to first explore things in pure JS before heading into these libraries, though it is not a necessity. Most of these libraries are easy to grasp, but when you want to make something big you might need to have prior JS knowledge.
I recommend that you go through the Codecademy JavaScript tutorial.
Here try this FIDDLE
<img src="http://lorempixel.com/400/200/sports/1" />
<select id="picDD">
<option value="1" selected>Picute 1</option>
<option value="2">Picute 2</option>
<option value="3">Picute 3</option>
<option value="4">Picute 4</option>
<option value="5">Picute 5</option>
</select>
var pictureList = [
"http://lorempixel.com/400/200/sports/1",
"http://lorempixel.com/400/200/sports/2",
"http://lorempixel.com/400/200/sports/3",
"http://lorempixel.com/400/200/sports/4",
"http://lorempixel.com/400/200/sports/5", ];
$('#picDD').change(function () {
var val = parseInt($('#picDD').val());
$('img').attr("src",pictureList[val]);
});
There are multiple ways to achieve the desired.
This one is by getting the Number value after the select change event and get that src out of the imagesArray Array key.
<select id="changeImage">
<option value="0">image 0</option>
<option value="1">image 1</option>
<option value="2">image 2</option>
</select>
<img id="image" src='//placehold.it/50x50/cf5'>
var imagesArray = [
"//placehold.it/50x50/cf5", // represents val 0,
"//placehold.it/50x50/f1f", // 1,
"//placehold.it/50x50/444" // 2 ...
];
$('#changeImage').change(function(){
$('#image')[0].src = imagesArray[this.value];
});
The other one is to have image names inside the option text:
<select id="changeImage">
<option>image.jpg</option>
<option>something.png</option>
<option>nature.jpg</option>
</select>
<img id="image" src='image.jpg'>
$('#changeImage').change(function(){
$('#image')[0].src = this.value;
});
Related
I've had a hard time finding a similar question for this, and its probably simple but just slipping my mind.
I've got a drop down menu, you make your selection and submit it, it jumps to 2ndpage.html?location=locationName
I'm trying to create a variable with a value of the "locationName" to use in a link that would use that value as a string like "www.locationName.com",
i've tried using something like
var locationName = getElementById("location").value;
and other similar ways but the variable seems to keep coming up undefined. And this seems to be the only thing stopping me from finishing my project, lol.
Thanks in advance.
You would find the value and text by accessing this.selectedIndex of the selection list. Use http:// for absolute link to a page.
<select id="locations">
<option value="http://www.google.com">Location 1</option>
<option value="http://www.loogle.com" selected="selected">Location 2</option>
<option value="http://www.foogle.com">Location 3</option>
</select>
var e = document.getElementById("locations");
e.addEventListener('change', function (){
var locationValue = this.options[this.selectedIndex].value;//www.loogle.com
var locationText = this.options[this.selectedIndex].text;//Location 2
window.location = locationValue;
});
Try this:
<p>Location: </p>
<select id="location">
<option value="location1">location 1</option>
<option value="location2">location 2</option>
<option value="location3">location 3</option>
</select>
<script>
var locationName = document.getElementById("location").value;
</script>
Or try this:
<p>Location: </p>
<select name="location">
<option value="location1">location 1</option>
<option value="location2">location 2</option>
<option value="location3">location 3</option>
</select>
<script>
var locationName = document.getElementsByName("location")[0].value;
</script>
How can I select an option with javascript (/console in google chrome)?
This is a part of the html code:
<nobr>
Element<br>
<span class="absatz">
<br>
</span>
<select name="element" class="selectbox" style="width:114" size="12" onchange="doDisplayTimetable(NavBar, topDir);">
<option value="0">- All -</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">X</option>
<option value="4">C</option>
<option value="5">D</option>
<option value="6">E</option>
<option value="7">F</option>
<option value="8">G</option>
<option value="9">H</option>
<option value="10">I</option>
<option value="11">J</option>
<option value="12">K</option>
<option value="13">L</option>
<option value="14">M</option>
<option value="15">N</option>
<option value="16">O</option>
<option value="17">P</option>
<option value="18">Q</option>
<option value="19">R</option>
</select>
</nobr>
Or http://pastebin.com/JSaKg4HB
I already tried this:
document.getElementsByName("element")[0].value = 1;
But it gives me this error:
Uncaught TypeError: Cannot set property 'value' of undefined
at :2:48
at Object.InjectedScript._evaluateOn (:875:140)
at Object.InjectedScript._evaluateAndWrap (:808:34)
at Object.InjectedScript.evaluate (:664:21)
EDIT:
I I tried it but it don't works on for the full website. Maybe because there is another html tag inside the first html tag(if I download the website, there is another html file called welcome.html where the selectbox is.) I thinks it's in an iFrame, because chrome gives me the Option "show Frame".
EDIT 2:
I can access the frame where the selectbox is but I still won't find the selectbox. Here is the code of the frame(not the full code): pastebin.com/iVUeDbYV
Try this:
document.querySelectorAll('[name="element"]')[0].value;
Although it is very weird that getElementsByName is not working for you. Are you sure the element is in the same document, and not in an iFrame?
The simple answer:
document.getElementById("select_element").selectedIndex = "option index";
Where option index is the index of the option in the dropdown that you'd like to activate.
You can get the index of an option by using this:
var selected = document.querySelector( '#'+div+' > option[value="'+val+'"]' );
Where div is the ID of the <select> tag.
how this helps!
This will do what you want.
document.querySelector('[name="element"]').value = 4 // The value you want to select
and this will retrieve the value
var value = document.querySelector('[name="element"]').value; // 4
this explains what's going on
var option = document.querySelector('[name="element"]');//option element
option.value; // 4
option.selectedIndex; // 4
option.selectedOptions; // [<option value="4">C</option>]
option.selectedOptions[0].innerText; // C
option.selectedOptions[0].value; // 4
Remember that selectedOptions is an array because more than one option may be selected, in those cases, you will have to loop through the array to get each value. As per Hanlet EscaƱo's comment, make sure your code is set to execute after the DOM has loaded.
window.onload = function() {
document.querySelector('[name="element"]').value = 0; // sets a default value
}
Background
Hey everyone, first off thanks for your help. This issue has been bothering my for quite a while now and I just can't seem to figure it out.
Some background, I am creating a page that links to a db that has movie posters stored. This page will allow me to retrieve specific movie posters based on two factors: the movieid that is passed and the poster size.
Specifics
I am trying to change the value of data-pp-pubid to the input from Publisher ID (in this case King Kong). I am also wanting to do the same thing for data-pp-placementtype to fill from my dropdown box.
This works if I use static information in the html. However, I am wanting to create dynamic variables to save me the trouble of constantly editing the html file. This is what I've got so far.
<div>
<form>
<select id="generic_size" name="Poster Size">
<option value="120x90">120x90</option>
<option value="120x240">120x240</option>
<option value="120x600">120x600</option>
<option value="150x100">150x100</option>
<option value="170x100">170x100</option>
<option value="190x100">190x100</option>
<option value="234x400">234x400</option>
<option value="234x60">234x60</option>
<option value="250x250">250x250</option>
<option value="280x280">280x280</option>
<option value="300x50">300x50</option>
<option value="300x250">300x250</option>
<option value="468x60">468x60</option>
<option value="540x200">540x200</option>
<option value="720x90">720x90</option>
<option value="800x60">800x60</option>
</select>
Publisher ID: <input type="text" value="King Kong" id="movieId">
<input type="submit" value="Get poster"
onclick="javascript:getMovInfo(); setSize(); getPoster();";>
</form>
</div>
<script type="text/javascript" data-pp-pubid="Mad Max" data-pp-placementtype="120x240"> (function getPoster(d, t) {
"use strict";
var s = d.getElementsByTagName(t)[0], n = d.createElement(t);
n.src = "//movietime.adtag.now.com/merchant.js";
s.parentNode.insertBefore(n, s);
}(document, "script"));
</script>
<script type="text/javascript">
function getMovInfo() {
var movRetrieve= document.getElementById("movieId").value;
var movInfo = document.getElementsByTagName("script")[2];
var movSet = movInfo.setAttribute("data-pp-pubid", movRetrieve);
}
function setSize (){
var sizeDropDown= document.getElementById("generic_size");
var sizeSelected= sizeDropDown.options[sizeDropDown.selectedIndex].value;
var sizeInScript = document.getElementsByTagName("script")[2];
var newSize = sizeInScript.setAttribute("data-pp-placementtype", sizeSelected);
}
</script>
Thanks again, this is my first post!
Ok, then you should convert the html data you have to some data in the code. An array ["300x50", ...] will do the job. Then you have to populate your select with the data.
This question already has answers here:
How to change the background image through the tag "selected"
(2 answers)
Closed 8 years ago.
So I know this question was, very similarly asked before, however I did not find the answer in that feed as the answer did not work with my other JavaScript.
Here's my problem. I am trying to add in a menu to change the background on a form I am working on. I cannot figure out how to make the background change to an image when an <option> is selected from the <select> field. I would like to accomplish this with just JavaScript, but I will use JQuery if need be.
<label for="pictype">Select a New Background</label>
<select id="pictype" name="pictype" onclick="picchange()">
<option value="p1">pic1</option>
<option value="p2">pic2</option>
<option value="p3">pic3</option>
<option value="p4">pic4</option>
<option value="p5">pic5</option>
<option value="p6">pic6</option>
</select>
You can use a .change event, and smart file naming to achieve this result. Using jQuery is by far the easiest solution.
If you name your images the same as the option values, you can then reference images based off of the current option selected. So for the first option you could name the picture, p1.jpg.
<label for="pictype">Select a New Background</label>
<select id="pictype" name="pictype">
<option value="p1">pic1</option>
<option value="p2">pic2</option>
<option value="p3">pic3</option>
<option value="p4">pic4</option>
<option value="p5">pic5</option>
<option value="p6">pic6</option>
</select>
jQuery
$("#pictype").change(function(){
var imageFileName = $(this).val();
$("body").css("background-image", "url(../Images/"+imageFileName+".jpg)");
});
So if you selected option #1, it would set the background image url to url("../Images/p1.jpg");
Here is the jsfiddle: http://jsfiddle.net/mtruty/3L2uP/
Hope this helps!
here is the code:
$( "#pictype" ).change(function(){
if( this.value == "p1" ) //here goes code to change picture
if( this.value == "p2" ) //here goes code to change picture
......
});
Demo: http://jsfiddle.net/Qwnm6/
<label for="pictype">Select a New Background</label>
<select id="pictype" name="pictype" onchange="document.body.style.background = this.value">
<option value="red">pic1</option>
<option value="green">pic2</option>
<option value="blue">pic3</option>
<option value="yellow">pic4</option>
<option value="lime">pic5</option>
<option value="gray">pic6</option>
</select>
Try this. NOTE: I deleted your onclick function calling pictype
HTML
<select id="pictype" name="pictype">
<option value="p1">pic1</option>
<option value="p2">pic2</option>
<option value="p3">pic3</option>
<option value="p4">pic4</option>
<option value="p5">pic5</option>
<option value="p6">pic6</option>
</select>
JavaScript
var selectEl = document.getElementById("pictype");
selectEl.onclick = function () {
if (this.value == "p1") {
document.body.style.backgroundColor = "Black";
}
else {
document.body.style.backgroundColor = "White";
}
}
I want to use this function to work on all my drop down lists. Problem: the first drop down works okay, but hen I try select any option in the 2nd drop down selections. It places the value from the first group in the span of the second group. I want the span to have the value from its own group. I would like to use this on multiple groups.
The code below does not work properly. the phone number display okay but when i try to select the parts, the value of the phone number is displayed, no matter what the selection is.
I want the phone number when i select phones, and parts when i select parts.
Thank you
<script>function displayResult(xspan,xselect)
{
var x=document.getElementById(xselect).selectedIndex;
alert(x);
var newTxt = document.getElementsByTagName("option")[x].value;
document.getElementById(xspan).innerHTML = newTxt;
//alert(document.getElementsByTagName("option").length);
}
</script>
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
<option value="">Phone Numbers</option>
<optgroup label="Shipping">
<option value=" - 800-463-3339">FedEx</option>
<option value=""></option>
</optgroup>
</select>
<span id="ShowPhone"></span>
<select id="myParts" onchange="displayResult('ShowParts','myParts')">
<option value="">Qik Parts list</option>
<optgroup label="BATT">
<option value="1">1</option>
<option value="2">1</option>
<option value="2">1</option>
<option value="2"><1/option>
</optgroup>
</select>
<span id="ShowParts"></span>
Mostly comments:
When you do:
var newTxt = document.getElementsByTagName("option")[x].value;
then document.getElementsByTagName("option") returns all the options in the document, you probably only want the ones for the select in question. But the options for a select are available as a collection, so you can do:
selectElement.options[x].value;
But that is unnecessary unless you are dealing with very old browsers or IE where there are no value attributes. Just use selectElement.value.
Where you have:
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
you can instead do:
<select id="myPhones" onchange="displayResult('ShowPhone', this.value)">
so that you pass the current value of the select directly to the function. Then the function can be:
function displayResult(id, value) {
document.getElementById(id).innerHTML = value;
}
This should work, though I haven't tested it.
function displayResult(spanId, selectId) {
document.getElementById(spanId).innerHTML = document.getElementById(selectId).value;
}