I have to do a web page for school that converts temperature between celsius and fahrenheit.
I tried to make it with 2 input boxes that change value based on the value of the other input box, when I write something on one of the input boxes for the first time it works, but then even though on the code the value changes, on the page it doesn't appear.
I am new to javascript and html in general and I don't know what I'm doing wrong.
This is the code:
function cambiagradi(x,y) {
if (document.getElementById(x).value == "Centigradi") {
document.getElementById(y).value = "Fahrenheit";
}
else {
document.getElementById(y).value = "Centigradi";
}
}
function Conversione(from,to,gradi) {
var x = document.getElementById(from).value;
if (document.getElementById(gradi).value == "Centigradi") {
document.getElementById(to).setAttribute("value", (x-32)*5/9);
}
else {
document.getElementById(to).setAttribute("value", (x*9/5)+32);
}
}
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-color: #008080;">
<h1 style="text-align:center">Convertitore Temperatura</h1>
<div class="container" style="display:flex; justify-content: center">
<div style=" padding: 1%; ">
<p>
<input type="text" id="box1" oninput="Conversione('box1','box2','Gradi2')">
</p>
<p style="margin-left:10%">
<label for="Gradi1">Gradi</label>
<select id="Gradi1" onchange="cambiagradi('Gradi1','Gradi2')">
<option value="Centigradi">Centigradi</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</p>
</div>
<div style=" padding: 1%; ">=</div>
<div style=" padding: 1%; ">
<p>
<input type="text" id="box2" oninput="Conversione('box2','box1','Gradi1')">
</p>
<p style="margin-left:10%">
<label for="Gradi2">Gradi</label>
<select id="Gradi2" onchange="cambiagradi('Gradi2','Gradi1')">
<option value="Fahrenheit">Fahrenheit</option>
<option value="Centigradi">Centigradi</option>
</select>
</p>
</div>
</div>
</body>
</html>
Thanks in advance!
You should just set the value of the element and all would work as expected.
The explanation you can find here.
function Conversione(from, to, gradi) {
const x = document.getElementById(from).value;
if (document.getElementById(gradi).value == "Centigradi") {
document.getElementById(to).value = ((x - 32) * 5) / 9;
} else {
document.getElementById(to).value = (x * 9) / 5 + 32;
}
}
Some explanations within the code. Tell me if you need more. It looks more complicated but it avoids inline JavaScript which is good :)
// Define your elements as variables first as you're going to use them multiple times :
const gradi1 = document.getElementById("Gradi1");
const gradi2 = document.getElementById("Gradi2");
const box1 = document.getElementById("box1");
const box2 = document.getElementById("box2");
// Now, always use gradi1, gradi2, box1 and box2 instead of document.getElementById ....
// Then, avoid INLINE JavaScript ! (onchange="")
// We're gonna add 'event listener' to your elements
gradi1.addEventListener("change", function(){
cambiagradi(this); // 'this' means you'll know which element triggered the event when calling the function
}, false);
gradi2.addEventListener("change", function(){
cambiagradi(this);
}, false);
box1.addEventListener("input", function(){
Conversione(this)
}, false);
box2.addEventListener("input", function(){
Conversione(this)
}, false);
// You passed 'this' previously, so its back here with the name you want (ex: ancora_this)
function cambiagradi(ancora_this) {
if (ancora_this.id == "Gradi1") {
if (ancora_this.selectedIndex == 0) { // 'selectedIndex' means selected option position in the dropdown menu (begins at 0)
gradi2.selectedIndex = 1;
} else {
gradi2.selectedIndex = 0;
}
} else {
if (ancora_this.selectedIndex == 1) {
gradi1.selectedIndex = 0;
} else {
gradi1.selectedIndex = 1;
}
}
}
function Conversione(ancora_this) {
var target, conv, unit;
if (ancora_this.id == "box1") {
target = box2;
unit = gradi1;
} else {
target = box1;
unit = gradi2;
}
if (unit.selectedIndex == 0) {
conv = (Number(ancora_this.value) * 9/5) + 32;
} else {
conv = (Number(ancora_this.value) - 32)*5/9;
}
target.value = conv;
}
body {
background-color: #008080
}
h1 {
text-align: center
}
.container {
display: flex;
justify-content: center
}
.container div {
padding: 1%;
}
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Convertitore Temperatura</h1>
<div class="container">
<div>
<p>
<!-- type="number" is better because it only allows numbers -->
<input type="number" id="box1">
</p>
<p style="margin-left:10%">
<label for="Gradi1">Gradi</label>
<select id="Gradi1">
<option value="Centigradi" selected>Centigradi</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</p>
</div>
<div>=</div>
<div>
<p>
<input type="number" id="box2">
</p>
<p style="margin-left:10%">
<label for="Gradi2">Gradi</label>
<select id="Gradi2">
<!-- I switched the order to have the same 'index' on both SELECT menus
Also, I added 'selected' to have a default selected unit at start -->
<option value="Centigradi">Centigradi</option>
<option value="Fahrenheit" selected>Fahrenheit</option>
</select>
</p>
</div>
</div>
</body>
</html>
Related
I have coded and used for loop but only works if I use multiple Input text.
I want to achieve:
Every time I input number on one Input text and hit the buttons "add" or "deduct, I want the total below will keep updating while adding or deducting.
let total = 0;
for(var i=0; i<priceTrim.length; i++){
if(parseInt(priceTrim[i].value))
total += parseInt(priceTrim[i].value);
}
document.getElementById('total').value = total;
Please see the screenshot
What I understand, that you want to enter the name and price of item and then by add or deduct button, perform add or subtract operation. Plus you also want to manage the Total Value.
I create a program through your screenshot. Code is written below.
// Selecting the Elements from Html
Item_Name = document.getElementById("Item_Name");
var Price = document.getElementById("Price");
var Add = document.getElementById("Add");
var Deduct = document.getElementById("Deduct");
var Name_Here = document.getElementById("name_here");
var Price_Here = document.getElementById("price_here");
var Total = document.getElementById("Total");
var Total_Value = 0;
// Get and Set the values
Add.onclick = function(){
Name_Here.innerText = Item_Name.value;
Price_Here.innerText = Price.value;
Total_Value += parseInt(Price.value);
Total.innerText = Total_Value;
}
Deduct.onclick = function(){
Name_Here.innerText = Item_Name.value;
Price_Here.innerText = Price.value;
Total_Value -= parseInt(Price.value);
Total.innerText = Total_Value;
}
.flex_container{
display: flex;
justify-content: center;
}
.container{
width: 300px;
min-height: 220px;
border: 1px solid black;
padding: 10px;
}
button{
margin: 12px 0px;
}
.Span_Header{
display: flex;
justify-content: space-between;
}
input{
width: 100%;
margin: 8px 0px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="flex_container">
<div class="container">
<span>Item name</span><br>
<input type="text" name="item_name" id="Item_Name" placeholder="Item name"><br>
<span>Price</span><br>
<input type="number" name="price" id="Price" placeholder="Price"><br>
<button id="Add">Add</button>
<button id="Deduct">Deduct</button>
<div class="Span_Header">
<span>Item name</span>
<span>Price</span>
</div>
<hr>
<div class="Span_Header">
<span id="name_here">Name Here</span>
<span id="price_here">Price Here</span>
</div>
<hr>
<div class="Total_div">
<span>Total: </span>
<span id="Total"></span>
</div>
</div>
</div>
</body>
</html>
Please include all of your code if you would like an answer. What is priceTrim?
Are you trying to loop through a number of textbox values? If so you will have to use the querySelectorAll domElement method to loop as it returns an array type of all the text boxes , then you can specify what it is you want to do with that information in the function.
Also your if statement syntax is all wrong. You have no code block for code to perform if your testing condition returns true.
Please put in all the code and try ans explain what exactly it is you are trying to achieve? I feel like you’ve given half a story!
I'm currently making a program for my players in an RPG to be able to select their character skills from drop-down menus which will 1. Display the title of the skill under the results section and also in the Selected Advantages section(top right). 2. Display the description of the skill under its title.
It is working mostly as intended except for a bug I have discovered. I can select the desired advantage and it will appear as expected. It will also remove the selection when I click on the delete button under the Selected Advantages section at the top right of the page.
The problem is that if I reselect the same advantage it will display the advantage description twice at the bottom of the page, if I do the same again it will display three times, and so on.
When I delete a selection the container is removed but when they are selected again the subsequent descriptions are also contained in a single container instead of creating a new one.
Here is my code so far.
Note: I have only included the object for Absolute Direction but have tested with others and get the same duplication result.
const createDivElement = document.createElement('div');
//Creates containers for the selected advantage descriptions.
function createContainer(advantageName) {
const placeAdvantageDescription = document.getElementById('place-text');
placeAdvantageDescription.appendChild(createDivElement);
createDivElement.setAttribute("id", `container-${advantageName}`);
}
//Creates and adds the text for the selected advantages title, points and description.
//should I make this three seperate functions???
function addAdvantageText(advantageObject) {
const createTitleElement = document.createElement('p');
const createPointsElement = document.createElement('p');
const createDescriptionElement = document.createElement('p');
//creates Title
createDivElement.append(createTitleElement);
createTitleElement.classList.add("title");
createTitleElement.innerText = advantageObject.title;
//creates points
createDivElement.append(createPointsElement);
createPointsElement.classList.add("points");
createPointsElement.innerText = `${advantageObject.points}.`;
//creates description
createDivElement.append(createDescriptionElement);
createDescriptionElement.classList.add("description-text");
createDescriptionElement.innerHTML = advantageObject.description;
}
//creates sub catagories for selected advantage and adds the extra text if applicable.
function addSubCategories(advantageObject) {
if (advantageObject.subCategory1) {
let createSubCategory1 = document.createElement('p');
createDivElement.append(createSubCategory1);
createSubCategory1.innerHTML = `<strong>${advantageObject.subCategory1.name}:</strong> ${advantageObject.subCategory1.text}<br><strong><em>${advantageObject.subCategory1.sub1Points}</em></strong>.`;
}
if (advantageObject.subCategory2) {
let createSubCategory2 = document.createElement('p');
createDivElement.append(createSubCategory2);
createSubCategory2.innerHTML = `<strong>${advantageObject.subCategory2.name}:</strong> ${advantageObject.subCategory2.text}<br><strong><em>${advantageObject.subCategory2.sub2Points}</em></strong>.`;
}
if (advantageObject.subCategory3) {
let createSubCategory3 = document.createElement('p');
createDivElement.append(createSubCategory3);
createSubCategory3.innerHTML = `<strong>${advantageObject.subCategory3.name}:</strong> ${advantageObject.subCategory3.text}<br><strong><em>${advantageObject.subCategory3.sub3Points}</em></strong>.`;
}
if (advantageObject.subCategory4) {
let createSubCategory4 = document.createElement('p');
createDivElement.append(createSubCategory4);
createSubCategory4.innerHTML = `<strong>${advantageObject.subCategory4.name}:</strong> ${advantageObject.subCategory4.text}<br><strong><em>${advantageObject.subCategory4.sub4Points}</em></strong>.`;
}
if (advantageObject.extraText) {
let createExtraText = document.createElement('p');
createDivElement.appendChild(createExtraText);
createExtraText.innerHTML = advantageObject.extraText;
}
}
//adds name of chosen advantages in Selected Advantages column and a delete button for each.
function addToSelectedColumn(advantageName) {
const hr = document.createElement('hr');
const button = document.createElement('button');
const createSelectedAdvantageDiv = document.createElement('div');
const placeSelectedText = document.getElementById('selected-items');
placeSelectedText.appendChild(createSelectedAdvantageDiv);
createSelectedAdvantageDiv.append(advantageName.toUpperCase());
createSelectedAdvantageDiv.setAttribute("id", `selected-items-container-${advantageName}`);
createSelectedAdvantageDiv.append(button);
button.setAttribute("id", `delete-${advantageName}`);
createSelectedAdvantageDiv.append(hr);
}
function removeAdvantageText(removeThis) {
let advantageDescriptionToRemove = document.getElementById(`container-${removeThis}`);
let selectedAdvantageToRemove = document.getElementById(`selected-items-container-${removeThis}`);
advantageDescriptionToRemove.remove();
selectedAdvantageToRemove.remove();
}
function removeAdvantage(advantageToDelete) {
document.getElementById(`delete-${advantageToDelete}`).addEventListener("click", function() {
removeAdvantageText(advantageToDelete);
})
};
function addAdvantage(advantageInString, advantageObjectName) {
createContainer(advantageInString);
addToSelectedColumn(advantageInString);
addAdvantageText(advantageObjectName);
addSubCategories(advantageObjectName);
}
//Event listeners for when users select advantage. They will check for matching selection then call addAdvantage() with arguments.
//AAAAAAAAAAAAAAAA
document.getElementById("submit-advantage-a").addEventListener("click", function(e) {
e.preventDefault();
const userAdvantageA = document.getElementById('user-advantages-a').value;
if (userAdvantageA === 'absolute direction') {
addAdvantage('absolute direction', absoluteDirection);
removeAdvantage('absolute direction');
} else if (userAdvantageA === 'absolute timing') {
addAdvantage('absolute timing', absoluteTiming);
removeAdvantage('absolute timing');
} else if (userAdvantageA === 'acute senses') {
addAdvantage('acute senses', acuteSenses);
removeAdvantage('acute senses');
}
});
let absoluteDirection = {
title: "Absolute Direction",
points: "5 or 10 points",
description: "You have an excellent sense of direction.This ability comes in two levels:",
subCategory1: {
name: "Absolute Direction",
text: "You always know which way is north, and you can always retrace a path you have followed within the past month, no matter how faint or confusing. This ability does not work in environments such as interstellar space or the limbo of the astral plane, but it does work underground, underwater, and on other planets. This gives +3 to Body Sense and Navigation (Air, Land, or Sea).<br> (Note: The navigational sense that guides migratory creatures to their destination is too crude to qualify; treat it as a 0-point feature.)",
sub1Points: "5 points"
},
subCategory2: {
name: "3D Spatial Sense",
text: "As above, but works in three dimensions. This ability is useful in deep space – although it does not help you if you travel across dimensions. You get the skill bonuses to Piloting and +2 to Aerobatics, Free Fall, and Navigation (Hyperspace or Space).",
sub2Points: "10 points"
}
}
.container {
border-bottom: solid 2px black;
padding: 1rem 2rem;
}
.title {
font-size: 1.5rem;
font-weight: bolder;
text-align: center;
}
.points {
font-weight: bold;
}
#selected-items-container {
float: right;
background-color: gray;
color: white;
text-align: center;
width: 20rem;
margin-right: 4rem;
}
.forms {
margin-left: 2rem;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/style.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script type="text/javascript" src="/script.js" async></script>
<title>GCRC</title>
</head>
<body>
<a id="home-nav" href="*">Home</a>
<div class="make-choice">
<div id="selected-items-container"><strong>SELECTED ADVANTAGES</strong>
<hr>
<div id="selected-items"></div>
</div>
<div class="forms">
<h1>Select your characters advantages</h1>
<p>A.</p>
<form method="GET">
<select name="user-advantages-a" id="user-advantages-a">
<option value="absolute direction">Absolute Direction</option>
<option value="absolute timing">Absolute Timing</option>
<option value="acute senses">Acute Senses</option>
</select>
<input id="submit-advantage-a" type="submit" />
</form>
<p>B.</p>
<form method="GET">
<select name="user-advantages-b" id="user-advantages-b">
<option value="binding">Binding</option>
<option value="blessed">Blessed</option>
<option value="brachiator">Brachiator</option>
</select>
<input id="submit-advantage-b" type="submit" />
</form>
<p>C.</p>
<form method="GET">
<select name="user-advantages-c" id="user-advantages-c">
<option value="catfall">Catfall</option>
<option value="chameleon">Chameleon</option>
<option value="channeling">Channeling</option>
</select>
<input id="submit-advantage-c" type="submit" />
</form>
<p>D.</p>
<form method="GET">
<select name="user-advantages-d" id="user-advantages-d">
<option value="damage resistance">Damage Resistance</option>
<option value="danger sense">Danger Sense</option>
<option value="daredevil">Daredevil</option>
</select>
<input id="submit-advantage-d" type="submit" />
</form>
</div>
</div>
<hr>
<div class="display-choice">
<p>Advantages</p>
<div class="advantages">
<div id="place-text"></div>
</div>
</div>
</body>
</html>
Can someone tell me everything wrong with my code?
const PI = 3.14;
function povrsina(r) {
if (!null) {
return (r * r) * PI;
}
}
function prikazivanje(event) {
event.preventDefault();
var poluP = document.getElementById("broj");
var poluP2 = poluP.value;
var r = parseFloat(poluP2);
var povrsina = povrsina(r);
var rezultat = document.getElementById("rezultat");
rezultat.innerHTML = povrsina;
}
var dugme = document.getElementById("izracunaj");
dugme.addEventListener("click", prikazivanje);
<!DOCTYPE html>
<html>
<head>
<title>Povrsina kruga</title>
<meta charset="UTF-8">
</head>
<body style="background-color: #DDDDDD">
<header>
<div style="background-color: silver; text-align: center">
<h1>Povrsina kruga</h1>
</div>
</header>
<section>
<form style="text-align: center">
<label for="broj">Unesi poluprecnik</label>
<input type="text" id="broj" />
<button id="izracunaj">Izracunaj</button>
</form>
<h1 style="text-align: center">
Resenje: <span id="rezultat"></span>
</h1>
</section>
</body>
</html>
When the button is clicked, if the input is null I don't want anything to happen, but if it has a number I want the answer to be right next to "Resenje: "
var povrsina = povrsina(r);
In line 54, name your variable something different. The error is being created because your variable name is being used as a function as well.
if(!null) {
return (r * r) * PI;
}
You should also change your if statement to something like if(r != undefined){...}.
I need help sorting this out. Everything seems to work fine until it gets to receive the results of request, where someting goes wrong. The idea of the project is a Web App, where user gets 2 fields for name and date of birth. After filling them the information is verified by checking in the spreadsheet with relevant information. If everything is okay, the program next obtains appropriate id with getSheetId(), generates <iframe> code for access and should be returning it with HtmlService. However, something makes it return undefined.
Code.gs
function doGet() {
Logger.log("Login is loading")
return HtmlService
.createTemplateFromFile('index')
.evaluate()
//.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function evaluate(name, date) {
var t = SpreadsheetApp.openById('1nQxfaQcNdM6S1roJs6gxTaZPtM5gOublch5jVKDhkho')
.getSheetByName('key');
Logger.log(t.getSheetId());
Logger.log(name);
Logger.log(date);
var v = t.getRange("B2:D200");
var i = 0;
for (i = 1; i < 200; i++) {
if (v.getCell(i, 2).getValue() == name) {
Logger.log(v.getCell(i, 2).getValue());
Logger.log(name & " = the name");
Logger.log(new Date(v.getCell(i,3).getValue()).getTime());
var pdate = date.split(".");
Logger.log(new Date(pdate[2],pdate[1],pdate[0]).getTime());
var t = v.getCell(i,3).getValue();
Logger.log(pdate);
Logger.log(t.getFullYear());
Logger.log(t.getMonth());
Logger.log(t.getDate());
if (new Date(t.getFullYear(),t.getMonth()+1,t.getDate()).getTime() == new Date(pdate[2],pdate[1],pdate[0]).getTime()) {
Logger.log("match found");
include(v.getCell(i,1).getValue());
break;
} else {
Logger.log("Bad date");
return "<h2>Wrong Input. 404.</h2>";}
}
}
if (i >= 199) {
Logger.log("Bad name");
return "<h2>Wrong Input. 404.</h2>";
}
}
var hhtml = "";
function include(name) {
var html = '<iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vTeFjXOSsBRAKjbFLUSBGZOXtmjZO_4RtxxrQtXbk9sxZkF5Kdjs9OIs0tSQwekjYbOTn7JJ-_iCdeD/pubhtml?gid='
var t = SpreadsheetApp.openById('1nQxfaQcNdM6S1roJs6gxTaZPtM5gOublch5jVKDhkho').getSheetByName(name);
if (t == null) {
Logger.log("Page not found");
return "<h1>Wrong Input. 404.</h1>"
} else {
html += t.getSheetId();
}
Logger.log(name);
html += '&single=true&widget=true&headers=false" width="80%" height="600"></iframe>'
html += '<br><br><br><h3>Рейтинг групи</h3><iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vRF1MobEoKdxvO_SopGTvl-WzqEQ3nQXd6Jo_a7RTAg09yluO32AClwd4krWnVHXGQllPPwOsDeYYzN/pubhtml?gid=2096708929&single=true&widget=true&headers=false" width="80%" height="600"></iframe>'
Logger.log(html);
hhtml = HtmlService.createHtmlOutput(html).getContent();
return HtmlService.createHtmlOutput(html).getContent();
}
function getHtmlCode() {
return hhtml;
}
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<div id="mainForm">
<h2> Будь-ласка введіть своє прізвище українською мовою та дату народження у форматі день.місяць.рік (наприклад: 22.06.2018) </h2>
<form>
<div>
<div class="inline form-group">
<label for="name">Прізвище</label>
<input type="text" id="nameInput" style="width: 150px;">
</div>
<div class="inline form-group">
<label for="date">Дата Народження</label>
<input type="text" id="dateInput" style="width: 150px;">
</div>
</div>
<button class="action" type="button" id="submitButton">Submit</button>
</form>
</div>
<style>
.hidden {
display:none;
}
.form-group {
margin: 2px 0px;
}
#submitButton {
margin: 4px 0px;
}
body {
margin-left: 50px;
}
</style>
<script>
$(function(){
console.log('startup')
$('#submitButton').on('click', function(){
console.log("data get");
function respondent(value)
{
$('#mainForm').toggleClass('hidden');
console.log("script is success");
console.log(value);
document.getElementById('Response').innerHTML = value
}
google.script.run.withSuccessHandler(respondent).evaluate(document.getElementById('nameInput').value, document.getElementById('dateInput').value);
})
})
</script>
<div id="Response">
<h2>Waiting for data...</h2>
</div>
</body>
</html>
After cleaning up your code formatting, it looks like you're only returning a value from evaluate() during the Wrong Input error conditions. Nothing is returned otherwise.
Perhaps you meant to add a line like this at the end of evaluate():
return include(name);
Also, the hhtml global variable and getHtmlCode() functions aren't useful in the context of Apps Script. Each execution is in a separate instance with no state being carried over. Which mean getHtmlCode() will always return an empty string.
I have two methods for changing a bpm, both work basically the same way, they just take in input two separate ways. One of the function works, and the other one semi-works.
If you select method 1, and then chose 3 beats, it will switch immediately back to 4 beats. However, if you use method 2 and select 3 beats, it will stay on 3 beats.
If someone could explain this behavior, that'd be awesome!
/*
** Augie Luebbers & Toni Rigolosi
** Group 15
*/
//Take the button in our html and store it as a variable.
var runButton = document.getElementById('run-button');
//Create an event listener for the aforementioned button.
runButton.addEventListener('click', doWork, false);
/*
** For some reason when we created this second event
** beacuse without it, it was returning null value
** because it executed before the DOM fully loaded.
** More info: http://goo.gl/uUROPz , http://goo.gl/0Z1HdJ <-- Stack Overflow links
*/
window.onload=function()
{
/*
** After investing about 4 hours into the extra credit we realised
** that the method used to change between beats 3 and 4 was specific
** originally we had used a method of finding the value of an input field with the type number
** as we had so much time devoted, we didn't want to straight out remove it
** so we incorporated both and a method of switching between them
*/
var changeMethodButton = document.getElementById('changemethod-button');
changeMethodButton.addEventListener('click', changeBeatMenu, false);
};
function changeBeatMenu ()
{
//Clear the selection methods
document.getElementById('selectionMain').setAttribute("class", "hidden");
document.getElementById('changebeat-button1').setAttribute("class", "hidden");
document.getElementById('beats').setAttribute("class", "hidden");
document.getElementById('changebeat-button2').setAttribute("class", "hidden");
//make a variable with the value of the first radio button.
//We only need one because there are only two options and we are using an 'if else statement'
var radio = document.getElementById("beat-method-1").checked;
if (radio)
{
//Set the selection method to visible
document.getElementById('selectionMain').setAttribute("class", "visible");
document.getElementById('changebeat-button1').setAttribute("class", "visible");
//create an event for the new button for the selection method
var changeBeatButton1 = document.getElementById('changebeat-button1');
changeBeatButton1.addEventListener('click', changeBeat1, false);
} else {
//set the number method to visible
document.getElementById('beats').setAttribute("class", "visible");
document.getElementById('changebeat-button2').setAttribute("class", "visible");
//create an event for the new button for the number method
var changeBeatButton2 = document.getElementById('changebeat-button2');
changeBeatButton2.addEventListener('click', changeBeat2, false);
}
}
function changeBeat1 ()
{
//creates an object holding the selection input field
var dropDown = document.getElementById("selectionMain");
//creates a variable with the selected item in the field
var dropDownValue = dropDown.options[dropDown.selectedIndex].value;
//as we are changing between 3 and 4, we test to see if it equal 3
if (dropDownValue == 3)
{
//if it does, make the fourth element hidden
document.getElementById('beat-4').setAttribute("class", "hidden");
} else {
//but if it's not 3, it's 4 so...
//we put the fourth element back to it's default state which also happens to be visible
document.getElementById('beat-4').setAttribute("class", "beat inactive");
}
}
//Does the same thing as the above function..
//but it uses a number input field instead of a selection input field
function changeBeat2 ()
{
var beats = document.getElementById('beats');
beatsInteger = beats.value;
if (beatsInteger == 3)
{
document.getElementById('beat-4').setAttribute("class", "hidden");
} else {
document.getElementById('beat-4').setAttribute("class", "beat inactive");
}
}
//Create a timer based on input
function doWork ()
{
var timer = calcMs();
setInterval(function(){ oscillate(); }, timer);
}
//Calculate beats per millisecond
function calcMs ()
{
var bpm = document.getElementById('bpm');
var Ms = (60000/bpm.value);
return Ms;
}
//Oscillate the divs between 1 and 4.
var buffer = 0;
var beatsInteger = 4;
function oscillate ()
{
var i;
for (i = 1; i <= beatsInteger; i++)
{
document.getElementById('beat-' + i).setAttribute("class", "beat inactive");
}
var myBeat = buffer % beatsInteger + 1;
document.getElementById('beat-' + myBeat).setAttribute("class", "beat active");
buffer++;
}
/*
** Augie Luebbers & Toni Rigolosi
** Group 15
*/
#header {
margin-bottom: 20px;
}
.beat {
width: 100px;
height: 50px;
margin-bottom: 20px;
padding: 10px;
text-align: center;
}
.inactive {
background-color: #d3d3d3;
border: 1px solid #000000;
}
.active {
background-color: #FFD1DC;;
border : 3px solid #FF0000;
}
.hidden {
visibility: hidden;
display: none;
}
.visible {
visibility: visible;
display: inline;
}
<!--
--
-- Augie Luebbers & Toni Rigolosi
-- Group 15
--
-->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lab 3: Metronome</title>
<meta name="description" content="Project 3">
<link rel="stylesheet" href="css/metro.css">
</head>
<body>
<section id="header">
<h3>Metronome</h3>
<label for="bpm">BPM</label>
<input type="text" name="bpm" id="bpm" placeholder="enter bpm"/>
<button name="run-button" id="run-button">Start</button>
<br>
<label for="selection">SELECTION</label>
<input type="radio" name="beat-method" value="method-1" id="beat-method-1"> Method 1
<input type="radio" name="beat-method" value="method-2" id="beat-method-2"> Method 2
<button name="changemethod-button" id="changemethod-button">Submit</button>
<br>
<select id="selectionMain" class="hidden">
<option value="3">3</option>
<option value="4">4</option>
</select>
<button name="changebeat-button1" id="changebeat-button1" class="hidden">Change Beat</button>
<!-- or -->
<label for="beats" class="hidden">BEATS</label>
<input type="number" name="beat" id="beats" min="3" max="4" step="1" value="4" class="hidden">
<button name="changebeat-button2" id="changebeat-button2" class="hidden">Change Beat</button>
</section>
<div id="beat-1" class="beat inactive">One</div>
<div id="beat-2" class="beat inactive">Two</div>
<div id="beat-3" class="beat inactive">Three</div>
<div id="beat-4" class="beat inactive">Four</div>
<script src="js/app.js"></script>
</body>
</html>