i am new to html and js. I have created a form with the following script. i have an event handler for calculateTime. I cant seem to get the form to calculate. If you guys could point me in the right direction that would be great. Thanks
<script>
function getWaterSystem() {
var waterSystem;
var selectedSystem = 0;
for (var i = 1; i <= 4; i++) {
waterSystem = document.getElementById("system + i");
if (waterSystem.checked == true) {
waterSystem = waterSystem(i).value;
}
}
return waterSystem;
}
function largePlant() {
var checkbox;
checkbox = document.getElementById("large");
if (checkbox(i).checked) {
checkbox = 1.5;
}
else {
checkbox = "";
}
return checkbox;
}
function getSoilType() {
var soilType;
var selectedSoil = 0;
for (var i = 1; i <= 3; i++) {
soilType = document.getElementById("soil + i");
if (soilType[i].checked) {
soilType = soilType[i].value;
}
}
return soilType;
}
function calculateTime() {
var waterTime = getWaterSystem() * getSoilType() * largePlant();
alert("The recommended watering time is " + waterTime);
}
</script>
I made some adjustment, just check it out, it's quite simple:
document.getElementById("check1").checked
<script>
function getWaterSystem() {
var waterSystem=0;
var selectedSystem = 0;
for (var i = 1; i <= 4; i++) {
if (document.getElementById("system" + i).checked) {
reutrn waterSystem = document.getElementById("system" + i).value;
}
}
return waterSystem;
}
function largePlant() {
var checkbox=0;
if (document.getElementById("large").checked) {
checkbox = 1.5;
}
else {
checkbox = 0;
}
return checkbox;
}
function getSoilType() {
var soilType=0;
var selectedSoil = 0;
for (var i = 1; i <= 3; i++) {
soilType = document.getElementById("soil" + i);
if (document.getElementById("soil" + i). checked) {
soilType = document.getElementById("soil" + i).value;
return soilType;
}
}
return soilType;
}
function calculateTime() {
var waterTime = getWaterSystem() * getSoilType() * largePlant();
alert("The recommended watering time is " + waterTime);
}
</script>
Could it have something to do with these two lines:
waterSystem = document.getElementById("system + i");
soilType = document.getElementById("soil + i");
If you want to target the id of #systemX or #soilX where X is being a number from you i var. You should write it like this:
waterSystem = document.getElementById("system" + i);
soilType = document.getElementById("soil" + i);
Related
<script type="text/javascript">
function display(id) {
$("html *").attr('id')
var sub=id.substring(0,1);
if(sub) {
document.getElementById(id).style.visibility="visible";
} else {
document.getElementById(id).style.visibility="hidden";
}
}
</script>
Using jQuery, select elements that has attribute id and iterate it using each method. Example:
$('[id]').each(function() {
console.log(this.getAttribute('id'));
});
function check(id)
{
var s = id.substring(0,1);
var tableCells = document.getElementsByTagName('td'),
cellCount = tableCells.length,i;
for (i = 0; i < cellCount; i += 1) {
var sub = tableCells.substring(0,1);
if(strcmp(s,sub)) {
document.getElementById(id).style.visibility="visible";
}
else {
document.getElementById(id).style.visibility="hidden";
}
}
}
function check(id)
{
var sub=id.substring(0,1);
var tableCells = document.getElementsByTagName('td'),
cellCount = tableCells.length,i;
for (i = 0; i < cellCount; i += 1) {
var sub1=tableCells[i].id;
var sub2=sub1.substring(0,1);
if(sub==sub2) {
document.getElementById(id).style.visibility="visible"; }
else {
document.getElementById(id).style.visibility="hidden"; }
}
}
I am new to JavaScript. I would like to add to add two buttons for my visitors to control font size. I would like to include two tags - 'p' and 'blockquote". Can you please help me edit this code in order to include both?
var min = 8;
var max = 18;
function increaseFontSize() {
var p = document.getElementsByTagName('p');
for (i = 0; i < p.length; i++) {
if (p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += 1;
}
p[i].style.fontSize = s + "px"
}
}
function decreaseFontSize() {
var p = document.getElementsByTagName('p');
for (i = 0; i < p.length; i++) {
if (p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != min) {
s -= 1;
}
p[i].style.fontSize = s + "px"
}
}
Thank you.
Here's a working version:
http://jsfiddle.net/ny4p7pg9/
I took the liberty of refactoring a bit the functions to make the code more parameterized.
function changeFontSize(delta) {
var tags = document.querySelectorAll('p,blockquote');
for (i = 0; i < tags.length; i++) {
if (tags[i].style.fontSize) {
var s = parseInt(tags[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += delta;
}
tags[i].style.fontSize = s + "px"
}
}
function increaseFontSize() {
changeFontSize(1);
}
function decreaseFontSize() {
changeFontSize(-1);
}
Instead of using:
p = document.getElementsByTagName('p');
you could, instead use:
elems = document.querySelectorAll('p, blockquote');
(the variable name is irrelevant, and was changed only because the elements are no longer exclusively <p> elements):
function increaseFontSize() {
var elems = document.querySelectorAll('p, blockquote');
for (i = 0; i < elems.length; i++) {
if (elems[i].style.fontSize) {
var s = parseInt(elems[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += 1;
}
elems[i].style.fontSize = s + "px"
}
}
var min = 8;
var max = 18;
function increaseFontSize() {
var elems = document.querySelectorAll('p, blockquote');
for (i = 0; i < elems.length; i++) {
if (elems[i].style.fontSize) {
var s = parseInt(elems[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += 1;
}
elems[i].style.fontSize = s + "px"
}
}
function decreaseFontSize() {
var elems = document.querySelectorAll('p, blockquote');
for (i = 0; i < elems.length; i++) {
if (elems[i].style.fontSize) {
var s = parseInt(elems[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != min) {
s -= 1;
}
elems[i].style.fontSize = s + "px"
}
}
document.querySelector('#increase').addEventListener('click', increaseFontSize);
document.querySelector('#decrease').addEventListener('click', decreaseFontSize);
<button id="increase">↑A</button>
<button id="decrease">A↓</button>
<p>Some text to have its text adjusted by the buttons just up there.</p>
<blockquote>Some text in a blockquote</blockquote>
The querySelectorAll() method accepts CSS-style selectors, and returns a (non-live) NodeList, and is supported in all modern browsers, including IE from version 8 onwards.
That said, it's probably better to increase the font-size of the <body> element, otherwise font-adjustment is redundant (since other elements will still be unclear), so, instead, I'd suggest:
function increaseFontSize() {
// retrieving, and caching, the <body> element:
var body = document.body,
// finding the current computed fontSize of the <body> element, parsing it
// as a float (though parseInt() would be just as safe, really):
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
// if the currentFontSize is less than the specified max:
if (currentFontSize < max) {
// we set the fontSize of the <body> to the incremented fontSize,
// increasing the current value by 1, and concatenating with the 'px' unit:
body.style.fontSize = ++currentFontSize + 'px';
}
}
function decreaseFontSize() {
var body = document.body,
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
if (currentFontSize > min) {
body.style.fontSize = --currentFontSize + 'px';
}
}
var min = 8;
var max = 18;
function increaseFontSize() {
var body = document.body,
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
if (currentFontSize < max) {
body.style.fontSize = ++currentFontSize + 'px';
}
}
function decreaseFontSize() {
var body = document.body,
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
if (currentFontSize > min) {
body.style.fontSize = --currentFontSize + 'px';
}
}
document.querySelector('#increase').addEventListener('click', increaseFontSize);
document.querySelector('#decrease').addEventListener('click', decreaseFontSize);
<button id="increase">↑A</button>
<button id="decrease">A↓</button>
<p>Some text to have its text adjusted by the buttons just up there.</p>
<blockquote>Some text in a blockquote</blockquote>
References:
document.body.
document.querySelectorAll().
Window.getComputedStyle().
I am trying to build a webpage where you can oreder a ticket to a cinema movie.I have used an algorithm to change the cinema ticked price based on spot's id. The problem is that when I change the src of the image I get an undefined id. Why do I get that, and how to fix it?. Here is the code:
window.onload = main;
var initialPrice = 0;
var dayMultiplier = 1;
var price = 0;
function main()
{
addButtonLsn();
}
function addButtonLsn()
{
$("#setDate").click(addSeats);
}
function addSeats()
{
if($("#zi").val() === "--*--")
{
alert("Day select missing");
return;
}
if($("#movies").val() ==="--*--")
{
alert("Movie select missing");
return;
}
setInitialPrice();
setDayMutliplier();
$("#sala").empty();
$("#price").html("Pret : 0");
var myId = 1;
for(var i = 0; i < 20; i++)
{
for (var j = 0; j < 12; j++)
{
var s = document.createElement("img");
s.setAttribute("src", "liber.jpg");
s.setAttribute("id", myId);
myId ++;
s.addEventListener("click", changeSeat);
s.addEventListener("mouseover", getSeatTicket);
var d = document.getElementById("sala");
d.appendChild(s);
}
}
}
function getSeatTicket()
{
var spotPrice = initialPrice;
spotPrice = initialPrice * dayMultiplier;
var spotMultiplyer = 1;
var ct = 1;
if($(this).attr("id") < 130)
{
spotMultiplyer = 1;
ct = 3;
}
else if ($(this).attr("id") < 180)
{
spotMultiplyer = 1.1;
ct = 2;
}
else
{
spotMultiplyer = 1.2;
ct = 1;
}
spotPrice *= spotMultiplyer;
console.log($(this).attr("id"));//undefined
$(this).attr("title","Categorie: " + ct + " ,pret " + spotPrice);
return spotPrice;
}
function changeSeat()
{
if($(this).attr('src') === "liber.jpg")
{
$(this).attr('src','rezervat.jpg');
price = price + getSeatTicket();
$("#price").html("Price: " + price);
}
else
{
$(this).attr('src','liber.jpg');
price = price - getSeatTicket();
$("#price").html("Price: " + price);
}
}
function setInitialPrice()
{
if($("#movies").val() === "The Gold Rush")
{
initialPrice = 10;
return;
}
if($("#movies").val() === "The Kid")
{
initialPrice = 11;
return;
}
if($("#movies").val() === "Modern Times")
{
initialPrice = 12;
return;
}
}
function setDayMutliplier()
{
if($("#zi").val() === "Luni-Joi")
{
dayMultiplier = 1;
return;
}
if($("#zi").val() === "Vineri")
{
dayMultiplier = 1.1;
return;
}
if($("#zi").val() === "Sambata")
{
dayMultiplier = 1.2;
return;
}
if($("#zi").val() === "Duminica")
{
dayMultiplier = 1.3;
return;
}
}
The function getSeatTicket is referring to this as the current element, which works fine when the function is used as a callback for the mouseover listener, but it will not work when you are calling it as you are in changeSeat.
Perhaps you should be using .call(this) to run the function using the same scope as changeSeat;
function changeSeat()
{
if($(this).attr('src') === "liber.jpg")
{
$(this).attr('src','rezervat.jpg');
price = price + getSeatTicket.call(this);
$("#price").html("Price: " + price);
}
else
{
$(this).attr('src','liber.jpg');
price = price - getSeatTicket.call(this);
$("#price").html("Price: " + price);
}
}
After code inspection, my guess is that when you try to access the element's id within the getSeatTicket() function, you are calling a function where $(this) is not actually refering to the DOM element to which the event is attached to.
To overcome this, my recommendation would be to pass the id to the getSeatTicket() function, and getting the reference to the element inside it. Something like (conceptual):
function getSeatTicket(id){
var element = $(id);
...
}
and call it like:
...
$(this).attr('src','rezervat.jpg');
price = price + getSeatTicket($(this).attr("id"));
...
Best.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Html
<html>
<head>
<script type="text/javascript" src="/test.js"></script>
<script type="text/javascript">
start();
</script>
</head>
<body>
</body>
</html>
Java script
var points = 1;
var points1;
var DELAY = 30;
var SPEED = 5;
var MAX_DY = 12;
var OBSTACLE_WIDTH = 30;
var OBSTACLE_HEIGHT = 100;
var TERRAIN_WIDTH = 10;
var MIN_TERRAIN_HEIGHT = 20;
var MAX_TERRAIN_HEIGHT = 50;
var POINTS_PER_ROUND = 5;
var DUST_RADIUS = 3;
var DUST_BUFFER = 10;
var NUM_OBSTACLES = 3;
var copter;
var dy = 0;
var clicking = false;
var score; // text you see on the screen
var obstacles = [];
var top_terrain = [];
var bottom_terrain = [];
var dust = [];
function start(){
starta();
}
function starta() {
setup();
setTimer(game, DELAY);
mouseDownMethod(onMouseDown);
mouseUpMethod(onMouseUp);
setTimer(points2, 10)
}
function points2(){
points1 = points/100
return points1;
}
function setup() {
setBackgroundColor(Color.black);
copter = new WebImage("image.png");
copter.setSize(25, 50);
copter.setPosition(getWidth()/3, getHeight()/2);
copter.setColor(Color.blue);
add(copter);
addObstacles();
addTerrain();
score = new Text("0");
score.setColor(Color.white);
score.setPosition(10, 30);
add(score);
}
function updateScore() {
points += POINTS_PER_ROUND;
score.setText(points);
}
function game() {
updateScore();
if (hitWall()) {
lose();
return;
}
var collider = getCollider();
if (collider != null) {
if (collider != copter) {
lose();
return;
}
}
if (clicking) {
dy -= 1;
if (dy < -MAX_DY) {
dy = -MAX_DY;
}
} else {
dy += 1;
if (dy > MAX_DY) {
dy = MAX_DY;
}
}
copter.move(0, dy);
moveObstacles();
moveTerrain();
moveDust();
addDust();
}
function onMouseDown(e) {
clicking = true;
}
function onMouseUp(e) {
clicking = false;
}
function addObstacles() {
for (var i = 0; i < NUM_OBSTACLES; i++) {
var obstacle = new WebImage("image.jpg");
obstacle.setSize(50, 100);
obstacle.setColor(Color.green);
obstacle.setPosition(getWidth() + i * (getWidth()/NUM_OBSTACLES),
Randomizer.nextInt(0, getHeight() - OBSTACLE_HEIGHT));
obstacles.push(obstacle);
add(obstacle);
}
}
function moveObstacles() {
for (var i=0; i < obstacles.length; i++) {
var obstacle = obstacles[i];
obstacle.move(-points1, 0);
if(obstacle.getX() < 0) {
obstacle.setPosition(getWidth(),
Randomizer.nextInt(0, getHeight() - OBSTACLE_HEIGHT));
}
}
}
function hitWall() {
var hit_top = copter.getY() < 0;
var hit_bottom = copter.getY() + copter.getHeight() > getHeight();
return hit_top || hit_bottom;
}
function lose() {
stopTimer(game);
var text = new Text("You Lose!");
text.setColor(Color.red);
text.setPosition(getWidth()/2 - text.getWidth()/2,
getHeight()/2);
add(text);
}
function getCollider() {
var topLeft = getElementAt(copter.getX()-1, copter.getY()-1);
if (topLeft != null) {
return topLeft;
}
var topRight = getElementAt(copter.getX() + copter.getWidth() + 1,
copter.getY() - 1);
if (topRight != null) {
return topRight;
}
var bottomLeft = getElementAt(copter.getX()-1,
copter.getY() + copter.getHeight() + 1);
if (bottomLeft != null) {
return bottomLeft;
}
var bottomRight = getElementAt(copter.getX() + copter.getWidth() + 1,
copter.getY() + copter.getHeight() + 1);
if (bottomRight != null) {
return bottomRight;
}
return null;
}
function addTerrain() {
for (var i=0; i <= getWidth() / TERRAIN_WIDTH; i++) {
var height = Randomizer.nextInt(MIN_TERRAIN_HEIGHT, MAX_TERRAIN_HEIGHT);
var terrain = new Rectangle(TERRAIN_WIDTH, height);
terrain.setPosition(TERRAIN_WIDTH * i, 0);
terrain.setColor(Color.green);
top_terrain.push(terrain);
add(terrain);
height = Randomizer.nextInt(MIN_TERRAIN_HEIGHT, MAX_TERRAIN_HEIGHT);
var bottomTerrain = new Rectangle(TERRAIN_WIDTH, height);
bottomTerrain.setPosition(TERRAIN_WIDTH * i,
getHeight() - bottomTerrain.getHeight());
bottomTerrain.setColor(Color.green);
bottom_terrain.push(bottomTerrain);
add(bottomTerrain);
}
}
function moveTerrain() {
for (var i=0; i < top_terrain.length; i++) {
var obj = top_terrain[i];
obj.move(-points1, 0);
if (obj.getX() < -obj.getWidth()) {
obj.setPosition(getWidth(), 0);
}
}
for (var i=0; i < bottom_terrain.length; i++) {
var obj = bottom_terrain[i];
obj.move(-points1, 0);
if (obj.getX() < -obj.getWidth()) {
obj.setPosition(getWidth(), getHeight() - obj.getHeight());
}
}
}
function addDust() {
var d = new Circle(DUST_RADIUS);
d.setColor("#ffd700");
d.setPosition(copter.getX() - d.getWidth(),
copter.getY() + DUST_BUFFER);
dust.push(d);
add(d);
}
function moveDust() {
for (var i=0; i < dust.length; i++) {
var d = dust[i];
d.move(-points1, 0);
d.setRadius(d.getRadius() - 0.1);
if(d.getX() < 0) {
remove(d);
dust.remove(i);
i--;
}
}
}
Okay so here is my script. The script works perfectly fine on a codehs sandbox, but now that I want to set it on my own website it is not working. Could some one please help me out. Thank you.
Could some one please tell me how I would execute this code from test.js. Thank you.
You need to include the .js to your HTML page, like this:
<script type="text/javascript" src="/test.js"></script>
<script type="text/javascript">
start(); //starts your program
</script>
<html>
<body>
<script type="text/javascript">
start();
function start() {
var val = "0,1";
var n = 5;
var chars = ['a', 'b', 'c', 'd', 'e'];
gVars = chars.slice(0, n);
for (var i = 0; i < gVars.length; i++)
document.write(gVars[i] + "<br />");
var termsStr = val.split(',');
for (var i = 0; i < termsStr.length; i++)
document.write(termsStr[i] + "<br />");
var gOrigTerms = [];
var maxterm = Math.pow(2, termsStr.length) - 1;
document.write("maxterm: " + maxterm + "<br />");
for (var i = 0; i < termsStr.length; i++) {
gOrigTerms[i] = parseInt(termsStr[i]);
document.write(gOrigTerms[i] + "<br />");
if (gOrigTerms[i] > maxterm) document.write("Invalid term in term list." + "<br />");
}
gFormula = new Formula(gVars, gOrigTerms);
document.write(gFormula);
gFormula.toString();
gFormula.reduceToPrimeImplicants(); //here the breakpoint is inserted
}
function Formula(vars, terms)
{
this.vars = vars;
this.termList = [];
for (var i = 0; i < terms.length; i++) {
this.termList[i] = new Term(Dec2Bin(terms[i], vars.length));
document.write("this.termList" + this.termList[i] + "<br />");
}
this.orginalTermList = [];
document.write("this.orginalTermList" + this.orginalTermList + "<br />");
}
function Dec2Bin(dec, size) {
var bits = [];
for (var bit = 0; bit < size; bit++)
{
bits[bit] = 0;
}
var i = 0;
while (dec > 0)
{
if (dec % 2 == 0)
{
bits[i] = 0;
} else
{
bits[i] = 1;
}
i++;
dec = (dec / 2) | 0;
// Or with zero casts result to int (who knows why...)
}
bits.reverse();
return bits;
}
function Term(varVals)
{
this.varVals = varVals;
document.write("this.varVals: " + this.varVals);
}
function reduceToPrimeImplicants() //there is some problem with this function
{
this.originalTermList = this.termList.slice(0);
var numVars = this.termList[0].getNumVars();
var table = [];
for (var dontKnows = 0; dontKnows <= numVars; dontKnows++) {
table[dontKnows] = [];
for (var ones = 0; ones <= numVars; ones++) {
table[dontKnows][ones] = [];
}
table[dontKnows][numVars + 1] = [];
}
table[numVars + 1] = [];
table[numVars + 1][numVars + 1] = [];
for (var i = 0; i < this.termList.length; i++) {
var dontCares = this.termList[i].countValues(DontCare);
var ones = this.termList[i].countValues(1);
var len = table[dontCares][ones].length;
table[dontCares][ones][len] = this.termList[i];
}
for (var dontKnows = 0; dontKnows <= numVars - 1; dontKnows++) {
for (var ones = 0; ones <= numVars - 1; ones++) {
var left = table[dontKnows][ones];
var right = table[dontKnows][ones + 1];
var out = table[dontKnows + 1][ones];
for (var leftIdx = 0; leftIdx < left.length; leftIdx++) {
for (var rightIdx = 0; rightIdx < right.length; rightIdx++) {
var combined = left[leftIdx].combine(right[rightIdx]);
if (combined != null) {
if (out.indexOf(combined) < 0) {
var len = out.length;
out[len] = combined;
}
if (this.termList.indexOf(left[leftIdx]) >= 0) {
this.termList.splice(this.termList.indexOf(left[leftIdx]), 1);
}
if (this.termList.indexOf(right[rightIdx]) >= 0) {
this.termList.splice(this.termList.indexOf(right[rightIdx]), 1);
}
if (this.termList.indexOf(combined) < 0) {
var len = this.termList.length;
this.termList[len] = combined;
}
}
}
}
}
}
}
function getNumVars()
{
return this.varVals.length;
}
function countValues(value)
{
result = 0;
for (var i = 0; i < this.varVals.length; i++) {
if (this.varVals[i] == value) {
result++;
}
}
return result;
}
function combine(term)
{
var diffVarNum = -1; // The position where they differ
for (var i = 0; i < this.varVals.length; i++) {
{
if (this.varVals[i] != term.varVals[i])
if (diffVarNum == -1) {
diffVarNum = i;
} else { // They're different in at least two places return null; }
}
}
if (diffVarNum == -1)
{
// They're identical return null;
}
resultVars = this.varVals.slice(0);
resultVars[diffVarNum] = DontCare;
return new Term(resultVars);
}
</script>
</body>
</html>
In the above code, that is not complete, but which implements quine Mccluskey algorithm. There is a problem while it is debugged.
If a breakpoint is inserted at gFormula.reducetoPrimeImplicants(); the debugger does not go into that function. This is the last function called in the code until now. But, it does go to start(), which is the first function.
There is some problem in reducetoPrimeImplicants(); function because it also gives ERROR in internet explorer.
I am not able to figure out the error. If I remove reducetoPrimeImplicants(); function from the code the works fine.
Please, can somebody tell me why the debugger does not enter reducetoPrimeImplicants();.
I am using the Firebug debugger.
Thanks in advance.
The last function in your page combine() is missing a closing brace.
If you don't mind, a suggestion: Please use http://jsbeautifier.org/ or some similar tool to indent your code better.
Your For loop has two starting braces.
for (var i = 0; i < this.varVals.length; i++) {
{
So remove one. This should solve your problem.