I have recently started using javascript and perhaps got a little in over my head. I'm trying to create a tool for one of my other hobbies that creates coordinates for fences from x1,y1 to x2,y2.
The part that I am getting hung up on right now is part of the UI. I want the user to be able to select their desired fence from a dropdown menu and then for the rest of the information pertaining to the fence (name, length, width, direction, etc.) to be filled into the input fields below. From there they will be referenced in the math portion which I already have done.
I want the fence pieces to be objects because I'm going to add more eventually and perhaps allow the user to add more and I figured that was the easiest more user friendly way to go about it.
I have managed to get to the point where the options are in the dropdown menu, I can select them, and it will fill the piece name in with the value which is the name but I cannot figure out how to access the length, width, height, etc.
This is my first project outside of Code Academy and a little bit I did 10 years ago in High School. That being said, if you notice that I am doing something else stupid, feel free to point it out. The answers for other's questions here have already been a huge source of help for me as I worked on this, so thank you for that and for the future help.
<script>
//Start Variable Library
var dropMenuPieceName = 0;
var dropMenuPieceName = 0;
//End Variable Library
// Start Function Library
var fencePieceDropDown = function(dropDownMenuID) {
var dropMenu = document.getElementById(dropDownMenuID);
for(var i = 0; i < fenceArray.length; i++) {
var dropMenuOption = document.createElement("option");
var dropMenuPieceName = fenceArray[i].name;
var dropMenuPieceName = fenceArray[i].length;
dropMenuOption.innerHTML = fenceArray[i].model;
dropMenuOption.value = fenceArray[i].name;
var dropMenuIndex = 1;
dropMenu.add(dropMenuOption,dropMenuIndex);
};
};
//End Function Library
// Start Fence Object Library
function Fence(name,model,length,width,direction,x_offSet,y_offSet,z_offSet,r_offSet) {
this.name = name;
this.model = model;
this.length = length;
this.width = width;
this.direction = direction;
this.x_offSet = x_offSet;
this.y_offSet = y_offSet;
this.z_offSet = z_offSet;
this.r_offSet = r_offSet;
};
var fenceArray = new Array();
var plot_ohrada = new Fence
("plot_ohrada","plot_ohrada",3,0.1,0.02,0,0,0,0);
fenceArray[0] = plot_ohrada;
var plot_ohrada_pruchozi = new Fence
("plot_ohrada_pruchozi","plot_ohrada_pruchozi",4,0.2,0.02,0,0,0,0);
fenceArray[1] = plot_ohrada_pruchozi;
var plot_ohrada_zlomena = new Fence
("plot_ohrada_zlomena","plot_ohrada_zlomena",5,0.3,0.03,0,0,0,0);
fenceArray[2] = plot_ohrada_zlomena;
//End Fence Object Library
</script>
</head>
<body>
<form name="primPieceSection">
<div align="center">
Piece Model:
<select id="primPieceModel" >
<option value = 0>Custom Piece</option>
<select><br /><br /><br />
Piece Name: <input type="text" id="primPieceName" placeholder="Insert Template Name"><br />
Piece Length: <input type="text" id="primPieceLength" value=0><br />
Piece Width: <input type="text" id="primPieceWidth" value=0><br />
Piece Direction: <input type="text" id="primPieceDir" value=0><br />
</div>
</form>
<script>
var primPieceNameField = document.getElementById("primPieceName");
var primPieceLengthField = document.getElementById("primPieceLength");
var primPieceModelDrop = document.getElementById("primPieceModel");
primPieceModelDrop.onchange = function() {
primPieceNameField.value = this.value; ///this should return the object's name
primPieceLengthField.value = this.value; ///this should return the object's length. I just put in this.value while I was testing it.
};
fencePieceDropDown("primPieceModel");
</script>
In your case, the value of each dropdown option should be not its name, but rather the index of the corresponding fence in the fenceArray, which is i. Then, inside primPieceModelDrop.onchange, you will use fenceArray[this.value] to access the selected fence object.
So, you need to replace this line:
dropMenuOption.value = fenceArray[i].name;
with this:
dropMenuOption.value = i;
And then rewrite the onchange handler as follows:
primPieceModelDrop.onchange = function() {
primPieceNameField.value = fenceArray[this.value].name;
primPieceLengthField.value = fenceArray[this.value].length;
};
What you’re doing is perfectly reasonable for a beginner, but you should understand that it’s a somewhat simplistic, low-level approach. As you become more confident in JS, and as your project grows, you may find it easier to employ a framework such as AngularJS.
Related
I have a code where I am trying to calculate a total value based on the value of the input selected by a user. It seems simple but I can't get the total to reflect. Please can someone show me where the fault is?
function calculate() {
var panel = parseInt(document.getElementsById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
}
document.getElementsById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate">Result</button>
<p id="total_hours">result displays here</p>
You need to
use for onclick="calculate()" take the function call, not only the function,
use getElementById, spelling matter,
declare all variables,
and finally move the output inside of the function
function calculate() {
var panel = parseInt(document.getElementById("panel").value),
panelv = 65,
panelt = panel * panelv,
derating_value = 2,
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>
getElementById is singular
declare your vars
call calculate() with brackets
assign the value inside the function
</input> is not needed
Here is a version with eventListeners since other answers already showed you how to fix YOUR version
function calculate() {
var panel = +document.getElementById("panel").value;
if (panel === "" || isNaN(panel)) panel = 0;
let panelv = 65;
let panelt = panel * panelv;
let derating_value = 2;
document.getElementById("total_hours").textContent = (panelt * derating_value);
}
window.addEventListener("load", function() {
document.getElementById("calc").addEventListener("click", calculate)
calculate(); // run at load
})
<input type="number" id="panel" placeholder="panel quantity"><br>
<button type="button" id="calc">Result</button> result displays here: <span id="total_hours"></span>
First, you should call method calculate.
<button type="button" onclick="calculate()">Result</button>
Then, add this line document.getElementsById("total_hours").innerHTML = total_hours_standby; inside calculate function.
Alos, typo error: document.getElementById instead of document.getElementsById
There are couple of issues here:
Most you could have found out if you had looked into console logs.
For starter the function is called getElementById not getElementsById, because there is supposed to be only one element with unique id, so plural does not make sense here.
Another one is a logic error: not updating content after clicking on button i.e when calculate gets executed.
There is also one more syntax error, which is how functions should be passed to HTML element's attribute. It needs to be functionName() instead of functionName
This is how simply fixing this code could look like:
var total_hours_standby = 0;
function calculate() {
var panel = parseInt(document.getElementById("panel").value);
panelv = 65;
panelt = panel * panelv;
derating_value = 2;
total_hours_standby = panelt * derating_value;
document.getElementById("total_hours").innerHTML = total_hours_standby;
}
document.getElementById("total_hours").innerHTML = total_hours_standby;
<input type="number" id="panel" placeholder="panel quantity"></input><br>
<button type="button" onclick="calculate()">Result</button>
<p id="total_hours">result displays here</p>
Here I give you couple of ideas for improving it.
Since you use global variable total_hours_standby it may be a good
idea to encapsulate it. So called module pattern should do the job.
New value of total_hours_standby does not seem to depend on an old
one, so I guess you mean to use it somewhere else - in order to do
so, you need to expose it with "public" getter.
If above is not the case, then you don't need total_hours_standby
variable at all and you can just directly return it or display it
without storing this value in variable.
I put code for rendering in separate function - this is because rule
of thumb for functions is that they should have single
responsibility. One functions for calculations, another for rendering
and then one function for handling user's input and click event, that
uses two previous ones. This way if for example you only want to
calculate something without rendering result, then you just, simply can :)
I also stored DOM nodes in variables, instead of calling
getElementById, it is not due to performance, how it is often
assumed, I did it only for better readability.
Constants instead of hard-coded values.
var Calculator = (function() {
const panelInput = document.getElementById("panel");
const output = document.getElementById("total_hours");
const PANEL_V = 65;
const DERATING_VALUE = 2;
const render = value => output.innerHTML = value;
const calculate = value => value * PANEL_V * DERATING_VALUE;
let total_hours_standby = 0;
return {
handleInput: function() {
total_hours_standby = calculate(panelInput.value);
render(total_hours_standby);
},
getTotalHoursStandby: () => total_hours_standby
};
})();
<input type="number" id="panel" placeholder="Panel quantity" />
<button type="button" onclick="Calculator.handleInput()">Calculate</button>
<p id="total_hours">Result displays here</p>
It is typo,
document.getElementsById
should be
document.getElementById
I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
I just want to acces a database in javascript from a form in the html file and pass it in a javascript function.
So what I realy want to do is take the value that I input in the html and use it in a function that takes some object data and do some simple math.
So the form i want to use looks like this:
<form name="mmForm">
<label for="element1">E1</label>
<input type="text" id="element1">
<label for="element2">E2</label>
<input type="text" id="element2">
<input type="button" value="Calculate" onclick="procesForm_mm()">
<div id="resultfield_mm">Result:</div>
</form>
And here is the javascript data i want to acces:
var Fe = new Object();
Fe.denumire = "Fier";
Fe.A = 56;
Fe.Z = 26;
Fe.grupa = VIIIB;
Fe.perioada = 4;
What I want to do is to acces the Fe.A = 56; from the Fe object while I have the inpun of "Fe" in the html file and then pass it in this function that seems to not work:
function procesForm_mm() {
var e1 = document.mmForm.element1.value;
var e2 = document.mmForm.element2.value;
result_mm = e1.A + e2.A;
document.getElementById("resultfield_mm").innerHTML = result_mm;
}
I look for some methods to do this trick and help me get on my tracks my first project as a web developer :) so anyone who will help me i will be verry greatefull.
result_mm = e1.A + e2.A;
That part will give you a error since a value does not have properties, what you have to do is this:
function procesForm_mm() {
var e1 = document.mmForm.element1.value;
var e2 = document.mmForm.element2.value;
result_mm = parseInt(e1) + parseInt(e2);
document.getElementById("resultfield_mm").innerHTML += result_mm;
}
Link http://jsbin.com/ifeluf/1/edit
hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.
I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>