Drop down menu showing improper images based on selection - javascript

I have a drop down box that will change an image if a new selection is made. Which i have got to work using the following code
<HTML>
<HEAD>
<TITLE>JS1</TITLE>
<script LANGUAGE="JAVASCRIPT TYPE="TEXT/JAVASCRIPT">
<!--
image1 = new image(120,90)
image1.src = "desk1.gif"
image2 = new image(120,90)
image2.src = "desk2.gif"
image3 = new image(120,90)
image3.src = "desk3.gif"
image4 = new image(120,90)
image4.src = "desk4.gif"
function loadCatch(list)
{
var img = list.options[list.selectedIndex].value
document.thumbnail.src = eval(img + ".src")
}
</SCRIPT>
</HEAD>
<BODY>
<IMG SRC="desk1.gif" NAME="thumbnail" HEIGHT="90" WIDTH="120">
<FORM>
<SELECT NAME="catch" onChange="loadCatch(this)">
<OPTION VALUE="Image1">Bands
<OPTION VALUE="Image2">Clips
<OPTION VALUE="Image3">Lamp
<OPTION VALUE="Image4">Else
</SELECT>
</FORM>
</BODY>
</HTML>
The trouble is my form has 3-4 parts so when you click back to edit the form stays selected with the correct option selected but but the image shows the default image, I know this is because it is using an onChange event so I have investigated another way using the following code:
<script language="JavaScript" type="text/javascript">
<!--
var dropdownIndex = document.getElementById('colorsselect').selectedIndex;
var dropdownValue = document.getElementById('colorsselect')[dropdownIndex].value;
document.write(dropdownValue);
//-->
</script>
Which displays the correct image if I click to go back but it isn't live (onChange) so the user doenst get immediate result showing the new image.
I'm not sure how to combine the two pieces of code above, hope someone can help?

Call that same loadCatch function onload:
1) Add an id to the select box so you can reference it elsewhere:
<select id="catch" name="catch" onchange="loadCatch(this)">
2) Call loadCatch from on body load:
<body onload="loadCatch(document.getElementById('catch'))">
3) Adjust loadCatch to do nothing if a value hasn't been selected yet:
function loadCatch(list)
{
if (list.selectedValue != -1) {
var img = list.options[list.selectedIndex].value
document.thumbnail.src = eval(img + ".src")
}
}

Related

How do you save a state in HTML?

As you might know from my previous posts, I am developing a chrome extension. I have a button that toggles the extension on & off, and this button's state is saved when you click out of the extension. You can see the code for this below:
popup.html
<!DOCTYPE html>
<html>
<head>
<link rel="StyleSheet" type="text/css" href="style_popup.css"/>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<div class="navbar">
View My Dashboard
</div>
<h1 class="center">[Title]</h1>
<button id="buttonclick" class="button">Enable Control</button>
<br> <img src="green_circle.PNG" height="140" width="150" id="centerimage"> <br>
<p class="center" id="status"> [Title] is running! </p>
</body>
</html>
popup.js
let changeColor = document.getElementById('changeColor');
chrome.storage.sync.get('color', function(data) {
changeColor.style.backgroundColor = data.color;
changeColor.setAttribute('value', data.color);
});
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('buttonclick');
// onClick's logic below:
link.addEventListener('click', function() {
handler();
});
});
function handler()
{
chrome.storage.local.get({count: 0}, function (result) {
var count = result.count;
var buttonState = document.getElementById('buttonclick');
var imageState = document.getElementById('centerimage');
var status = document.getElementById('status');
if (count == 0) {
buttonState.style.backgroundColor = "#75ad0a";
buttonState.innerHTML = "Enabled";
imageState.src = "green_circle.PNG";
status.innerHTML = "[Title] is running!"
count = 1;
}
else {
buttonState.style.backgroundColor = "#AA2B0E";
buttonState.innerHTML = "Disabled";
imageState.src = "red_circle.png";
status.innerHTML = "[Title] is not running!"
count = 0;
}
chrome.storage.local.set({count: count});
});
}
However, I am running into a bit of a pickle. I want to make it such that if a user were to click the button (thereby disabling the extension), exit the chrome extension, and then click back into it, it would still show as disabled. With my current case, however, it will just display the "Enable Control" and "[Title] is running" every time they open the extension UNTIL the user clicks the button. In other words, it would be reset & and I want the state to be preserved. As you can see from my popup.js, I've already written code that saves the state of a variable, but I am unsure how to actually make the state be preserved in the HTML. I would greatly appreciate any help, thanks!

Having Trouble Switching Images

I'm just learning some java. I am currently learning if, else statements.
In the game I am creating, the user picks a number between 0 and 10 and puts it into an input box. If correct, the image on screen changes to one picture, if incorrect, it switches to a different picture. However, I cannot seem to get the images to change at all. I've tried a few different ways of coding; I'm currently using an img array. However, when I do the code I receive an ObjectHTMLImageElement error.
Here is my current code:
<div id="top">
<h1>Pie in the Face</h1>
<p>Guess how many fingers I'm holding up between 0 and 10.
<br /> If you guess correctly, I get a pie in the face.
<br /> If you guess wrong, you get a pie in the face.</p>
<input id="answer" />
<button id="myButton">Submit</button>
</center>
</div>
<div id="container">
<div id="image"></div>
<div id="manpie"></div>
<div id="girlpie"></div>
</div>
<script type="text/javascript">
var x = Math.random();
x = 11 * x;
x = Math.floor(x);
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = "images/manpie2.jpg";
imgArray[1] = new Image();
imgArray[1].src = "images/girlpie2.jpg";
document.getElementById("myButton").onclick = function() {
if (x == document.getElementById("answer").value) {
document.getElementById("image").innerHTML = imgArray[0];
// what I had document.getElementById("image").innerHTML=imgArray[0];
} else {
document.getElementById("image").innerHTML = imgArray[1];
}
}
</script>
</body>
I have also tried using lines such as: document.getElementById("image").innerHTML=document.getElementById("manpie");
and then nothing works. Here is a link to the "live" site it's on.
http://176.32.230.6/mejorarcr.com/
any help would be appreciated. Thank You!
You have to change the innerHTML value in your code:
if (x==document.getElementById("answer").value) {
document.getElementById("image").innerHTML='<img src="'+imgArray[0].src+'" />';
// what I had document.getElementById("image").innerHTML=imgArray[0].src;
} else {
document.getElementById("image").innerHTML='<img src="'+imgArray[1].src+'" />';
}
DEMO or this
change:
document.getElementById("image").innerHTML=imgArray[0];
to:
document.getElementById("image").setAttribute("src", imgArray[0]);
make sure imgArray[0] is the actual image path:
imgArray[0]="images/manpie2.jpg";
imgArray[1]="images/girlpie2.jpg";

change list options using google apps script

I want to load a list of items into a dropdown select box using a combination of html and javascript (google apps script).
I have been able to get all of the javascript functions to call and return values as expected, but when my code tries to add options to the select object, it seems to fail.
Here is my current HTML ('index'):
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
// The code in these functions run when the page is loaded.
google.script.run.withSuccessHandler(addItems).getFolderList();
//This function uses an array of folder names to create options for the select list
function addItems(folders){
alert('addItems was called!');
var htmlSelect = document.getElementById('folder');
for(var z = 0; z < folders.length; z++){
var selectBoxOption = document.createElement('OPTION');
selectBoxOption.value = folders[z];
selectBoxOption.text = folders[z];
htmlSelect.add(selectBoxOption); 
}
}
//this function lets the user know if the upload failed or not
function successMess(returnText) {
var div = document.getElementById('output');
div.innerHTML = '<p>'+returnText+'</p>';
}
</script>
</head>
<body>
<form id="myForm">
<p>Please choose a folder to receive the upload</p>
<select name="folder" id="folder">
<option value="Test Value">Test Value</option>
</select>
<br>
<input name="myFile" type="file" id="myFile"/>
<br>
<input type="button" value="Submit"
onclick="google.script.run.withSuccessHandler(successMess).processForm(this.parentNode)" />
</form>
<div id="output"></div>
</body>
</html>
Here is the accompanying JavaScript (.gs):
function doGet(){
return HtmlService.createHtmlOutputFromFile('index');
}
function processForm(formObject) {
var formBlob = formObject.myFile;
var folderName = formObject.folder;
var returnText = 'Please choose a valid file to upload';
if(formBlob.length > 0){
returnText = 'Your document was uploaded successfully!';
try{
var folder = DriveApp.getFoldersByName(folderName).next();
var driveFile = folder.createFile(formBlob);
}catch(e){
returnText = 'There was an error processing your document';
}
}
return returnText;
}
function getFolderList(){
Logger.log('getFolderList was called');
var ParentFolder = DriveApp.getFoldersByName('Test Folder').next();
var shopFolders = ParentFolder.getFolders();
var folderList = [];
while(shopFolders.hasNext()){
folderList.push(shopFolders.next().getName());
}
folderList.sort();
return folderList;
}
Everything is working beautifully...except the folder list population. I have manually populated the select options just to make sure the processForm function is working correctly. I have even tested (using another alert) to make sure that the folder name array from "getFolderList()" is being passed faithfully (and it is). It doesn't seem to have any problems getting the select item called "folder" or creating a new "option" item. It seems to fail when "addItems" tries to add the option to the list. Can anyone tell me what I'm doing wrong, and/or how to fix it?
Thanks!
Here is a solution to your problem:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="myForm">
<p>Please choose a folder to receive the upload</p>
<select name="folder" id="fldrList">
<option value="Test Value">Test Value</option>
</select>
<br>
<input name="myFile" type="file" id="myFile"/>
<br>
<input type="button" value="Submit"
onclick="google.script.run.withSuccessHandler(successMess).processForm(this.parentNode)" />
</form>
<div id="output"></div>
</body>
<script type="text/javascript">
// The code in these functions run when the page is loaded.
google.script.run.withSuccessHandler(addItems).getFolderList();
//This function uses an array of folder names to create options for the select list
function addItems(folders){
console.log('addItems was called!' + folders);
var htmlSelect = document.getElementById('fldrList');
console.log('htmlSelect: ' + htmlSelect);
var optionHTML = '';
for(var z = 0; z < folders.length; z++){
console.log('z: ' + z);
console.log('folders[z]: ' + folders[z]);
optionHTML = optionHTML + "<option value='" + folders[z] + "'>" + folders[z] + "</option>";
};
htmlSelect.innerHTML = optionHTML;
}
//this function lets the user know if the upload failed or not
function successMess(returnText) {
var div = document.getElementById('output');
div.innerHTML = '<p>'+returnText+'</p>';
}
</script>
</html>
Change the id name of your select element from folder to fldrList.
Unfortunately, the add method is not working. You can create the HTML in the form of a string and inject it.
Notice that the FOR LOOP creates an HTML string, then when the FOR LOOP is done, the HTML is injected into the SELECT element. It works. For some reason, Apps Script doesn't seem to be allowing the .add method. Don't know why.

dropdown menu in javascript with adding new elements

I am new in javascript and in this moment I am trying to use "Basic DOM and JS". I am doing a dropdown menu, what gets his elements from an array. There is an input field, where you can add new items into the array.I also made a button to push and save the item into array and make the dropdown automatically with DOM.
My problem if you push the button, it makes always a new dropdown menu. Otherwise the array works good, but I need just one dropdown menu with the items of array. I think this problem comes out at listing with ul li too. Here is my whole code and thanks for helping
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
var menu = document.createElement("select");
document.body.appendChild(menu);
for(var i = 0; i<select.length; i++){
var option = document.createElement("option");
var text = document.createTextNode(select[i]);
option.appendChild(text);
menu.appendChild(option);
}
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
You are creating the select tag every time array() is invoked. So create select tag once and rest of the time create option tag when array() is invoked. Here is your solution.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
var select = new Array;
var selectIsCreated = false;
var menu;
function array(){
var input = document.getElementById("input");
var value = input.value;
select.push(value);
if(!selectIsCreated){
menu = document.createElement("select");
document.body.appendChild(menu);
selectIsCreated = true;
}
var option = document.createElement("option");
var text = document.createTextNode(select[select.length-1]);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<input onclick="array()" type="button" value="Add">
</body>
</html>
So Suman already answered your question, but in terms of simplifying the code or the approach, I think you could take a different approach by removing the use of the "select" array entirely. The array isn't necessary to add in the value to the select list, as you can get everything you need from the input element, so you just need to work on adding the option to the actual select DOM element.
Here is the desired functionality re-factored a bit with this in mind.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<meta charset="utf-8">
<script>
function createSelect() {
select = document.createElement('select');
select.id = 'select';
document.body.appendChild(select);
return document.getElementById('select');
}
function addOption(){
var input = document.getElementById("input");
var value = input.value;
// This will attempt to grab the 'select' element, but if it finds
// that it doesn't exist (i.e. getElementById returns a "falsy" value)
// then it will return the value of the createSelect function.
// This could also be done with more explicit "if" statements
var menu = document.getElementById('select') || createSelect();
// The same effect could be achieved by running this code:
/*
var menu = document.getElementById('select');
// If the select element hasn't been created/added to the page yet,
// then the above call to getElementById will return a "falsy" value,
// i.e. a value that isn't a strict boolean type but JS will treat it
// as "false".
if (!menu) {
menu = createSelect();
}
*/
var option = document.createElement("option");
var text = document.createTextNode(value);
option.appendChild(text);
menu.appendChild(option);
}
</script>
</head>
<body>
<input id="input" type="text">
<!--
I've renamed the array() function since we don't even
have an array anymore
-->
<input onclick="addOption()" type="button" value="Add">
</body>
</html>
You can see this in action on this jsFiddle

Issue trying to get website to work - possible issue with my html code?

SO I have code that I'm trying to implement from my jsfiddle into an actual working website/mini-app. I've registered the domain name and procured the hosting via siteground, and I've even uploaded the files via ftp so I'm almost there...
But I'm thinking there's something wrong with my HTML code or JS code or how I implemented my JS code into my HTML code, because all of the HTML and CSS elements are present, but the javascript functionality is absent.
Here is my fiddle:
jsfiddle
^^ Click on start to see the display in action (which doesn't work in the actual website, which leads me to believe there's an issue with my JS file - whether it be code-related or whether that's because I integrated the file incorrectly) (or maybe even uploaded to the server incorrectly, perhaps?)...
And here is the actual site:
http://www.abveaspirations.com/index.html
And here's my HTML code uploaded to the server via FTP:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id='frame'>
<div id='display'>
<h1 id='output'></h1>
</div>
</div>
<div class="spacer">
</div>
<div id="main"> <!-- 11main -->
<h1 id='consoleTitle'>Control Board</h1>
<h5 id='consoleSub'><i>Double-click on an entry to remove. And add entries to your heart's desire...</i></h5>
<div id="controlbox"> <!-- ##controlbox -->
<div id="controlpanel"></div>
<div class="spacer"></div>
<div id="formula"> <!--formula -->
<form id="frm" method="post">
<input id="txt" type="text" placeholder="Insert your own entry here..." name="text">
<input id='submitBtn' type="submit" value="Start">
<input id='stop' type="button" value="Stop">
<select id="load1">
<option id='pre0' value="Preset 0">Preset 0</option>
<option id='pre1' value="Preset 1">Preset 1</option>
<option id='pre2' value="Preset 2">Preset 2</option>
</select>
<!-- These are for buttons as opposed to OPTION...
<input id="load" type="button" value="Preset 1">
<input id="load2" type="button" value="Preset 2"-->
</form>
</div> <!-- formula -->
</div> <!-- ##controlbox -->
</div> <!-- 11main -->
</body>
And my JS code, also uploaded to server via FTP (I didn't include the accompanying CSS file, but if that would help, I can provide ):
$(document).ready(function () {
var txtBox = $('#txt');
var frm = $('#frm');
var output = $('#output');
var subBtn = $('#submitBtn');
var stopBtn = $('#stop');
var loadBtn = $('#load');
var loadBtn2 = $('#load2');
var loadBtnA = $('#load1');
var pre0 = $('#pre0');
var pre1 = $('#pre1');
var pre2 = $('#pre2');
var txt = $('#display');
var preset1 = ["1", "2", "3"];
var preset2 = ["a", "b", "c"];
var container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
var console = $('#controlpanel');
var oldHandle;
function loadPreset0() {
container = [];
console.empty();
container = ["What we do in life echoes in all eternity.", "Find your purpose and give it life.", "When you work your hardest, the world opens up to you."];
updateConsole();
};
function loadPreset1() {
container = [];
console.empty();
container = preset1;
updateConsole();
};
function loadPreset2() {
container = [];
console.empty();
container = preset2;
updateConsole();
};
$(pre0).data('onselect', function() {
loadPreset0();
});
$(pre1).data('onselect', function() {
loadPreset1();
});
$(pre2).data('onselect', function() {
loadPreset2();
});
$(document).on('change', 'select', function(e) {
var selected = $(this).find('option:selected'),
handler = selected.data('onselect');
if ( typeof handler == 'function' ) {
handler.call(selected, e);
}
});
function updateConsole() {
for (var z = 0; z < container.length; z++) {
var resultC = container[z];
var $initialEntry = $('<p>' + '- ' + resultC + '</p>');
console.append($initialEntry);
};
};
updateConsole();
frm.submit(function (event) {
event.preventDefault();
if (txtBox.val() != '') {
var result = txtBox.val();
container.push(result); //1.
var resultB = container[container.length-1];
var $entry = $('<p>' + '- ' + resultB + '</p>');
console.append($entry); //2.
}
var options = {
duration: 5000,
rearrangeDuration: 1000,
effect: 'random',
centered: true
};
stopTextualizer();
txt.textualizer(container, options);
txt.textualizer('start');
txtBox.val('');
});
$("#controlbox").on('dblclick', 'p', function() {
var $entry = $(this);
container.splice($entry.index(), 1);
$entry.remove();
});
function stopTextualizer(){
txt.textualizer('stop');
txt.textualizer('destroy');
}
$(stopBtn).click(function() {
stopTextualizer();
});
});
Any help would be appreciated. I guess I'm just not sure what to do after uploading the html file to the server via ftp. Or maybe I did that correctly and there's something wrong with my code that I'm overlooking. Basically I'm lost. So help please!
You forgot to load jQuery. Make sure that you use <script src="../path-to-jquery/jquery.js"></script> before you load your script.js script.
Also, I noticed that you're loading your scripts in the head tag. This is bad practice, load them right before </body>.
I believe your site is missing jQuery. Add this to the top of your code to hotlink to google's jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Categories

Resources