I am hoping that you can help me out. I need to change an image based on the selection of 2 dropdown values. I have a number of image variations to show any option. I have a selection of code that I know concernates the file name of the image, but I can't seem to find a way to actually display that image. I have taken the code from a previous answer, but I can't get it to work for me - Changing image based on selection in 2 dropdowns.
Here is the code that I am using:
$('select.form-control').change(function() {
var file = $('#shape').val() + '-' + $('#waist').val() + '.jpg';
$('#imgToChange').prop('src', filename);
});
<select class="form-control" id="shape" name="shape">
<option value="a">Select a country</option>
<option value="b">Canada</option>
<option value="c">U.S.A.</option>
</select><br>
<select class="form-control" id="waist" name="waist">
<option value="1">Select a country</option>
<option value="2">Canada</option>
<option value="3">U.S.A.</option>
<option value="4">India</option>
</select><br>
<img id="imgToChange">
Where am I going wrong on this one?
Thanks in advance!
The variable you stored the image filename is different from the variable you passed as the value in for the image's src tag
$('select.form-control').change(function() {
var filename = $('#shape').val() + '-' + $('#waist').val() + '.jpg';
$('#imgToChange').attr('src', filename);
});
You can also try using the .attr() method in place of the .prop() method like i did
Updated See code below
HTML
<select id="select-1">
<option value="brown-head">Brown Head</option>
<option value="black-head">Black Head</option>
<option value="blue-head">Blue Head</option>
</select>
<select id="select-2">
<option value="brown-body">Brown Body</option>
<option value="black-body">Black Body</option>
<option value="blue-body">Blue Body</option>
</select>
<img id="imgElem" src="" alt="">
JS
var imageSrc;
var imgFolder = "/path/to/image/folder/"; // specify the path to the folder containing the imgs in this variable
$("select").change(function(){
imageSrc = imgFolder + $("#select-1").val() + "-" + $("#select-2").val() + ".jpg";
$("#imgElem").attr("src", imageSrc);
$("p").text(imageSrc);
});
UPDATED ONCE AGAIN
This update creates the img tag each time an option is selected, replacing the previous img tag. This is to prevent the img src(undefined) error on page load.
To archive this, i added a div in the html to hold the img element, and simply change the divs html content.
HTML UPDATED
<select id="select-1">
<option value="brown-head">Brown Head</option>
<option value="black-head">Black Head</option>
<option value="blue-head">Blue Head</option>
</select>
<select id="select-2">
<option value="brown-body">Brown Body</option>
<option value="black-body">Black Body</option>
<option value="blue-body">Blue Body</option>
</select>
<p></p> <!-- just for debugging -->
<div class="img-wrap"></div> <!-- a div to hold the image -->
JS UPDATED
// specify the path to the folder containing the imgs in this variable
var imgFolder = "/path/to/image/folder/";
$("select").change(function(){
var src; // variable to hold the src
src = imgFolder + $("#select-1").val() + "-" + $("#select-2").val() + ".jpg";
// append src to a p element just for debugging sake(i.e to see the change in the src)
$("p").text(src);
// create an img element with the src each time and append to the image wrap div
$(".img-wrap").html(`<img src="${src}">`);
});
UPDATED ONCE AGAIN
To make it show the image with the default selected options both on page load and on option select, i tweaked the code again
NEW JS CODE
function getImageSrc(){
// specify the path to the folder containing the imgs in this variable
var imgFolder = "/path/to/image/folder/";
// loop through each select element
$("select").each(function(){
// fire function to get src
getSrc();
// fire function to get src on change
$(this).change(function(){
getSrc();
})
});
function getSrc(){
var src; // variable to hold the src
src = imgFolder + $("#select-1").val() + "-" + $("#select-2").val() + ".jpg";
$("#imgElem").attr("src", src);
// append src to a p element just for debugging sake(i.e to see the change in the src)
$("p").text(src);
// create a an img element with the src each time and append to the image wrap div
$(".img-wrap").html(`<img src="${src}">`);
}
}
// fire function on page-load
$(document).ready(function(){
getImageSrc();
})
Your variable name should be filename not just file because that's what you're using in your code. Here's what you need.
$('select.form-control').change(function() {
var filename = $('#shape').val() + '-' + $('#waist').val() + '.jpg';
$('#imgToChange').prop('src', filename);
});
UPDATE
If you're pulling your images from a folder img then you need to do this:
$('#imgToChange').prop('src', 'img/'+filename);
Related
I have created a button with allow me to create image on canvas for drag and drop canvas.
<button type="button" class="btn-one" onclick="addimage3();">Board</button>
function addimage3(){
var img2 = document.createElement("img");
img2.src = "object3.png";
img2.height = 20;
img2.width = 400;
var class_name = "foo";
img2.setAttribute("class", class_name);
document.getElementById("pc").appendChild(img2);
$(img2).draggable();
}
I know that I need to create many button in order to let user able to create many image in canvas for drag and drop, Is that possible to make them into dropdownlist and make it will create the image based on what user choose in the list?
Create a <select> element with as many options as you have images. Every option value attribute will hold the src of the image. Now everytime listen for the change event on the <select> element to get the URL of the currently selected image.
Then when you got the URL, create a new image and set the src property to the selected URL. From here append the image to the desired element and your image has been chosen.
Example below:
// Select the select field and the image container.
const select = document.getElementById('select-image');
const imgContainer = document.getElementById('image-container');
select.addEventListener('change', function(event) {
const value = event.target.value; // Get the value of the selected option.
const image = new Image(); // Create new image.
image.src = value; // Set value to image.
imgContainer.innerHTML = ''; // Empty container.
imgContainer.appendChild(image); // Add image to container.
});
<select id="select-image" name="image">
<option hidden value="">Choose image</option>
<option value="https://www.placecage.com/640/360">Image 1</option>
<option value="https://placebeard.it/640x360">Image 2</option>
<option value="https://baconmockup.com/640/360">Image 3</option>
</select>
<div id="image-container">
</div>
You want to grab the value of the drop-down so you can figure out which image type the user selected. Using a switch statement, you can set the image attributes based on which type they picked.
function addImage() {
var type = document.querySelector("#imgtype").value;
var imgElem = document.createElement("img");
switch (type) {
case "img1":
imgElem.src= "https://images.pexels.com/photos/736230/pexels-photo-736230.jpeg";
break;
case "img2":
imgElem.src= "https://www.carmax.com/cars/images/type-icons/sedans.svg";
break;
}
document.getElementById("pc").appendChild(imgElem);
}
// Make it onChange of the select
document.querySelector('#imgtype').addEventListener('change', (e) => { addImage(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="imgtype">
<option value="img1" selected>Flower</option>
<option value="img2">Car</option>
</select>
<button type="button" onClick="addImage()">Add Image</button>
<div id="pc"></div>
Everything works as it should. Just having trouble getting both select box values carried with the hash event listener. For now I only have #search_region in there and it carries over as it should. I need #search_region and #search_categories in there.
Output displays www.example.com#135&140. The link www.example.com#135&140 as is should be able to be copied to a new tab and keep both values chosen selected basically.
Any ideas on how I should go about this one?
<select name="search_region" id="search_region" class="search_region">
<option value="0">All Regions</option>
<option class="level-0" value="135">Camps Bay</option>
<option class="level-0" value="136">Cape Town</option>
<option class="level-0" value="137">Durbanville</option>
<option class="level-0" value="139">Hermanus</option>
<option class="level-0" value="138">Langebaan</option>
</select>
<select name="search_categories" id="search_categories" class="search_categories">
<option value="">Select Category</option>
<option class="level-0" value="140">140</option>
<option class="level-0" value="141">141</option>
</select>
<script type="text/javascript">
// ADDS selected values to URL
$(function(){
var url = '';
$('#search_region').change(function () {
url = $(this).val();
window.location.hash = url;
console.log(window.location.hash);
});
$('#search_categories').change(function () {
if(url !==''){
window.location.hash = url+"&"+$(this).val();
}
console.log(window.location.hash);
});
});
// carries selected value over to new browser or new tab. *where the help is needed*
window.addEventListener('hashchange', fn, false);
window.onload = fn; // fire on pageload
function fn() {
$('#search_region').val(window.location.hash.replace('#', ''));
console.log("hash = " + window.location.hash);
}
</script>
This is an add on from a previously asked question. Link below
Displaying two seperate select box values in a URL
Its just a matter of checking if there are two hashes and splitting it and setting the values to the select.
function fn() {
var values = window.location.hash.replace('#', '').split('&')
$('#search_region').val(values[0]);
if (values.length > 1){
$('#search_categories').val(values(1));
}
console.log("hash = " + window.location.hash);
}
Your code expects that the second element is only ever changed after the first one is. You should consider using the same event handler on both elements and constructing the right URL no matter which element receives the event. Remove the half-global variable url.
Secondly, in fn, you have to .split() the hash to separate the two values and assign them to their respective elements.
I'm trying to bulid an image path from two select fields. I have to use the "id"s because "value"s are used already. Unfortunatedly only the second select works. Does anyone have a hint? As you might see I'm not a coder. Could anyone be so kind and help to make the code more elegant/slim?
I use onchange to update the "result1" and "result2" allways when the user alters his selection.
Thanks in advance, Georg
Here is my code:
<script>
function showOptions1(s) {
document.getElementById("result1").innerHTML = "<img src='img/preview/" + s[s.selectedIndex].id;
}
</script>
<script>
function showOptions2(s) {
document.getElementById("result2").innerHTML = s[s.selectedIndex].id + ".jpg'>";
}
</script>
<select onchange="showOptions1(this)" id="my_select1">
<option value="werta" id="1">Text Item 1a</option>
<option value="wertb" id="2">Text Item 1b</option>
</select>
<select onchange="showOptions2(this)" id="my_select2">
<option value="wertc" id="3">Text Item 1c</option>
<option value="wertd" id="4">Text Item 1d</option>
</select>
<span id="result1"></span><span id="result2"></span>
I wouldn't use the onchange event because you want the user to select two things before building the path. So, put another button on the screen called "save image" or something like that. The onclick of this button gets the "value" of each select input and concats them together. You can easily get a handle to the select inputs using jquery by name
var select1 = $("#my_select1");
Now your problem is that you don't want the value. That would be easy. Instead you want the select option and then you want to get the id. You can do that as follows
var my1id = $("#my_select1 option:selected" ).id;
Thanks a lot for your support. Cheers Georg
Finaly I use this code (and stick to onchange because I dont want another button because there are allready three of them):
<script>
var selection01, selection02;
showOptions1 = function(s) {
selection01 = "<img src='img/preview/" + s[ s.selectedIndex ].id;
getResult();
};
showOptions2 = function(s) {
selection02 = s[ s.selectedIndex ].id + ".jpg' width='200px;'>";
getResult();
};
function getResult() {
var total = selection01 + selection02;
console.log( total );
document.getElementById("Image").innerHTML = total;
};
</script>
<select id="select1" onchange="showOptions1(this)">
<option value="" id="01" selected>...</option>
<option value="werta" id="10">Text Item 1a</option>
<option value="wertb" id="20">Text Item 1b</option>
</select>
<select id="select2" onchange="showOptions2(this)">
<option value="" id="02" selected>...</option>
<option value="wertc" id="30">Text Item 1c</option>
<option value="wertd" id="40">Text Item 1d</option>
</select>
<hr><span id="Image"></span>
I am new to JavaScript. This request seems simple enough but cant seem to get it to work.
I want to select from a drop down menu and return the value in the HTML. As I have it now, it returns the value in a text box, but I want it to write it without using a text box, just simply return it in the <p></p>.
http://jsfiddle.net/Ppk5k/
Here you go:
function favBrowser()
{
var mylist=document.getElementById("myList");
document.getElementById("favorite").innerHTML = mylist.options[mylist.selectedIndex].text+".";
}
You have to use innerHTML to set the HTML of #favorite to the browser selected.
Working example: http://jsfiddle.net/Ppk5k/6/
Update
To get the value and text:
function favBrowser() {
var mylist = document.getElementById("myList");
document.getElementById("favorite").innerHTML = mylist.options[mylist.selectedIndex].text;
document.getElementById("favorite").innerHTML += " and the value of that option is " + mylist.options[mylist.selectedIndex].value + ".";
}
If you selected Google Chrome it will output:
Your favorite browser is Google Chrome and the value of that option
is G.
And for the example: http://jsfiddle.net/Ppk5k/13/
Get the <p> by its ID (or by some other method), then set its innerHTML.
You can not use document.write after the page has loaded, it will replace the page content. You need to use innerHTML or appendChild.
Don't forget to include a value="" attribute within the option tags, something like:
<script type="text/javascript">
function favBrowser() {
var mylist=document.getElementById('myList');
document.getElementById('favorite').value=mylist.value;
}
</script>
<form>
Select your favorite browser:
<select id="myList" onchange="favBrowser()">
<option></option>
<option value="Google Chrome">Google Chrome</option>
<option value="Firefox">Firefox</option>
<option value="Internet Explorer">Internet Explorer</option>
<option value="Safari">Safari</option>
<option value="Opera">Opera</option>
</select>
<p>Your favorite browser is: <input type="text" id="favorite" size="20" value=""></p>
</form>
The simplest way of doing this is by giving an id attribute to a HTML element and change it's innerHTML or clear, create and append a text node to the element:
innerHTML:
var element = document.getElementById('someElement');
element.innerHTML = "someValue";
appendChild:
var element = document.getElementById('someElement');
var oldChild = element.firstChild;
element.removeChild(oldChild);
var newChild = document.createTextNode("someValue");
element.appendChild(newChild);
Use innerHTML . Demo
HTML:
<form>
Select your favorite browser:
<select id="myList" onchange="favBrowser()">
<option></option>
<option>Google Chrome</option>
<option>Firefox</option>
<option>Internet Explorer</option>
<option>Safari</option>
<option>Opera</option>
</select>
<p id="favorite">Your favorite browser is:
</p>
</form>
Javascript :
function favBrowser() {
var mylist = document.getElementById("myList");
document.getElementById("favorite").innerHTML= "Your favorite browser is: " + mylist.options[mylist.selectedIndex].text;
}
I've got a multiple select that I want to use to pick which elements show up in an HTML template window. So I have several options that I want to iterate over, and based on whether it's been selected, make the preview elements visible or hidden.
I'm going for something like this:
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
$(??????).css($css);
});
As you can see, I'm just iterating over each option (I'm pretty sure that syntax works) in my area_select menu, but I don't know how to make the css get applied to the corresponding piece.... how can I reference my preview elements via my options?
An easier way to go is to call .val() on the multiple select. That returns an array of selected values that you can iterate over.
var array = $('#area_select').val()
$.each(array, function(i,val) {
// your code
});
So as far as showing the elements is concerned, it would depend on what type of data is stored in the value of the select options.
For an ID, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('#' + value).css('visibility','visible');
});
Or if they are class names, do this:
$(selectorForCollection).css('visibility','hidden');
var array = $('#area_select').val();
$.each(array, function(i,value) {
$('.' + value).css('visibility','visible');
});
Give each of the options a name corresponding to the ID of the correct piece.
e.g.
<select>
<option value="whatever">Whatever</option>
<option value="whatever2">Whatever 2</option>
</select>
Then each of you elements will be contained in a a div like this:
<div id="whatever-preview">
<!-- Whatever -->
</div>
Then your Javascript
$('#area_select option').each(function(i){
if($(this).is(':selected')){var $css = {'visibility' : 'visible'}}
else{var $css = {'visibility' : 'hidden'}}
var div_name = "#" + $(this).attr('value') + "-preview";
$(div_name).css($css);
});
Give each option an id referencing the id of the corresponding element in the preview window.
for instance:
<option id="option-1">This turns on the first option element in the preview window</option>
<option id="option-2">This turns on the first option element in the preview window</option>
and give the preview window elements similar-ending ids:
<div id='window-1'>corresponding window preview element</div>
Then in the javascript:
$("#window-" + $(this).attr('id').split('-')[1]).css($css);
First, give the elements to hide or show the same class but id's matching the options values:
<div class="something" id="val_1">content1</div>
<div class="something" id="val_2">content2</div>
<div class="something" id="val_3">content3</div>
<div class="something" id="val_4">content4</div>
<select id="area_select">
<option value="val_1">val 1</option>
<option value="val_2">val 1</option>
<option value="val_3">val 1</option>
<option value="val_4">val 1</option>
</select>
then, when the select choosen option changes hide all the stuff and show the selected
$('#area_select').change( function(){
var val = $(this).val();
$('.something').hide();
$('#'+val).show();
return false;
});