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>
Related
Image of empty list
Showing populated options within inspector
I dynamically add options through a JS file based on the DB items. They sometimes populate when I CTRL+SHIFT+R hard refresh the page but not every time.
They never populate when I do a regular refresh (ctrl+r).
I am genuinely so confused how the options could be populated inside the inspector but not actually visible..
The JS is also surrounded with $(document).ready(function ()) so to my knowledge it only runs once the page is ready.
Function where I populate one of the dropdowns
function renderEndUseDropdown()
{
var endUseList = new Set(filteredProductList.map((element) => element.endUse));
var endUse = Array.from(endUseList);
var endUseSelection = document.getElementById("processname");
for(var i = 0; i < endUse.length; i++)
{
if(endUse[i] !== '')
{
var option = endUse[i];
var displayElement = document.createElement("option");
displayElement.textContent = option;
displayElement.value = option;
endUseSelection.add(displayElement);
}
}
}
The above code would be adding options to this block of HTML
<div class="col-xs-12 col-sm-6 col-md-2">
<select class="selectpicker" multiple="multiple" data-live-search="true" title="End Use" id="processname" multiple data-actions-box="true">
</select>
</div>
Since you are using bootstrap-select, this needs to be done.
So your function could be updated like below.
function renderEndUseDropdown()
{
var endUseList = new Set(filteredProductList.map((element) => element.endUse));
var endUse = Array.from(endUseList);
var endUseSelection = document.getElementById("processname");
for(var i = 0; i < endUse.length; i++)
{
if(endUse[i] !== '')
{
var option = endUse[i];
var displayElement = document.createElement("option");
displayElement.textContent = option;
displayElement.value = option;
endUseSelection.add(displayElement);
}
}
$('#processname').selectpicker('refresh');
}
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 have created a javascript search in select element.
option tag does not get any CSS to hide or display none, for this solution I have removed unmatched option and make a backup for removed option for reset list button.
It's working fine but I have a problem, I have about 19000 option for this select list.
search works fine but when I hit reset button, only 9500 option from 19000 comes back.
I appreciate your help.
Here is the code:
CodePen Demo
HTML
<h1>Search in select "option" tag</h1>
<select multiple name="selectMenu" id="selectMenu" style="width:100px" size=10>
<option value ="item 1">item 1</option>
<option value ="item 2">item 2</option>
<option value ="thing 3">thing 3</option>
<option value ="item 4">item 4</option>
<option value ="stuff 5">stuff 5</option>
<option value ="stuff 6">stuff 6</option>
<option value ="stuff 7">stuff 7</option>
<option value ="item 8">item 8</option>
</select>
<p>Search within this list</p>
<input type=text name="search" id="search" onkeypress="searchItems();">
<br>
<input type=button value="Search" onclick="searchItems();">
<input type=button value="Reset List" onclick="resetList();">
Javascript
var itemList = null;
var itemListOriginal = new Array();
var backup = false;
function searchItems() {
itemList = document.getElementById("selectMenu");
var searchStrObj = document.getElementById("search");
var itemDescription = "";
// replace white space with wild card
var searchString = searchStrObj.value;
searchString = searchString.replace(" ", ".*");
var re = new RegExp("(" + searchString + ")", "i"); //"i" sets "ignore case" flag
if (itemListOriginal.length < 1)
backup = true;
else
backup = false;
// loop through options and check for matches
for (i=itemList.options.length - 1; i >=0 ; i--) {
itemDescription = itemList.options.item(i).text;
if (backup) {
hash = new Array();
hash['name'] = itemDescription;
hash['value'] = itemList.options.item(i).value;
itemListOriginal[i] = hash;
}
if (!itemDescription.match(re)) {
itemList.remove(i);
}
}
return false;
}
function resetList() {
//hack! remove all elements from list before repopulating
for (i=itemList.options.length - 1; i >=0 ; i--) {
itemList.remove(i);
}
for (i=0; i < itemListOriginal.length; i++) {
hash = itemListOriginal[i];
//option = new Option(hash['name'], hash['value']); REMOVED
//itemList.options.add(option, i); REMOVED
itemList.options[i] = new Option(hash['name'], hash['value'], false, false);
}
document.getElementById("search").value = "";
}
DEMO
I've observed that in your code backup is changed every time you call the function searchitems().
Thus erasing the old values that were stored in it.
So I've changed that
It is working fine but I have a problem,
I have about 19000 option for this select list.
search works fine but when I hit reset button,
only 9500 option from 19000 comes back.
That is the reason behind that. So I've modified your code and added a global variable backupList in that.
so when the unwanted elements are removed old elements aren't deleted in my code but instead, new removed elements are appended to old removed elements using += shorthand operator.
also rather creating options dynamically and using .add or .append or any similar javascript method I'm using .innerHTML for simplicity as you can see in the code. only problem is that now after you click reset elements will not be sorted as it was in the first case, You'll need to sort them believe me it is easy. for sorting refer: sort select menu alphabetically?.
var itemList = null;
var itemListOriginal = new Array();
var backup = false;
var backupList =""; // To store removed elements
function searchItems() {
itemList = document.getElementById("selectMenu");
var searchStrObj = document.getElementById("search");
var itemDescription = "";
var searchString = searchStrObj.value;
searchString = searchString.replace(" ", ".*");
var re = new RegExp("(" + searchString + ")", "i"); //"i" sets "ignore case" flag
for (i=itemList.options.length - 1; i >=0 ; i--) {
itemDescription = itemList.options.item(i).text;
var hash = new Array();
hash['name'] = itemDescription;
hash['value'] = itemList.options.item(i).value;
itemListOriginal[i] = hash;
if (!itemDescription.match(re)) {
itemList.remove(i); //Remove Unwanted Elements
backupList+="<option value='"+ hash['value']+"'>"+itemDescription+"</option>";
/* append new unwanted elements with previous,
initially it is blank "".
This is Important
*/
}
}
return false;
}
function resetList() {
var itemList = document.getElementById("selectMenu");
itemList.innerHTML+=backupList; /* Add removed elements to list.
alternate to .append,.add or similar function*/
backupList=""; // Make Backup Empty!
document.getElementById("search").value = "";
}
Hope it helps! cheers :)!
I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I'm hoping I can achieve this on the fly. Also if the value changes it should add or remove appropriately.
What programming language would I need to do this in? I'm using PHP for the overall website.
Here is an example that uses jQuery to achieve your goals:
Assume you have following html:
<div>
<select id="input_count">
<option value="1">1 input</option>
<option value="2">2 inputs</option>
<option value="3">3 inputs</option>
</select>
<div>
<div id="inputs"> </div>
And this is the js code for your task:
$('#input_count').change(function() {
var selectObj = $(this);
var selectedOption = selectObj.find(":selected");
var selectedValue = selectedOption.val();
var targetDiv = $("#inputs");
targetDiv.html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
You can simplify this code as follows:
$('#input_count').change(function() {
var selectedValue = $(this).val();
var targetDiv = $("#inputs").html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/
You can read more about jQuery: http://jquery.com/
I would go for jQuery.
To start with look at change(), empty() and append()
http://api.jquery.com/change/
http://api.jquery.com/empty/
http://api.jquery.com/append/
Doing it in javascript is quite easy. Assuming you've got a number and an html element where to insert. You can obtain the parent html element by using document.getElementById or other similar methods. The method assumes the only children of the parentElement is going to be these input boxes. Here's some sample code:
function addInput = function( number, parentElement ) {
// clear all previous children
parentElement.innerHtml = "";
for (var i = 0; i < number; i++) {
var inputEl = document.createElement('input');
inputEl['type'] = 'text';
// set other styles here
parentElement.appendChild(inputEl);
}
}
for the select change event, look here: javascript select input event
you would most likely use javascript(which is what jquery is), here is an example to show you how it can be done to get you on your way
<select name="s" onchange="addTxtInputs(this)" onkeyup="addTxtInputs(this)">
<option value="0">Add</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="7">7</option>
</select>
<div id="inputPlaceHolder"></div>
javascript to dynamically create a selected number of inputs on the fly, based on Mutahhir answer
<script>
function addTxtInputs(o){
var n = o.value; // holds the value from the selected option (dropdown)
var p = document.getElementById("inputPlaceHolder"); // this is to get the placeholder element
p.innerHTML = ""; // clears the contents of the place holder each time the select option is chosen.
// loop to create the number of inputs based apon `n`(selected value)
for (var i=0; i < n; i++) {
var odiv = document.createElement("div"); //create a div so each input can have there own line
var inpt = document.createElement("input");
inpt['type'] = "text"; // the input type is text
inpt['id'] = "someInputId_" + i; // set a id for optional reference
inpt['name'] = "someInputName_" + i; // an unique name for each of the inputs
odiv.appendChild(inpt); // append the each input to a div
p.appendChild(odiv); // append the div and inputs to the placeholder (inputPlaceHolder)
}
}
</script>
Let's say that I have select list with 3 options inside:
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Now, I want to update one of these options, so i create textfield & button.
The option appear inside the textfield everytime i press on one of the options at the select list.
Can someone direct me what do i need to do?
thanks
Adding up to the first example that we had this morning jsfiddle
HTML:
<select id='myselect'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
<input type='text' value='1' name='mytext' id='mytext' />
<button value='add' id='addbtn' name='addbtn'>add</button>
<button value='edit' id='editbtn' name='editbtn'>edit</button>
<button value='delete' id='deletebtn' name='deletebtn'>delete</button>
JavaScript:
var myselect = document.getElementById('myselect');
function createOption() {
var currentText = document.getElementById('mytext').value;
var objOption = document.createElement("option");
objOption.text = currentText;
objOption.value = currentText;
//myselect.add(objOption);
myselect.options.add(objOption);
}
function editOption() {
myselect.options[myselect.selectedIndex].text = document.getElementById('mytext').value;
myselect.options[myselect.selectedIndex].value = document.getElementById('mytext').value;
}
function deleteOption() {
myselect.options[myselect.selectedIndex] = null;
if (myselect.options.length == 0) document.getElementById('mytext').value = '';
else document.getElementById('mytext').value = myselect.options[myselect.selectedIndex].text;
}
document.getElementById('addbtn').onclick = createOption;
document.getElementById('editbtn').onclick = editOption;
document.getElementById('deletebtn').onclick = deleteOption;
myselect.onchange = function() {
document.getElementById('mytext').value = myselect.value;
}
Basically i added an edit field that when clicked it'll edit the value and text of the currently selected option, and when you select a new option it'll propogate the textfield with the currently selected option so you can edit it. Additionally, i also added a delete function since i figure you might need it in the future.
Use jquery :selected selector and val() method.
$('select:selected').val($('input_textbox').val());
First of all always give an ID to your input tags. For eg in this case you can do something like: <select id='myDropDown'>
Once you have the ID's in place its simple matter of picking up the new value from textbox and inserting it into the dropdown:
Eg:
// Lets assume the textbox is called 'myTextBox'
// grab the value in the textbox
var textboxValue = document.getElementById('myTextBox').value;
// Create a new DOM element to be inserted into Select tag
var newOption = document.createElement('option');
newOption.text = textboxValue;
newOption.value = textboxValue;
// get handle to the dropdown
var dropDown = document.getElementById('myDropDown');
// insert the new option tag into the dropdown.
try {
dropDown.add(newOption, null); // standards compliant; doesn't work in some versions of IE
}
catch(ex) {
dropDown.add(newOption); // IE only
}
Below is a pure js example using your markup.
EDIT
After rereading your question Im not sure if you wanted the option to update when a user clicked the button or not.. To just put the option into an input you can do this.
var select = document.getElementsByTagName("select")[0],
input = document.getElementById("inputEl");
select.onchange = function(){
input.value = this[this.selectedIndex].text;
}
To update the option to what the user typed in is below.
http://jsfiddle.net/loktar/24cHN/6/
Markup
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<br/>
<input type="text" id="inputEl"/>
<button id="button">Update</button>
Javascript
var select = document.getElementsByTagName("select")[0],
input = document.getElementById("inputEl"),
button = document.getElementById("button");
select.onchange = function(){
input.value = this[this.selectedIndex].text;
var selected = this,
selectedIndex = this.selectedIndex;
button.onclick = function(){
selected[selectedIndex].text = input.value;
}
}