Javascript Image Swap not activating function - javascript

I'm not much of a javascript coder so i am seeking any advice from anyone who may be able to help me with a problem i have, the main issue is i am trying to swap an image so that they can be selected by choosing a radio button.
<script language="JavaScript">
function changeImage(newImage)
{
if document[imageName].src = eval(newImage + ".src");
}
var img00700000232 = new Image();
img00700000232.src = "/2/00700000232.jpg";
var img00700000263 = new Image();
img00700000263.src = "/2/00700000263.jpg";
var img00700000270 = new Image();
img00700000270.src = "/2/00700000270.jpg";
var img00700000133 = new Image();
img00700000133.src = "images/TempImage.png";
var img00700000164 = new Image();
img00700000164.src = "images/TempImage.png";
var img00700000140 = new Image();
img00700000140.src = "images/TempImage.png";
var img00700000157 = new Image();
img00700000157.src = "images/TempImage.png";
</script>
</head><body>
<form name="test">
<input name="field" type="radio" value="00700000232" onchange="changeImage('img00700000232');">Prod1</input>
<br/>
<input name="field" type="radio" value="00700000263" onchange="changeImage('img00700000263');">Prod2</input>
<br/>
<input name="field" type="radio" value="00700000270" onchange="changeImage('img00700000270');">Prod3</input>
<br/>
<input name="field" type="radio" value="00700000133" onchange="changeImage('img00700000133');">Prod4</input>
<br/>
<input name="field" type="radio" value="00700000164" onchange="changeImage('img00700000164');">Prod5</input>
<br/>
<input name="field" type="radio" value="00700000140" onchange="changeImage('img00700000140');">Prod6</input>
<br/>
<input name="field" type="radio" value="00700000157" onchange="changeImage('img00700000157');">Prod7</input>
<br/>
</form>
<img name="image_name" src="images/TempImage.png" />
This is the code that is generated from ASP classic so the code is generated server side so im not sure whether this is an issue or whether there is a problem with my code, any and all help will be much appreciated.
Thanks
Brad

You have a syntax error:
if document[imageName].src = eval(newImage + ".src");
should be:
if( document["image_name"])
document["image_name"].src = eval(newImage + ".src");
EDIT:
A better way to get at the "image_name" DOM element though would be to change the 'name' attribute to 'id' and use document.getElementById instead.
So, that'd look like this:
<img id="image_name" src="images/TempImage.png" />
function changeImage(newImage)
{
var imgEle = document.getElementById("image_name");
if (imgEle){
imgEle.src = eval(newImage + ".src");
}
}
Also, you don't necessarily need to use eval here. You can reference the image variables in the Anchor tag if you want
so change this
<input name="field" type="radio" value="00700000164" onchange="changeImage('img00700000164');">Prod5</input>
to this
Prod5
which you would then have to change your function from
function changeImage(newImage)
{
var imgEle = document.getElementById("image_name");
if (imgEle && newImage){
imgEle.src = newImage.src;
}
}

Related

Google Apps Scripts - My button will not call the javascript function

This is the html code user input form:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div class="marginauto" align="middle">
<style>
.marginauto {
margin: 10px auto 20px;
display: block;
}
</style>
<h1>
<img class="marginauto" align="middle" src="https://drive.google.com/uc?export=view&id=********" alt="*****">
Fabrication Time Record
</h1 >
<h2 class="marginauto" align="middle">
Information
</h2>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"><br>
<label for="jnum">Job number:</label><br>
<input type="text" id="jnum" name="jnum"><br>
<h2>
Operation
</h2>
<input type="radio" id="cut" name="operation" value="cut">
<label for="cut">Cut</label><br>
<input type="radio" id="drill" name="operation" value="drill">
<label for="drill">Drill</label><br>
<input type="radio" id="fitup" name="operation" value="fitUp">
<label for="fitup">Fit Up</label><br>
<input type="radio" id="weld" name="operation" value="weld">
<label for="weld">Weld</label><br>
<h2>
Comments
</h2>
<input type="text" id="comment"><br>
<br>
<button id="clockin">Clock in</button>
</div>
<script type="text/javascript">
document.getElementById("clockin").addEventListener("click",addLine);
function addLine(){
var firstName = document.getElementById("fname");
var lastName = document.getElementById("lname");
var operation = document.getElementByName("operation");
var entry = {
entry.fn = firstName.value;
entry.ln = lastName.value;
entry.op = operation.value;
}
google.script.run.addEntry(entry);
firstName.value = "";
lastName.value = "";
}
</script>
</body>
</html>
This is the script that takes user inputs from the html and (ideally) transfers them to a google spreadsheet:
function doGet(e){
Logger.log(e);
var html = HtmlService.createHtmlOutputFromFile("userForm");
html.setTitle("Record Time")
return(html)
}
function addEntry(entry){
Logger.log("Someone clicked the button");
var ssid = "1E81*****************QBmW1o4Q";
var ss = SpreadsheetApp.openById(ssid);
SpreadsheetApp.setActiveSpreadsheet(ss);
var database = ss.getSheetByName("Database");
SpreadsheetApp.setActiveSheet(database);
database.appendRow = ([entry]);
}
When I click the button, nothing happens. I am sure that I am calling the correct spreadsheet because I can read and write from the doGet() function, but there seems to be a problem with the addLine() function that I cannot find.
Any help is greatly appreciated, I am very new to web app development.
What I want is for the button to transfer the data from some text input fields to a google spreadsheet. I used multiple different button syntaxes but cannot nothing happens.
You are passing an object to addEntry you should pass an array.
Change
var entry = {
entry.fn = firstName.value;
entry.ln = lastName.value;
entry.op = operation.value;
};
To
var entry = [
firstName.value,
lastName.value,
operation.value
];
Also you have a typo in your client script. Change
var operation = document.getElementByName("operation");
To
var operation = document.getElementsByName("operation");
However getElementsByName returns a node list so to find the checked radio button you need to add this to your client script.
let operations = document.getElementsByName("operation");
let operation = null;
for( let i=0; i<operations.length; i++ ) {
if( operations[i].checked ) {
operation = operations[i];
break;
}
}

Google apps HTML Form - Record and refresh form variable

I struggling with a custom golf stroke HTML form using google's html webapp service. The goal is for the form to dynamically refresh with the new stroke/hole numbers after you click a button. Eventually, it will record each stroke in a google spreadsheet
I can't figure out how to refresh the form and rebuild the html file with the new stroke/hole numbers after clicking either next shot or next hole. My code I have so far is rough as I am just hacking my way through this.
code.gs
function doGet(){
return HtmlService.createHtmlOutputFromFile('Index');
}
function doPost(){
Logger.log("Posted");
}
//hardcoded for testing, will start at 1 for each at beginning of round
var Hole = 11;
var Shot = 22;
var HoleShot = 3;
var DataArr = [Shot, Hole, HoleShot]
function Test() {
Hole++;
Logger.log(DataArr[2]);
Logger.log(HoleShot);
}
function HoleRead() {
return Hole;
}
function ShotRead() {
return Shot;
}
function HoleShotRead() {
return HoleShot;
}
function NextShot() {
//button function to add 1 to total shots and hole shot, but stay on same hole
//then refresh/clear the form and show the new shot number
Shot++;
HoleShot++;
Logger.log(HoleShot);
ShotToSheet();
//refresh or call NEXT html
return HtmlService.createHtmlOutputFromFile('NEXT');
}
function NextHole() {
//add +1 to hole and total shots but reset hole shot back to 1
//then refresh/clear the form and show the new shot/Hole number
}
function Complete() {
}
function ShotToSheet() {
//records teh 3 variables plus date to a row in a google spreadsheet
}
//builds an Input Spreadsheet if one doesnt exist
function SheetExist() {
var my_ss = "HTML To Sheet Test";
var my_sheet = "Input";
var files = DriveApp.getFilesByName(my_ss);
var file = !files.hasNext() ? SpreadsheetApp.create(my_ss) : files.next();
var ss = SpreadsheetApp.openById(file.getId())
try {
ss.setActiveSheet(ss.getSheetByName(my_sheet));
} catch (e) {
ss.insertSheet(my_sheet);
//[TO DO]add headers if first time creating Input Sheet
}
Logger.log(my_ss + " " + my_sheet);
//[TO DO]maybe return IDs or names to be used later
}
html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form id="ShotForm">
<br>
<span id="TotShot"></span>
<span id="Hole"></span>
<span id="HoleShot"></span>
<fieldset id = "ClubData">Club <br>
<input type="radio" name="Club" id="D" onclick = "ClubClick(this.value);" value="D">
<label for="D">D</label><br>
<input type="radio" name="Club" id="5i" onclick = "ClubClick(this.value);" value="5i">
<label for="5i">5i</label><br>
<input type="radio" name="Club" id="58" onclick = "ClubClick(this.value);" value="58">
<label for="58">58</label><br>
<input type="radio" name="Club" id="P" onclick = "ClubClick(this.value);" value="P">
<label for="P">P</label><br>
<br>
Type <br>
<input type="radio" name="Type" id="Tee Shot" onclick = "TypeClick(this.value);" value="Tee Shot">
<label for="Tee Shot">Tee Shot</label><br>
<input type="radio" name="Type" id="Fairway" onclick = "TypeClick(this.value);" value="Fairway">
<label for="Fairway">Fairway</label><br>
<input type="radio" name="Type" id="Rough" onclick = "TypeClick(this.value);" value="Rough">
<label for="Rough">Rough</label><br>
<input type="radio" name="Type" id="Green" onclick = "TypeClick(this.value);" value="Green">
<label for="Green">Green</label><br>
<br>
Distance <br>
<input type="number" name="Distance" onchange = "DistanceEdit(this.value);" min="1" max="1000">
</fieldset>
<span id="TotShot2"></span>
<span id="Hole2"></span>
<span id="HoleShot2"></span>
will be recorded as:<br>
<span id="Choice1">Club</span> -
<span id="Choice2">Type</span> -
<span id="Choice3">Distance</span>
<br> <br>
<input type="submit" name="NextShotButt" onclick = "NextShot();"value="Next Shot"><br> <br>
<input type="button" name="NextHoleButt" onclick = "NextHole();" value="Next Hole"><br> <br>
<input type="button" name="Complete" onclick = "Complete();" value="Complete">
</form>
</body>

Loop over an array and create form input tags after labels

Im trying to loop over an array to create some form tags, depending on how many values there are in the array. So far i have got my label and input tags that are being created. The problem i am having is displaying the input tags correctly after the labels. Any help would be much appreciated!
I'm trying to achieve:
<label class="material-label" for="leather_materials">
<input id="leather_materials" class="shoe-materials" type="radio" name="materials" value="leather">
<label class="material-label" for="suade_materials">
<input id="suade_materials" class="shoe-materials" type="radio" name="materials" value="suade">
<label class="material-label" for="nubuck_materials">
<input id="nubuck_materials" class="shoe-materials" type="radio" name="materials" value="nubuck">
my code so far:
materialArray = ['leather','suade','nubuck'];
//loop over material array
for( i = 0; i < materialArray.length; i++) {
//create label elements
var matLabel = document.createElement('label');
matLabel.setAttribute('for', materialArray[i] + '_materials');
matLabel.setAttribute('class', 'material-label');
console.log(matLabel);
//add text to label elements
var matLabelTextNode = document.createTextNode(materialArray[i]);
matLabel.appendChild(matLabelTextNode);
//create input elements
var matInput = document.createElement('input');
matInput.className = 'shoe-materials';
matInput.setAttribute('class', 'shoe-materials');
matInput.setAttribute('id', materialArray[i] +'_materials');
matInput.setAttribute('name', 'materials');
matInput.setAttribute('type', 'radio');
matInput.setAttribute('value', materialArray[i]);
console.log(matInput);
//append to parent div
addMaterials.appendChild(matLabel);
$('.material-label').after(matInput);
}
I tried using jQuery after() but it went a bit messed up and got the following
<label class="material-label" for="leather_materials">leather</label>
<input id="nubuck_materials" class="shoe-materials" type="radio" name="materials" value="nubuck">
<input id="suade_materials" class="shoe-materials" type="radio" name="materials" value="suade">
<input id="leather_materials" class="shoe-materials" type="radio" name="materials" value="leather">
<label class="material-label" for="suade_materials">suade</label>
<input id="nubuck_materials" class="shoe-materials" type="radio" name="materials" value="nubuck">
<input id="suade_materials" class="shoe-materials" type="radio" name="materials" value="suade">
<label class="material-label" for="nubuck_materials">nubuck</label>
<input id="nubuck_materials" class="shoe-materials" type="radio" name="materials" value="nubuck">
Mistake you're doing is appending those elements after the .material-label element. So you keep adding them after the labels which has already that class.
From :
$('.material-label').after(matInput);
To:
$(matLabel).after(matInput);
Updated code:
var addMaterials = document.getElementById("addMaterials");
materialArray = ['leather','suade','nubuck'];
//loop over material array
for( i = 0; i < materialArray.length; i++) {
//create label elements
var matLabel = document.createElement('label');
matLabel.setAttribute('for', materialArray[i] + '_materials');
matLabel.setAttribute('class', 'material-label');
console.log(matLabel);
//add text to label elements
var matLabelTextNode = document.createTextNode(materialArray[i]);
matLabel.appendChild(matLabelTextNode);
//create input elements
var matInput = document.createElement('input');
matInput.className = 'shoe-materials';
matInput.setAttribute('class', 'shoe-materials');
matInput.setAttribute('id', materialArray[i] +'_materials');
matInput.setAttribute('name', 'materials');
matInput.setAttribute('type', 'radio');
matInput.setAttribute('value', materialArray[i]);
console.log(matInput);
//append to parent div
addMaterials.appendChild(matLabel);
$(matLabel).after(matInput);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addMaterials"></div>
The jQuery statement $('.material-label') selects every element with that class, so when you use $('.material-label').after(matInput), you are adding the contents of matInput after each of the three labels.
To get the current label, just use i as the index for the array returned by $('.material-label').
Changing
//append to parent div
addMaterials.appendChild(matLabel);
$('.material-label').after(matInput);
To
//append to parent div
currentLabel = $('.material-label')[i];
$(currentLabel).after(matInput);
Will get the results you want.
Change '.material-label' to matLabel
$(matLabel).after(matInput);
Here is the JSFiddle: https://jsfiddle.net/82o6hfna/
I never liked the object manipulation approach to building html. I like to build the string of html then insert it into the dom. Just my opinion.
JS
//to uppercase of first letter only
String.prototype.toUpperCaseFirstLetter = function() {
var s = this;
return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}
var materialArray = ['leather','suade','nubuck'];
function buildMaterialRadios () {
var str = '';
for (var i = 0; i < materialArray.length; i++) {
var item = materialArray[i];
str += '<label class="material-label" for="'+item+'_materials">'+item.toUpperCaseFirstLetter()+'</label><input id="'+item+'_materials" class="shoe-materials" type="radio" name="materials" value="'+item+'">';
};
document.getElementById('material_selections').innerHTML = str;
}
buildMaterialRadios();
HTML
<form name="shoebuilderform">
<div id="material_selections"></div>
</form>
http://jsfiddle.net/qcmdnd4d/

JavaScript error msg : Uncaught TypeError: Cannot set property 'onclick' of null

The below javascript code is displaying nothing,although this code works by Fiddle perfectly. The javascript console gives me 2 error messages which I don't understand: Failed to load resource: net::ERR_FILE_NOT_FOUND and Uncaught TypeError: Cannot set property 'onclick' of null, so anyone understands the reason of the error messages and how can I get my code worked so it will calculate & display stuff that users will choose?
The code is:
var numericalValues = new Array();
numericalValues["Alot"]= 4;
numericalValues["NotMuch"]= 2;
numericalValues["NoSometimes"]= 3;
numericalValues["Hate"]= 0;
numericalValues["Chocolate"]= 4;
numericalValues["Carrot"]= 0;
numericalValues["Both"]= 2;
numericalValues["None"]= 0;
function getScoreChoco()
{
var scoreChoco = 0;
var form = document.forms["form"];
var choco = form.elements["choco"];
for(var i=0; i<choco.length; i++)
{
if(choco[i].checked)
{
scoreChoco = numericalValues[choco[i].value];
break;
}
}
return scoreChoco;
}
function getScoreCake()
{
var scoreCake = 0;
var form = document.forms["form"];
var cake = form.elements["cake"];
for(var i=0; i<cake.length; i++)
{
if(cake[i].checked)
{
scoreCake = numericalValues[cake[i].value];
break;
}
}
return scoreCake;
}
function getTotal()
{
var totalScore = getScoreCake() + getScoreChoco();
document.getElementById('result').innerHTML = "Your total score is: "+totalScore;
document.getElementById('calculate').onclick=getTotal;
}
Okay the HTML code for it:
<form id="form" name="form">
<fieldset id="controls">
<p>Do you like chocolate?
<label>Yes a lot </label>
<input type="radio" name="choco" id="alot" value="Alot" checked="true">
<label>Not that much </label>
<input type="radio" name="choco" id="notMuch" value="NotMuch">
<label>No, but still I don't mind eating it sometimes </label>
<input type="radio" name="choco" id="noSometimes" value="NoSometimes">
<label>No, I hate it </label>
<input type="radio" name="choco" id="hate" value="Hate">
</p>
<p>Do you prefer chocolate cake or carrot cake?
<label>chocolate </label>
<input type="radio" name="cake" id="chocolate" value="Chocolate" checked="true">
<label>Carrot </label>
<input type="radio" name="cake" id="carrot" value="Carrot">
<label>Both</label>
<input type="radio" name="cake" id="both" value="Both">
<label>None </label>
<input type="radio" name="cake" id="none" value="None">
</p>
<p>
<input type="button" name="Calculate" id="calculate" value="Calculate" />
</p>
<p id="result"></p>
</form>
I'm guessing that your javascript code is located above the HTML code. Therefore, when you try to access document.getElementById('calculate'), the html code has not been parsed yet, so there is no element with id calculate yet, so it returns undefined. Try putting the javascript code at the end of the body tag instead of wherever it is (probably in the head tag, im guessing)

How to input multiple checkbox values into a hidden textbox via javascript

Here's my code:
<script type="text/javascript" xml:space="preserve">
function ATHD(f) {
var aa = "I would like help with the following topic(s): "
var bb = "Password Reset "
var cc = "Password Setup "
var dd = "Firmware Upgrade (if applicable) "
var ee = "Local Access Setup "
var ff = "Remote Access Setup "
var gg = "Mobile Access Setup "
var hh = "Recording Schedule Setup "
var ii = "How to playback video "
var jj = "How to convert video "
var kk = "Email Notification Setup "
var ll = "PTZ Setup (if applicable) "
if( f.pr.checked == true) {
f.sup.value = aa + bb;
}
if( f.ps.checked == true) {
f.sup.value = aa + cc;
}
}
</script>
<form><input onclick="ATHD(this.form)" id="1" type="checkbox" name="pr" /> Password Reset<br />
<input onclick="ATHD(this.form)" id="2" type="checkbox" name="ps" /> Password Setup<br />
<input onclick="ATHD(this.form)" id="3" type="checkbox" name="fu" /> Firmware Upgrade (if applicable)<br />
<input onclick="ATHD(this.form)" id="4" type="checkbox" name="la" /> Local Access Setup<br />
<input onclick="ATHD(this.form)" id="5" type="checkbox" name="ra" /> Remote Access Setup<br />
<input onclick="ATHD(this.form)" id="6" type="checkbox" name="ma" /> Mobile Access Setup<br />
<input onclick="ATHD(this.form)" id="7" type="checkbox" name="rss" /> Recording Schedule Setup<br />
<input onclick="ATHD(this.form)" id="8" type="checkbox" name="pb" /> How to playback video<br />
<input onclick="ATHD(this.form)" id="9" type="checkbox" name="cv" /> How to convert video<br />
<input onclick="ATHD(this.form)" id="10" type="checkbox" name="en" /> Email Notification Setup<br />
<input onclick="ATHD(this.form)" id="11" type="checkbox" name="ptz" /> PTZ Setup (if applicable)<br />
<br />
<span style="FONT-WEIGHT: bold">Question</span><span style="COLOR: #ff0000">*</span> (please be specific)<br />
<br />
<textarea style="HEIGHT: 164px; WIDTH: 577px" rows="10" cols="40">
</textarea></p>
<p><button>Continue...</button>
<textarea style="HEIGHT: 164px; DISPLAY: hidden; WIDTH: 577px" rows="10" cols="40" name="sup">
</textarea>
 </p>
</form>
Basically, what I am looking to do is to whenever a box is checked, I want the value of the checkbox to be added into a hidden field. I understand that I still need to add the "value=[the value of the checkbox]" in the html code; what I want to allow for is multiple checkboxes to be selected so that multiple items will get added to the textbox.
I understand that one way of doing this would be to be to create if-then statements for every possible variation; this would not be very time effective as there would be thousands of permutations.
I am also trying to figure out if using an array would work to simplify this; I am not really sure how to conceptualize this in the simplest way as I have only been doing javascripting for three weeks. If someone can tell me how to think about this, I would greatly appreciate it. Looking more to learn how to do this so I can contribute to these forums and simplify the process of scripting functions as I do not have a background in coding.
If you can use jQuery, you won't need much code:
You could update the results whenever somebody clicks on a checkbox ($('input').on('click', function() {).
I personally would use <label> elements, but that's just me. You could grab the values by
$('input:checked').each(function() {
values.push($(this).parent().text());
});
Here is a working example: http://jsfiddle.net/HarryPehkonen/zNfju/1/
I have made small changes your dom like removing onclick events and It may solve your problem
var arr = [];
remove_item = function(arr,value){
for(b in arr ){
if(arr[b] == value){
arr.splice(b,1);
break;
}
}
return arr;
}
var inputs = document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++)
{
if(inputs[i].getAttribute('type') == 'checkbox')
{ inputs[i].addEventListener("change",function() {
if(this.checked)
arr.push(parseInt(this.id));
else
{
remove_item(arr,parseInt(this.id));
}
console.log(arr); document.getElementById("chcbx").value = arr.join(",");
},false);
}
}
and have a look at jsFiddle remove_item
Here's another way of doing it.
// find number of checkboxes (you haven't specified if you
// have a set number or not. If you have a set number, just
// set checkboxCount to whatever number you have.
var checkboxCount = 0;
var inputTags = document.getElementsByTagName('input');
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].type == 'checkbox') {
checkboxCount++;
}
}
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].getAttribute("name") + ';';
}
document.getElementById("hdnValues").value = totalValue;
alert(totalValue);
}
This basically counts all the checkboxes, loops through all, checks if they're checked, gets the value of the name attribute, then appends it to a string which is delimited by ;
jsfiddle: http://jsfiddle.net/mcDvw/
Alternatively, you could set all the values you want into the value attribute of the checkbox and read that instead of having the value in JS variable. e.g.
HTML:
<input onclick="ATHD()" id="1" type="checkbox" name="pr" value="Password Reset" /> Password Reset<br />
<input onclick="ATHD()" id="2" type="checkbox" name="ps" value="Password Setup" /> Password Setup<br />
JS:
function ATHD() {
var totalValue = '';
for (var i = 1; i < checkboxCount; i++) {
if (document.getElementById(i).checked)
totalValue += inputTags[i].value + ';';
}
document.getElementById("hdnValues").value = totalValue;
document.getElementById("showValues").value = totalValue;
}
jsfiddle: http://jsfiddle.net/mcDvw/1/

Categories

Resources