I am trying to store images in an array using javascript. I also want to assign each image from that array to an option from a drop down list. The images are on different servers.
My function doesn’t work no matter what I try. Can someone please help me with this?
P.S – In this case I am only allowed to use javascript (homework :/) and I must use arrays to store the images.
HTML code:
<form action="#" method="get" accept charset="utf-8">
<select id="car">
<option> BMW </option>
<option> Mercedes </option>
<option> Audi </option>
<option> VW </option>
</select>
<input type="button" value="select" onclick="myFunction();">
</form>
Javascript code:
function myFunction() {
var pictures = new Array();
pictures[0] = "https://pixabay.com/p-848904/?no_redirect";
pictures[1] = "http://www.pruebas.pieldetoro.net/web/MERCEDES/DOSSIERES/w115/8-1.jpg";
pictures[2] = "https://pixabay.com/p-1203738/?no_redirect";
pictures[3] = "https://cdn.pixabay.com/photo/2015/11/13/13/45/vw-beetle-1042002_960_720.jpg";
var index = document.getElementById('car').selectedIndex;
document.images[0].src="https://pixabay.com/p-848904/?no_redirect" + pictures[index] + ".jpg";
}
Thank you for your answers!
That code should work :
function myFunction()
{
var pictures = [
"https://pixabay.com/p-848904/?no_redirect",
"http://www.pruebas.pieldetoro.net/web/MERCEDES/DOSSIERES/w115/8-1.jpg",
"https://pixabay.com/p-1203738/?no_redirect",
"https://cdn.pixabay.com/photo/2015/11/13/13/45/vw-beetle-1042002_960_720.jpg"
];
var index = document.getElementById('car').selectedIndex;
document.getElementById('img1').src = pictures[index];
Related
What I want to do
Auto populate a form text field based on what is selected in a form select field.
What I have done so far
The code below is working perfectly fine during development:
STEP 1: I populate array of data
<script type="text/javascript">
var carcolorData = new Array();
carcolorData['Ford'] = 'Blue';
carcolorData['BMW'] = 'Green';
carcolorData['Fiat'] = 'Red';
carcolorData[''] = 'Hello';
</script>
STEP 2: I create a typical html form with a text and select field:
<form>
<select name="cartype" id="cartype" >
<option selected="selected"></option>
<option>Ford</option>
<option>BMW</option>
<option>Fiat</option>
</select>
<input name="carcolor" type="text" id="carcolor" />
</form>
STEP 3: I create a little javascript function to autopopulate onchange:
<script type="text/javascript">
document.form.cartype.onchange = showColor;
function showColor()
{
var obj_sel = document.form.cartype;
document.form.carcolor.value = carcolorData[obj_sel.value];
}
</script>
The problem
Doesn't work anymore after upload on public_html. Whatever I select it displays 'Hello' which is the color corresponding to blank in my example. I am totally lost... The code is correct since it works fine during development phase. Why is it not working anymore after upload on public_html?
Possible reasons
I am thinking of this but I may be far from the truth...
Different versions of IE (?)
Different development parameters (?)
Conflict with other javascript on the same page (?)
The javascript is not positioned correctly in the script (?)
I think it should be
document.forms
not document.form
To get the select "cartype", assume you got only one form, use:
document.forms[0].cartype
Also, are you missing the <form tag before the <select?
Change this
<script type="text/javascript">
document.form.cartype.onchange = showColor;
function showColor()
{
var obj_sel = document.form.cartype;
document.form.carcolor.value = carcolorData[obj_sel.value];
}
</script>
To this :
<script type="text/javascript">
var showColor = function ()
{
var myform = document.form; //maybe change this to match form with an id.
var selected_cartype = myform.cartype.options[myform.cartype.selectedIndex].value; //better do this to get a select value
myform.carcolor.value = carcolorData[selected_cartype];
}
document.form.cartype.onchange = showColor;
</script>
And there is another problem in the HTML : select's options have no value attribute.
<select name="cartype" id="cartype" >
<option selected="selected"></option>
<option>Ford</option>
<option>BMW</option>
<option>Fiat</option>
</select>
To
<select name="cartype" id="cartype" >
<option value="" selected="selected"></option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
<option value="Fiat">Fiat</option>
</select>
I need to figure out how to make my javascript take in the select names dynamically. How should I go about this?
I've tried Tried var i = getElementsByName() and then if (i == "x) ... else .... with no results
My Javascript:
function displayResult()
{
var m=document.getElementsByName("x");
document.getElementById('divid').innerHTML = m[0].value;
}
My Html:
<form>
<select name = x>
<option> a </option>
<option> b </option>
<option> c </option>
</select>
<select name = y>
<option> 2 </option>
<option> 3 </option>
<option> 4 </option>
</select>
</form>
The simplest solution would be with jQuery http://jquery.com
var myx = "x";
var elems = $("select[name=" + myx + "]");
Also with new browser APIs using pure Javascript:
var elems = document.querySelectorAll("select[name=x]")
https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll
So you need that x to be 'dynamic'. I don't really understand what you mean with that but I guess you want to specify another name every time you call the function. That's what function parameters are for.
Change your function to this:
function displayResult(name)
{
var m=document.getElementsByName(name);
document.getElementById('divid').innerHTML = m[0].value;
}
Now you can call the function with:
displayResult("x");
I think that what you are actually looking for is this:
var nodes = document.getElementsByTagName('select');
var names = new Array();
for(i=0,c=nodes.length;i<c;i++){
names.push(nodes[i].name);
}
this code will produce an array names containing the names of selects presented on the page
I've done a ton of research over the net to come to this code failure :( I have a select list that has an onchange event "emails()". When a certain index value is chosen, I have the javascript pull an array value to populate the "recipient" INPUT value. I know a little javascript, but not enough apparently. Any help would be great, thanks in advance and I apologize if this post isn't "forum correct" it's my first one :)
<html>
<head>
<script type="text/javascript">
function emails() {
var valObj = document.getElementsByName("recipient").value;
var selOpts = document.getElementsById("Concerning");
var selIndex = selOpts.selectedIndex;
var recValue = selOpts.options[selIndex].value;
var jvalObj = new Array()
jvalObj[0]="Empty";
jvalObj[1]="email#1";
jvalObj[2]="email#2";
jvalObj[3]="email#3";
jvalObj[4]="email#4";
jvalObj[5]="email#5";
jvalObj[6]="email#6";
jvalObj[7]="email#7";
jvalObj[8]="email#8";
jvalObj[9]="email#9";
for(i=0; i<selOpts.options.length; i++;)
if (recValue.value=="Benefits")
{valObj.value = jvalObj[1].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[2].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[2].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[3].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[4].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[5].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[6].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[7].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[8].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[3].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[2].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[9].value; break;}
}
}</script>
</head>
<body>
<form action="/cgi-bin/formmail" method="post" >
<td width=255 valign=top style='width:191.25pt;padding:0pt 0pt 0pt 0pt'>
<select onChange="javascript:emails();"
" id="Concerning">
<option value="">
<option value="Benefits">Benefits
<option value="Customer_Service">Customer Service
<option value="Employee_Paperwork">Employee Paperwork
<option value="Human_Resources"> Human Resources
<option value="Open_Positions">Open Positions
<option value="Payroll">Payroll
<option value="Quote_Request">Quote Request
<option value="Safety">Safety
<option value="Technical_Support">Technical Support
<option value="Training">Training
<option value="Unemployment">Unemployment
<option value="Workers_Compensation">Workers' Compensation
</select>
</td>
<input TYPE="hidden" NAME="recipient" VALUE="">
<input TYPE="hidden" NAME="subject" VALUE="Contact Form">
<input TYPE="hidden" NAME="email" VALUE="postmaster#company.com">
<input TYPE="hidden" NAME="required" VALUE="Name,Phone,Email,Concerning,Comments">
</form></body>
</html>
Now that I finally get it, this should do the trick.
document.getElementById('Concerning').onchange = function() {
var myArray = ["Empty",
"email#1",
"email#2",
"email#3",
"email#4",
"email#5",
"email#6",
"email#7",
"email#8",
"email#9"];
document.getElementsByName('recipient')[0].value = myArray[this.selectedIndex];
};
Although I might do something like this instead because it is a lot shorter:
document.getElementsByName('recipient')[0].value = 'email#' + this.selectedIndex;
I think this is a whole lot simpler than you are making it. If I am interpreting your code correctly, all you want to do is take the selected value of the list and stick it into the hidden input recipient. In that case you can pass this to the onChange declaration. The new selected value will be the value of that list. Finally, get the hidden input and set the value there.
http://jsfiddle.net/pvvQd/
<select onChange="emails(this);" id="Concerning">
In this code the function emails accepts a single parameter. We pass this to that parameter which is the select list. You used getElementsByName incorrectly in your original code. This returns an array of elements with that name (as name isn't unique per page). So assuming there is only one we retrieve the zero index. You should probably give that field an id and retrieve it by that instead. Finally we just set the hidden fields value to the select list's value.
function emails(elem) {
//you should probably give this an id and retrieve using that instead
var recipients = document.getElementsByName('recipient')[0];
recipients.value = elem.value;
}
Actually, if you wanted to make this super short you could do:
http://jsfiddle.net/pvvQd/1/
I would encourage you to stay away from inline javascript declarations. Instead you can do something like this. That way your code and html are not intertwined.
http://jsfiddle.net/pvvQd/2/
document.getElementById('Concerning').onchange = function() {
document.getElementsByName('recipient')[0].value = this.value;
};
I think you have a cut-n-paste error. document.getElementsById should be document.getElementById as it only grabs a single element.
There is also an error with an extra " <select onChange="javascript:emails();" " id="Concerning"> should be <select onChange="javascript:emails();" id="Concerning">
Also you onChange should just be onChange="emails();" don't need to add "javascript:"
Try changing inputs to have an ID value not just name that way instead of using document.getElementsByName (which returns an array and why your valObj.value assignment fails as it should be valObj[0].value = ) you can use document.getElementById("recipient")
You are also checking for the value of recValue here if (recValue.value=="Benefits")
when that variable is already the value so it should be recValue == "Benefits".
You don't need to go through all of the element as you already have the selected index and could just act off of that single value. The loop is just overkill. Not certain what you are trying to achieve there.
Suggested edits to the original source code, see comments for edits.
function emails()
{
var valObj = document.getElementsByName("recipient").value;
var selOpts = document.getElementsById("Concerning");
var selIndex = selOpts.selectedIndex;
var recValue = selOpts.options[selIndex].value;
/*Since the array will assing default integer indices where keys don't exist
we can rewrite the array as follows to spare redundant write access to it*/
var jvalObj = new Array("Empty", "email#1", "email#2", "email#3", "email#4",
"email#5", "email#6", "email#7", "email#8", "email#9");
for(i=0; i<selOpts.options.length; i++){
if (recValue.value=="Benefits"){
valObj.value = jvalObj[1].value;
i = selOpts.options.length;
/*Each of the deleted conditionals used the same comparison which means
that they will never meet their criteria without first meeting this
conditional, which was set to break the loop*/
}else if (selOpts.options[i].selected==true){
valObj.value = jvalObj[i].value;
/*Personal preference: unless you're bound to the use of break I'd leave use i = len
- the exception being where you'd want to retain i of course
*/
i = selOpts.options.length;
}
}
The html
<!-- DOM events carry out javascript callbacks by default -->
<select onChange="emails();" id="Concerning">
<!DOCTYPE html>
<html lang="eng">
<head>
<script type="text/javascript">
function emails()
{
var recipient = document.getElementById("recipient");
var concerning = document.getElementById("Concerning");
var recipientEmailToSet = concerning.options[concerning.selectedIndex].value;
recipient.value = recipientEmailToSet;
//Remove next line for alert to go away
alert(recipient.value);
}
</script>
</head>
<body>
<form action="/cgi-bin/formmail" method="post" >
<td width=255 valign=top style='width:191.25pt;padding:0pt 0pt 0pt 0pt'>
<select onChange="emails();" id="Concerning">
<option value=""></option>
<option value="email#1">Benefits</option>
<option value="email#2">Customer Service</option>
<option value="email#3">Employee Paperwork</option>
<option value="email#4"> Human Resources</option>
<option value="email#5">Open Positions</option>
<option value="email#6">Payroll</option>
<option value="email#7">Quote Request</option>
<option value="email#8">Safety</option>
<option value="email#9">Technical Support</option>
<option value="email#10">Training</option>
<option value="email#11">Unemployment</option>
<option value="email#12">Workers' Compensation</option>
</select>
</td>
<input TYPE="hidden" id="recipient" VALUE="" />
<input TYPE="hidden" id="subject" VALUE="Contact Form" />
<input TYPE="hidden" id="email" VALUE="postmaster#company.com" />
<input TYPE="hidden" id="required" VALUE="Name,Phone,Email,Concerning,Comments" />
</form>
</body>
</html>
I'm having an issue writing some code for a website. It's written in HTML/Javascript. I've managed to write a large chunk of code that seems to work alright, but this issue is now I can't seem to have multiple line strings within Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Multiline test</title>
</head>
<body>
<p>Select variable value below:</p>
<div>
<form name="form001">
<select name="choice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
<p id="selection"></p>
<script type="text/javascript">
// First, get the <select> element. findElementsByName() returns a collection,
// we only want the first elements that's found (hence the [0]):
var choice = document.getElementsByName('choice')[0];
// Now, get a reference to the <p> where we'll show the result:
var selectionP = document.getElementById('selection');
// This Array will hold the labels. label[0] will be 'Text1', labels[1] 'Text2', etc.
var labels = [
"Multiline test \n Multiline test",
"Text2",
"Text3"
];
// Now attach a handler to the onchange event.
// This function will be executed if the <select>ion is changed:
choice.onchange = function() {
var optionIndex = choice.selectedIndex; // The index of the selected option
var text = labels[optionIndex]; // The label that corresponds to that index
selectionP.innerHTML = text;
};
</script>
</body>
This is the updated code. Now all I need is a multiline work around.
This
document.form001.choice
"Text" + choice + "Text"}
Doesn't make any sense, does it? You need to do something like
var choice = document.form001.choice
"Text" + choice + "Text"}
By the way to follow the flow of your JavaScript program you should use Google Chrome's JavaScript Console. It really help understanding what's going on.
i noticed you wrote:
Now what I believe to be happening is that when it's not calling the
Javascript function as it is supposed to.
Inside your function either:
write:
console.log('this function is being executed');
// this will make a line show up in the chrome document inspector / firebug console (just google those)
or
alert('This function is being executed!')
That should help with troubleshooting a lot.
Note: I've put up a working example of this code here: http://jsfiddle.net/F87tJ/
Let's take the following HTML:
<html>
<head></head>
<body>
<p>Select variable value below:</p>
<div>
<form name="form001">
<select name="choice">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
</div>
<script type="text/javascript">
// JavaScript goes here
</script>
</body>
</html>
Now, I'm going to assume you want to respond to the user changing the selection of the dropdown box. This is pretty easy in JavaScript. Just get a reference to the <select> element and attach an event handler to it. An event handler is just a function that will be called when the given event occurs. In this case:
// First, get the <select> element. findElementsByName() returns a collection,
// we only want the first elements that's found (hence the [0]):
var choice = document.getElementsByName('choice')[0];
// Now attach a handler to the onchange event.
// This function will be executed if the <select>ion is changed:
choice.onchange = function() {
// Do something
};
With me so far? Good.
Now, you wanted to show 'Text1', 'Text2' or 'Text3', based on the selection, right? So, we have to know which <option> is selected. That, too, is easy:
var optionIndex = choice.selectedIndex;
This will just give you a zero-based index of the selected <option>. So, if the first option is selected, optionIndex will have value 0.
To show some text based on the selection, we need some strings. Since we're dealing with a collection here, let's put it in an array:
var labels = [
"Text1",
"Text2",
"Text3"
];
Arrays in JavaScript are also zero-based, so label[0] will be 'Text1', labels[1] 'Text2', etc.
If we bring it all together, we get something like this:
var choice = document.getElementsByName('choice')[0];
var labels = [
"Text1",
"Text2",
"Text3"
];
choice.onchange = function() {
var optionIndex = choice.selectedIndex; // The index of the selected option
var text = labels[optionIndex]; // The label that corresponds to that index
alert(text);
};
I hope this helps. :-)
I rewrote problem areas in your code, and added comments to show what was changed.
<!DOCTYPE html> <!-- HTML pages should have a DOCTYPE header, as well as html, head, and body tags. -->
<html>
<head>
<title></title>
</head>
<body>
Text
Text
Text
Text
<br/>
<br/>
Select variable value below:
<br/>
-
<div>
<form name="form001">
<select name="choice">
<!-- <size=3> Don't think there's a such thing as a size tag -->
<option value=1 selected="selected">1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>
<script type="text/javascript">
function js001(){ //This was missing paranthesis
var v1 = "Text1"
var v2 = "Text2"
var v3 = "Text3"
var choice = document.form001.choice; //choice wasn't defined
alert("Text" + choice + "Text");
}
</script>
<script type="text/javascript">
//js001();
</script> <!-- The S needed to be lowercase here -->
<div class="pagetext">
<br/>
<br/>
Text
<br/>
<br/>
Text
<div>
</body>
</html>
Here's another version which I think will do what you need.
When the user selects an item from the dropdown, it displays a text string below the dropdown that corresponds to the item that the user selected.
<html>
<body>
<form name="form001">
<!-- when the user changes the selected item in this dropdown, -->
<!-- the JavaScript function "js001()" will get called -->
<select name="choice" onchange="js001()">
<option value=0 selected="selected">1</option>
<option value=1>2</option>
<option value=2>3</option>
</select>
</form>
<!-- This is the div in which the selected item's related text will be shown -->
<div id="selectedStuff"/>
<script type="text/javascript">
function js001()
{
// Rather than use separate variables for each value,
// it is simpler if we store them in an array
var values = ["Text1", "Text2", "Text3"];
// The value of the selected item in the dropdown maps to the index in the values
// array for the text we want to show
var valueIndex = document.form001.choice.value;
var text = "Text" + values[valueIndex] + "Text"
document.getElementById("selectedStuff").innerHTML = text;
}
// When the page loads it makes sense to call the js001() function,
// so that the text for initially-selected dropdown value gets shown
js001();
</script>
</body>
</html>
Gang -
This is my first time posting. I'm a JavaScript noob - I think I've figured out what direction to take - just not sure how to get there.
I have a triple drop down select menu. I want the third(final) selection to reveal a hidden div. Am I on the right track by thinking I need to use a combination of onchange, getElementById and if statements?
The javascript code for the dropdown is Philip M's Cut & Paste Triple Combo box from JavaScriptKit.com. That work's beautifully. I won't insert my exact code as the category list is significantly longer.
var categories = [];
categories["startList"] = ["Wearing Apparel","Books"]
categories["Wearing Apparel"] = ["Men","Women","Children"];
categories["Books"] = ["Biography","Fiction","Nonfiction"];
categories["Men"] = ["Shirts","Ties","Belts","Hats"];
categories["Women"] = ["Blouses","Skirts","Scarves", "Hats"];
categories["Children"] = ["Shorts", "Socks", "Coats", "Nightwear"];
categories["Biography"] = ["Contemporay","Historical","Other"];
categories["Fiction"] = ["Science Fiction","Romance", "Thrillers", "Crime"];
categories["Nonfiction"] = ["How-To","Travel","Cookbooks", "Old Churches"];
var nLists = 3; // number of select lists in the set
function fillSelect(currCat,currList){
var step = Number(currList.name.replace(/\D/g,""));
for (i=step; i<nLists+1; i++) {
document.forms['tripleplay']['List'+i].length = 1;
document.forms['tripleplay']['List'+i].selectedIndex = 0;
}
var nCat = categories[currCat];
for (each in nCat) {
var nOption = document.createElement('option');
var nData = document.createTextNode(nCat[each]);
nOption.setAttribute('value',nCat[each]);
nOption.appendChild(nData);
currList.appendChild(nOption);
}
}
function getValue(L3, L2, L1) {
alert("Your selection was:- \n" + L1 + "\n" + L2 + "\n" + L3);
}
function init() {
fillSelect('startList',document.forms['tripleplay']['List1'])
}
navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false);
</script>
My HTML is:
<div id="menuSearch">
<form name="tripleplay" action="">
<p><select name='List1' onchange="fillSelect(this.value,this.form['List2'])">
<option selected>-- Topic of Interest --</option>
</select></p>
<p><select name='List2' onchange="fillSelect(this.value,this.form['List3'])">
<option selected>-- Geographic Area --</option>
</select></p>
<select id="info"name='List3' onchange="getValue(this.value, this.form['List2'].value, this.form['List1'].value)">
<option selected >-- Information Type --</option>
</select>
</form>
</div>
the divs to show/hide are:
<div id="modelingCV">list of publications</div>
<div id="groundwaterCV">list of publications</div>
<div id="subsidenceCV">list of publications</div>
<div id="managementCV">list of publications</div>
<div id="qualityCV">list of publications</div>
<div id="wildlifeCV">list of publications</div>
Is replacing the getValue in the onchange in the final form select with getElementByID the best approach? And replace the getValue in the javascript function with some type of if statement to specify the values? I am guessing I need to hide the divs with javascript vs CSS? Am I completely off base all around?
Oy. Definitely bit off more than I can chew on this one. Any guidance would be appreciated. Thanks for reading!