I'm trying to display an image when the user selects an option in the dropdown list, the image will then be displayed after button click. This is my idea on how to do this but I'm not quite sure if its correct so I'm asking others for opinion's.
Here's my code and a fiddle: http://jsfiddle.net/Bc6Et/1546/
html
<select name="" id="dropdownlist" size="">
<option value="img1">Image</option>
<option value="img2">Image</option>
<option value="img3">Image</option>
<option value="">so on and so forth</option>
</select>
<input type="button" value="Show Image" onclick="showimg()" class="button">
javascript/jquery
function showimg() {
var q = document.getElementById("dropdownlist");
var selected = q.options[q.selectedIndex].value;
var src = "/var/www/VAA/img";
if (selected === img1) {
show_image("/var/www/VAA/img/img1.png");
}
elseif(selected === img2) {
show_image("/var/www/VAA/img2.png");
}
}
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
document.body.appendChild(img);
}
Or I could use case/break switch statements instead of if/else. Appreciate all the help tnx oh and 1 more thing the images are on my desktop thought you might need that info
Instead of having a if statement for each images maybe you can try something like this?
<option value="name_of_your_image">Image</option>
And then call your function:
var src = "/var/www/VAA/"+selected+".png";
show_image(src);
http://jsfiddle.net/Bc6Et/1558/
I think this is a better option if you have a lot of images.
You were looking into the wrong variable. q is always the dropdown element and has nothing to do directly with which option is selected and/or their respective value.
img1 and img2 must be declared as a string since they are no variables.
function showimg() {
var q = document.getElementById("dropdownlist");
var selected = q.options[q.selectedIndex].value;
console.log(selected);
var src = "/var/www/VAA/img";
if (selected === "img1") {
show_image("/var/www/VAA/img");
}
else if (selected === "img2") {
show_image("/var/www/VAA/img");
}
}
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
console.log(src);
document.body.appendChild(img);
}
working fiddle
It would work but you will need one if condition for every image you have.
Why don't you put all images on the same folder, and build the imagepath concatenating strings?
src = "/var/www/VAA/";
var selected = q.options[q.selectedIndex].value;
show_image(src+selected);
There are several errors
function showimg() {
var q = document.getElementById("dropdownlist");
var selected = q.options[q.selectedIndex].value;
var src = "/var/www/VAA/img";
if (selected === "img1") {
//_____^__________
show_image("/var/www/VAA/img");
}
else if(selected === "img2") {
//__^__________^______
show_image("/var/www/VAA/img");
}
}
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
document.body.appendChild(img);
}
FIDDLE
I have a suggestion so that you don't have to have a lot of conditional statements for identifying which image to show: what if you place the image src (or maybe just the filename if you want) as the value of the select box's options, like so:
<select name="image" id="dropdownlist">
<option value="/source/for/image1.png">Image 1</option>
<option value="/source/for/image2.png">Image 2</option>
<option value="/source/for/image3.png">Image 3</option>
</select>
<input type="button" value="Show Image" class="button" />
And then you can modify your jQuery code like so:
$('.button').on('click', function() {
var image = $('<img src="' + $('#dropdownlist').val() + '" />');
$('body').append(image);
});
Related
I've been struggling for the last 2 days to create an option when a user clicks the button "submit" after they selected a value from a "select>" element, the website to show an image.
<label for="cars" id="carInput" name="carInput">
<select id="modelsList">
<option value="mba">Mercedes-Benz A Class</option>
<option value="mbc">Mercedes-Benz C Class</option>
<option value="mbe">Mercedes-Benz E Class</option>
<option value="mbs">Mercedes-Benz S Class</option>
<option value="mbeq">Mercedes-Benz EQE Class</option>
<option value="mbeqs">Mercedes-Benz EQS Class</option>
</select>
<button id="btn">submit</button>
I tried something like this in Javascript, but everytime I click the submit button it adds a new image and I really dont want that, I want the image to change everytime a value is chosen.
document.querySelector('#btn').addEventListener('click', submit);
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let container = document.querySelector('.container');
const aImg = document.createElement("img");
const cImg = document.createElement("img");
const eImg = document.createElement("img");
const sImg = document.createElement("img");
const eqImg = document.createElement("img");
const eqeImg = document.createElement("img");
aImg.src = "https://ag-spots-2021.o.auroraobjects.eu/2021/07/26/mercedes-amg-cla-45-c117-c479326072021173956_1.jpg?1627314027"
cImg.src = "https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjM1bXk3dTVtcTd1OC1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.dxCeoriV-0ygVtEXaXgFFvuomnzNmndAS1G5qVVYqaM/image;s=1080x720"
eImg.src = "https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjdjYzZ2cm84NjNrcS1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.5PJ743A4FPdZuZkRpYhJh9g96i1AASth2X4nBJXS0oU/image;s=644x461"
sImg.src = "https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6InM1NnM5ZndkYTR4dC1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.1N_EW-jPwI1Q33sSuwaIdYxTexUdYAHcWgEFYCPqkrU/image;s=1080x720"
eqImg.src = "https://www.cars-data.com/pictures/mercedes/mercedes-benz-g-class_4266_24.jpg"
eqeImg.src = "https://mercedesblog.com/wp-content/uploads/2019/06/mercedes-eqe.jpg"
if (value === 'mba') {
container.appendChild(aImg);
} else if (value === 'mbc') {
container.appendChild(cImg)
} else if (value === 'mbe') {
container.appendChild(eImg);
} else if (value === 'mbs') {
container.appendChild(sImg);
} else if (value === 'mbeq') {
container.appendChild(eqImg);
} else {
container.appendChild(eqeImg);
}
}
And 1 more bonus question: how to actually inject a whole div container with 3 flex childrens(a img, paragraph and a small div) when the submit button is clicked?
Try removing all child nodes from the container first:
function removeAllChildNodes(parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
}
const container = document.querySelector('#container');
removeAllChildNodes(container);
You can remove everything from the container before appending :
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let container = document.querySelector('.container');
container.innerHTML = '';
[...]
or you can change src of image without appending new image
document.querySelector('#btn').addEventListener('click', submit);
const images = {
mba:'https://ag-spots-2021.o.auroraobjects.eu/2021/07/26/mercedes-amg-cla-45-c117-c479326072021173956_1.jpg?1627314027',
mbc:'https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjM1bXk3dTVtcTd1OC1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.dxCeoriV-0ygVtEXaXgFFvuomnzNmndAS1G5qVVYqaM/image;s=1080x720',
mbe:'https://ireland.apollo.olxcdn.com/v1/files/eyJmbiI6IjdjYzZ2cm84NjNrcS1BVVRPVklUUk8iLCJ3IjpbeyJmbiI6InE3bXo1M2JpZnB6ay1BVVRPVklUUk8iLCJzIjoiMTYiLCJwIjoiMTAsLTEwIiwiYSI6IjAifV19.5PJ743A4FPdZuZkRpYhJh9g96i1AASth2X4nBJXS0oU/image;s=644x461',
mbs:'https://www.cars-data.com/pictures/mercedes/mercedes-benz-g-class_4266_24.jpg',
mbeq:'https://www.cars-data.com/pictures/mercedes/mercedes-benz-g-class_4266_24.jpg',
default:'https://mercedesblog.com/wp-content/uploads/2019/06/mercedes-eqe.jpg'
}
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let container = document.querySelector('.container');
const img = document.querySelector('#img');
if(images.hasOwnProperty(value)) {
img.setAttribute('src', images[value]);
} else {
img.setAttribute('src', images.default);
}
}
<label for="cars" id="carInput" name="carInput"/>
<select id="modelsList">
<option value="mba">Mercedes-Benz A Class</option>
<option value="mbc">Mercedes-Benz C Class</option>
<option value="mbe">Mercedes-Benz E Class</option>
<option value="mbs">Mercedes-Benz S Class</option>
<option value="mbeq">Mercedes-Benz EQE Class</option>
<option value="mbeqs">Mercedes-Benz EQS Class</option>
</select>
<button id="btn">submit</button>
<div class="container">
<img id="img"/>
</div>
I suggest changing about the way you think of the relationship between the HTML and the JS. The former is the presentation layer, the latter is the logic layer. It makes little sense to include presentation information in your business logic, if you can help it. Right now, if you want to make changes to the way this select works (for example, adding new images or changing existing images) you have to change the JS as well as the HTML.
You could change your code to the following:
document.querySelector('#btn').addEventListener('click', submit);
function submit() {
let select = document.querySelector('#modelsList');
let value = select.options[select.selectedIndex].value;
let containerImg = document.querySelector('#container-img');
containerImg.hidden = false;
containerImg.src = value;
}
This allows you to add any number of future image options without having to touch the code. This makes some assumptions about the HTML. You would have to change it like this:
<label for="cars" id="carInput" name="carInput">
<select id="modelsList">
<option value="image1.png">Mercedes-Benz A Class</option>
<option value="image2.png">Mercedes-Benz C Class</option>
</select>
<button id="btn">submit</button>
</label>
<div class="container">
<img hidden src="" id="container-img" />
</div>
Add this div element.
<div id="container"></div>
Change container variable.
let container = document.getElementById('container');
Add innerHTML method before your if statement.
container.innerHTML=""; //<-------------- This will clear your div before appending your new image
if (value === 'mba') { //Note: I have not changed the if statement
container.appendChild(aImg);
} else if (value === 'mbc') {
container.appendChild(cImg)
} else if (value === 'mbe') {
container.appendChild(eImg);
} else if (value === 'mbs') {
container.appendChild(sImg);
} else if (value === 'mbeq') {
container.appendChild(eqImg);
} else {
container.appendChild(eqeImg);
}
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);
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>
i've been searching in the internet for the possible solution but I can't find a possible solution. I hava a drop down list.
<select id="module-box" onchange="myFunction()">
<option value="">Select status</option>
<option value="1">Pending</option>
<option value="2">Approved</option>
<option value="3">Denied</option>
<option value="4">All</option>
</select>
And here's my javascript
function myFunction() {
var x = document.getElementById("module-box").value;
if(x==1){
window.location = "/pending";
}
else if(x==2){
window.location = "/approved";
}
else if(x==3){
window.location = "/denied";
}
else if(x==4){
window.location = "/list";
}
}
Upon selecting it will go to the specified url but the value of the combobox will return to value 0. Do you have any idea to make the selected value of the combobox to remain? Thanks.
You can use some item in Query String and upon page load, check the value of that item and set the selected item of the combo box accordingly.
See corrected code below:
var select_element = document.getElementById('module-box');
select_element.onchange = function(e){
if (!e)
var e = window.event;
var svalue = this.options[this.selectedIndex].value;
if(svalue==1){
window.location = "/pending";
}
else if(svalue==2){
window.location = "/approved";
}
else if(svalue==3){
window.location = "/denied";
}
else if(svalue==4){
window.location = "/list";
}
}
Check this link for DEMO
So I'm trying to change an image based on which option the user selects from a dropdown menu. My images for now are "cyan.png", "magenta.png", "yellow.png", "black.png", and "fuschia.png".
My HTML
<select name="color" multiple>
<option>Cyan</option>
<option>Magenta</option>
<option>Yellow</option>
<option>Black</option>
<option>Fuschia</option>
</select>
My JavaScript
// This part tries to load all images onto the carArray variable
var nameArray = new Array("cyan.png", "magenta.png", "yellow.png", "black.png", "fuschia.png");
var carArray = new Array;
for(var i = 0; i < carArray.length; i++) {
carArray[i] = new Image;
carArray[i].src = nameArray[i];
}
// This part tries (and fails) to change the image when the user selects a color from a dropdown menu
window.onload = function() {
var colorPicker = document.getElementsByName("color").selectedIndex;
var options = document.getElementsByName("color").options;
document.getElementById("photo").src = carArray[options[colorPicker];
}
Could you please help me understand what the problem is, and how to fix it.
If you bind your function on window.onload, it will only fire once at windows loading. You probably want to bind it on the select onchange event.
E.g.:
function pickColor() {
var colorPicker = document.getElementsByName("color").selectedIndex;
var options = document.getElementsByName("color").options;
document.getElementById("photo").src = carArray[options[colorPicker]];
}
<select name="color" onchange="pickColor()" multiple>
...
As #LightStyle suggests, you should avoid inline event assignments. I don't know your DOM, so for simplicity I'll add an id (it must be unique in the page) to your select. You can then do the following:
document.getElementById('color').onchange = function() {
var colorPicker = document.getElementsByName("color").selectedIndex;
var options = document.getElementsByName("color").options;
document.getElementById("photo").src = carArray[options[colorPicker]];
}
<select name="color" id="color" multiple>