Is it possible to sent a string variable into a JavaScript? - javascript

I am working on a function which allows the price of an order to be automatically calculated based off user inputs into a form. The users will be selecting the "Type" of service they want, and also inputting the "square foot" of an order.
Is the problem because I have attempted to set a string variable to have a intiger value?
When I press the button on the form there is nothing printed on the webpage.
<form>
<select id="type" required>
<option disabled selected value> Type of service </option>
<option value="Gardening">Gardening</option>
<option value="Decorating">Decorating</option>
<option value="Fencing">Fencing</option>
<option value="Flooring">Flooring</option>
<option value="Landscaping">Landscaping</option>
</select>
<input type="number" id="square_ft" placeholder="square_ft">
<button type="submit" onclick="calculatePrice()">Check Price</button>
</form>
<p id="price"> </p>
<script>
function calculatePrice() {
var hours = 4;
var totalPriceHour = 0;
var priceHour = 0;
var priceSquareFt = 0;
var totalSquareFt = 0;
var orderTotal = 0;
var materials = false;
var type = document.getElementById("type").value;
var square_ft = document.getElementById("square_ft").value;
if (type == Gardening) {
priceHour = 20;
priceSquareFt = 3;
} else if (type == Decorating) {
priceHour = 20;
priceSquareFt = 3;
} else if (type == Landscaping) {
priceHour = 30;
priceSquareFt = 2;
} else if (type == Flooring) {
priceHour = 20;
priceSquareFt = 2;
} else (type == Fencing) {
priceHour = 30;
priceSquareFt = 3;
}
totalPriceHour = hours * priceHour;
totalSquareFt = square_ft * priceSquareFt;
orderTotal = totalSquareFt + totalPriceHour;
document.getElementById("price").innerHTML = orderTotal;
}
</script>

the value of an input will return a string so make sure you compare your type variable to a string adding quotes to your validation... also if you put a submit button inside your form this will attempt to send a request to the server..
function calculatePrice() {
var hours = 4;
var totalPriceHour = 0;
var priceHour = 0;
var priceSquareFt = 0;
var totalSquareFt = 0;
var orderTotal = 0;
var materials = false;
var type = document.getElementById("type").value;
var square_ft = document.getElementById("square_ft").value;
if (type == 'Gardening') {
priceHour = 20;
priceSquareFt = 3;
} else if (type == 'Decorating') {
priceHour = 20;
priceSquareFt = 3;
} else if (type == 'andscaping') {
priceHour = 30;
priceSquareFt = 2;
} else if (type == 'Flooring') {
priceHour = 20;
priceSquareFt = 2;
} else if (type == 'Fencing') {
priceHour = 30;
priceSquareFt = 3;
}
totalPriceHour = hours * priceHour;
totalSquareFt = square_ft * priceSquareFt;
orderTotal = totalSquareFt + totalPriceHour;
document.getElementById("price").innerHTML = orderTotal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="type" required>
<option disabled selected value> Type of service </option>
<option value="Gardening">Gardening</option>
<option value="Decorating">Decorating</option>
<option value="Fencing">Fencing</option>
<option value="Flooring">Flooring</option>
<option value="Landscaping">Landscaping</option>
</select>
<input type="number" id="square_ft" placeholder="square_ft">
<button type="button" onclick="calculatePrice()">Check Price</button>
</form>
<p id="price"> </p>

Related

Javascript: Populate value of Text Fields with Variables based on Value of Select Menu

The HTML:
<select id="SHIELD" onchange="calcCHO();" >
<option value="610" selected >CHO-SHIELD 610</option>
<option value="608" >CHO-SHIELD 608</option>
<option value="604" >CHO-SHIELD 604</option>
</select>
<input id="FILLER" type="text" disabled value="" />
The Script:
function calcCHO(){
var f_S = "Silver";
var f_N = "Nickel";
var f_SC = "Silver/Copper";
var CHOS = document.getElementById("SHIELD").value;
var FILLER = document.getElementById("FILLER").value;
if(CHOS === "610") {
FILLER = f_S;
}
else if (CHOS === "608") {
FILLER = f_N;
}
else {
FILLER = f_SC;
}
}
This looks pretty straightforward, any idea why it does not work or produce any console errors?
Thanks!
try it like that.
function calcCHO(){
var f_S = "Silver";
var f_N = "Nickel";
var f_SC = "Silver/Copper";
var CHOS = document.getElementById("SHIELD").value;
var FILLER = document.getElementById("FILLER");
if(CHOS === "610") {
FILLER.value = f_S;
}
else if (CHOS === "608") {
FILLER.value = f_N;
}
else {
FILLER.value = f_SC;
}
}

Input value is not changed on Javascript

I make shopping Cart now with vanilla javascript, html, css.
This program is when consumer click selection tag, add new tag and change count.
To Add new Tag is already working. Change count is not work. When I clicked, selectA, selectB, selectC is changed but not working on input tag.
var selectA = 0;
var selectB = 0;
var selectC = 0;
function handleOnChange(e) {
// 선택된 데이터 가져오기
let value = e.value;
let name = e.options[e.selectedIndex].text;
let itemList = document.getElementById("addItem");
var Item = document.createElement('div');
var itemName = document.createElement('div');
var itemSumA = document.createElement('input');
var itemSumB = document.createElement('input');
var itemSumC = document.createElement('input');
itemName.innerHTML = name;
if (value === "A") {
if (selectA === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumA);
itemList.appendChild(Item);
}
itemSumA.value = selectA;
} else if (value === "B") {
console.log(selectB);
if (selectB === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumB);
itemList.appendChild(Item);
}
itemSumB.value = ++selectB;
} else {
if (selectC === 0) {
Item.appendChild(itemName);
Item.appendChild(itemSumC);
itemList.appendChild(Item);
}
itemSumC.value = ++selectC;
}
document.getElementById("Sum").innerHTML = selectA * 39800 + selectB * 49800 + selectC * 59800;
}
<li class="checked">
<button class="accordion">주문 정보</button>
<div class="panel">
<p>상품 선택</p>
<select name="tent" id="tent" onchange="handleOnChange(this)">
<option value="A">A. 스피드 원터치 팝업텐트(3~4인용)</option>
<option value="B">B. 5초 원터치 텐트(3인용) (+10,000)</option>
<option value="C">C. 5초 원터치 텐트(5인용) (+20,000)</option>
</select>
<div id="addItem"></div>
</div>
</li>
I want to know why.

How to use this true/false flag to make switching radio buttons disable other radio buttons effects

Ive tried following this:
var changed = function() {
if (document.getElementById('wolf').checked) {
wolfActive = true;
turtleActive = false;
lizardActive = false;
} else if (document.getElementById('lizard').checked) {
lizardActive = true;
wolfActive = false;
turtleActive = false;
} else if (document.getElementById('turtle').checked) {
turtleActive = true;
lizardActive = false;
wolfActive = false;
}
}
But i can't get each radiobuttons effect to be false when a different radio button is selected ( having a hard time understanding how it works)
This is my JavaScript:
var Turtle = 1;
var Turtlelv = 1;
var TurtleCexp = 0;
var TurtleMexp = 100;
var NextMaxTurtleExp = TurtleMexp;
var Turtleregen = 0.5;
var Lizard = 1;
var Lizardlv = 1;
var LizardCexp = 0;
var LizardMexp = 100;
var NextMaxLizardExp = LizardMexp;
var Wolf = 1;
var Wolflv = 1;
var WolfCexp = 0;
var WolfMexp = 100;
var NextMaxWolfExp = WolfMexp;
var Strength = 2;
var Magic = 1;
var Wolfstrength = 1
var ManaPoints = 10
function Wolfandstrength() {
if (document.getElementById("wolf-radio").checked) {
Strength = Strength + Wolfstrength
document.getElementById("Strength").innerHTML = Strength;
} else {
Strength = Strength - Wolfstrength
document.getElementById("Strength").innerHTML = Strength;
}
}
function wolfXpUp() {
if (document.getElementById("wolf-radio").checked && WolfCexp < WolfMexp)
{
setTimeout(wolfXpUp, 100)
WolfCexp = WolfCexp + 1;
document.getElementById("WolfCexp").innerHTML = WolfCexp;
}
if (WolfCexp >= WolfMexp) {
Wolflv = Wolflv + 1;
WolfCexp = 0;
Wolf = Wolf + 1;
Wolfstrength = Wolfstrength + 1;
Strength = Strength + 1;
NextMaxWolfExp= NextMaxWolfExp *1.5;
}
document.getElementById("Strength").innerHTML = Strength;
document.getElementById('WolfMexp').innerHTML = NextMaxWolfExp;
document.getElementById('Wolflv').innerHTML = Wolflv;
document.getElementById('WolfCexp').innerHTML = WolfCexp;
document.getElementById('Wolf').innerHTML = Wolf;
}
function lizardXpUp() {
if (document.getElementById("lizard-radio").checked && LizardCexp <
LizardMexp) {
setTimeout(lizardXpUp, 200)
LizardCexp = LizardCexp + 1;
document.getElementById("LizardCexp").innerHTML = LizardCexp;
}
if (LizardCexp >= LizardMexp) {
Lizardlv = Lizardlv + 1;
LizardCexp = 0;
Lizard = Lizard + 1;
Lizardmagic = Lizardmagic + 1;
Magic = Magic + 1;
NextMaxLizardExp= NextMaxLizardExp *1.5;
}
document.getElementById("Magic").innerHTML = Magic;
document.getElementById('LizardMexp').innerHTML =
NextMaxLizardExp;
document.getElementById('Lizardlv').innerHTML = Lizardlv;
document.getElementById('LizardCexp').innerHTML = LizardCexp;
document.getElementById('Lizard').innerHTML = Lizard;
}
function turtleXpUp() {
if (document.getElementById("turtle-radio").checked && Turtleexp <
TurtleMexp) {
setTimeout(turtleXpUp, 200)
TurtleCexp = TurtleCexp + 1;
document.getElementById("TurtleCexp").innerHTML = TurtleCexp;
}
if (TurtleCexp >= TurtleMexp) {
Turtlelv = Turtlelv + 1;
TurtleCexp = 0;
Turtle = Turtle + 1;
Tmanapoints = Tmanapoints + 1;
ManaPoints = ManaPoints + 1;
NextMaxLizardExp= NextMaxLizardExp *1.5;
}
document.getElementById("ManaPoints").innerHTML = ManaPoints;
document.getElementById('TurtleMexp').innerHTML = NextMaxTurtleExp;
document.getElementById('Turtlelv').innerHTML = Turtlelv;
document.getElementById('TurtleCexp').innerHTML = TurtleCexp;
document.getElementById('Turtle').innerHTML = Turtle;
}
document.getElementById("wolf-radio").addEventListener("change", wolfXpUp)
document.getElementById("wolf-radio").addEventListener("change",
Wolfandstrength)
document.getElementById("lizard-radio").addEventListener("change",
lizardXpUp)
document.getElementById("lizard-radio").addEventListener("change",
Wolfandstrength);
document.getElementById("Strength").innerHTML = Strength;
document.getElementById("Magic").innerHTML = Magic;
document.getElementById("ManaPoints").innerHTML = ManaPoints;
HTML code: ( can change if needed its not perfect)
font size="+2"> <b> Pets </b></font>
<div id="turtle" class="control">
<label class="radio">
<input type="radio" name="Pets" id="turtle-radio">
</label><img src="turtle.png" alt="turtle" height="100" width="100"> Lv
<span id="Turtlelv">1</span> <span id="TurtleCexp">0</span> / <span
id="TurtleMexp">100</span>
<br />
<br />
<div id="lizard" class="control">
<label class="radio">
<input type="radio" name="Pets" id="lizard-radio">
</label><img src="lizard.png" alt="lizard" height="42" width="42">
Lv <span
id="Lizardlv">1</span> <span id="LizardCexp">0</span> / <span
id="LizardMexp">100</span>
<br />
<div id="wolf" class="control">
<label class="radio">
<input type="radio" name="Pets" id="wolf-radio">
</label><img src="wolf.png" alt="wolf" height="60" width="60">
Lv <span id="Wolflv">1</span> <span
id="WolfCexp">0</span> / <span id="WolfMexp">100</span></div>
<br />
<span id="Strength">0</span>
<br />
<span id="Magic">0</span>
<br />
<span id="ManaPoints">0</span>
I expect from using that true/false function in my what i've already tried box to help me disable radio buttons functions/ stat buffs while a diffrent radio button is selected. But the actual output when you switch from the turtle radio button to lizard radio button it takes away 1 strength when strength should be untouched unless the wolf radio button is selected.

Changing a a html element with a if/else if statement based on a selected option

I want to change the lable tags and the placeholder of the input for the for the form with an id of "PercentageCalc". I want it to change based off of the selected option for the dropdown menu. I tried different ways of writing the function and tried giving it .addEventListener. Cant seem to figure it out.
let numField1 = document.getElementById('numField1');
let numField2 = document.getElementById('numField2');
let resultField = document.getElementById('resultField');
let form = document.getElementById('PercentageCalc');
let preInputText = document.getElementById('preInputText');
let numField1Text = document.getElementById('numField1Text');
let numField2Text = document.getElementById('numField2Text');
let CalcTypeSelector = document.getElementById('CalcTypeSelector');
CalcTypeSelector.addEventListener('change', function () {
if (CalcTypeSelector.value = 'whatisXPofY') {
preInputText.innerText = "What is";
numField1Text.innerText = "% of";
numField1.placeholder = "X";
numField2Text.innerText = "?";
numField2.placeholder = "Y";
} else if (CalcTypeSelector.value = 'XisYPofWhat') {
numField1Text.innerText = "is";
numField1.placeholder = "X";
numField2Text.innerText = "% of what?";
numField2.placeholder = "Y";
} else if (CalcTypeSelector.value = 'whatPofXisY') {
preInputText.innerText = "What % of";
numField1Text.innerText = "is";
numField1.placeholder = "X";
numField2Text.innerText = "?";
numField2.placeholder = "Y";
}
});
form.addEventListener('submit', function (e) {
if (!numField1.value || !numField2.value ) {
alert("Please enter number values in the fields")
} else {
let x = parseFloat(numField1.value);
let y = parseFloat(numField2.value);
let result = x / y;
let percent = result * 100;
resultField.innerText = "Result: " + percent + "%";
e.preventDefault();
}
});
<body>
<h1>Percentage Calculators</h1>
<form id="CalcType">
<select id="CalcTypeSelector">
<option>Choose and option</option>
<option value="whatisXPofY">what is X percentage of Y?</option>
<option value="XisYPofWhat">X is Y percentage of what?</option>
<option value="whatPofXisY">what percentage of X is Y?</option>
<option value="XPofWhatisY">X percentage of what is Y?</option>
<option value="YPofXisWhat">Y percentage of X is what?</option>
</select>
</form>
<div>
<p>X is what percent of Y?</p>
<form id="PercentageCalc">
<label id="preInputText">gfg</label>
<input type="text" id="numField1" />
<label id="numField1Text">gfdg</label>
<input type="text" id="numField2" />
<label id="numField2Text">rter</label>
<br />
<br />
<input type="submit" value="Calculate">
</form>
</div>
<h3 id="resultField"></h3>
<script type="text/javascript" src="calc.js"></script>
The problem is in your if statements you should use == || === instead of =
now it works
let numField1 = document.getElementById('numField1');
let numField2 = document.getElementById('numField2');
let resultField = document.getElementById('resultField');
let form = document.getElementById('PercentageCalc');
let preInputText = document.getElementById('preInputText');
let numField1Text = document.getElementById('numField1Text');
let numField2Text = document.getElementById('numField2Text');
let CalcTypeSelector = document.getElementById('CalcTypeSelector');
CalcTypeSelector.addEventListener('change', function () {
console.log(CalcTypeSelector.value);
if (CalcTypeSelector.value == 'whatisXPofY') {
preInputText.innerText = "What is";
numField1Text.innerText = "% of";
numField1.placeholder = "X";
numField2Text.innerText = "?";
numField2.placeholder = "Y";
} else if (CalcTypeSelector.value === 'XisYPofWhat') {
numField1Text.innerText = "is";
numField1.placeholder = "X";
numField2Text.innerText = "% of what?";
numField2.placeholder = "Y";
} else if (CalcTypeSelector.value === 'whatPofXisY') {
preInputText.innerText = "What % of";
numField1Text.innerText = "is";
numField1.placeholder = "X";
numField2Text.innerText = "?";
numField2.placeholder = "Y";
}
});
form.addEventListener('submit', function (e) {
if (!numField1.value || !numField2.value ) {
alert("Please enter number values in the fields")
} else {
let x = parseFloat(numField1.value);
let y = parseFloat(numField2.value);
let result = x / y;
let percent = result * 100;
resultField.innerText = "Result: " + percent + "%";
e.preventDefault();
}
});
<body>
<h1>Percentage Calculators</h1>
<form id="CalcType">
<select id="CalcTypeSelector">
<option>Choose and option</option>
<option value="whatisXPofY">what is X percentage of Y?</option>
<option value="XisYPofWhat">X is Y percentage of what?</option>
<option value="whatPofXisY">what percentage of X is Y?</option>
<option value="XPofWhatisY">X percentage of what is Y?</option>
<option value="YPofXisWhat">Y percentage of X is what?</option>
</select>
</form>
<div>
<p>X is what percent of Y?</p>
<form id="PercentageCalc">
<label id="preInputText">gfg</label>
<input type="text" id="numField1" />
<label id="numField1Text">gfdg</label>
<input type="text" id="numField2" />
<label id="numField2Text">rter</label>
<br />
<br />
<input type="submit" value="Calculate">
</form>
</div>
<h3 id="resultField"></h3>

Calculating a student grade in JavaScript

I've got an HTMl form to input student names and grades in which should use JavaScript to calculate a grade that is then printed on the screen. My HTMl works fine if I comment the meat of my JavaScript out, but not if I don't. The error is somewhere in the code that I commented out, but I just can't find it (or them).
The HTML form will submit, alert the user, and show my message correctly as long as it is fed a concrete grade and score instead of trying to fetch it through getGrade() and getScore(). This is why I know the bug is in the JavaScript.
I've run the page in the JavaScript console to look for bugs, but there are no red flag errors.
This is my first HTML/JavaScript program, and I not very good at it. Anyway, it's a day late and in less than two hours, it will be two days late, so if anyone could help, I'd appreciate it hugely. Here's the code, sorry if it's too much:
<!DOCTYPE html>
<html>
<head>
<title>Joe Peterson's Assignment 7</title>
<script>
function calculateGrade(){
document.getElementById("form1").style.display = "none";
document.getElementById("p1").style.display = "block";
var fname = document.getElementById("LastName").value;
var lname = document.getElementById("FirstName").value;
var valMidterm = document.getElementById("MidtermScore").value;
var valFinal = document.getElementById("FinalScore").value;
var lMidterm = document.getElementById("MidtermLetter").value;
var lFinal = document.getElementById("FinalLetter").value;
var homeworkArray = document.getElementById("HomeworkScores").value.split(',');
var classworkArray = document.getElementById("ActivityScores").value.split(',');
/*
var s1 = new Student(fname, lname);
for (var i = 0; i < classworkArray.length; i++)
s1.addGradedActivity(classworkArray[i]);
for (var i = 0; i < homeworkArray.length; i++)
s1.addGradedHomework(homeworkArray[i]);
s1.setMidterm(valMidterm, lMidterm);
s1.setFinal(valFinal, lFinal);
var grade = s1.getGrade();
var score = s1.getScore();
*/
document.getElementById("span1").innerHTML = (grade);
document.getElementById("span2").innerHTML = (score);
document.getElementById("fname").innerHTML = (fname);
document.getElementById("lname").innerHTML = (lname);
alert(document.getElementById("FirstName").value);
return false;
}
/*
function Coursework(){
var sum = 0;
var num = 0;
this.addScore = function(score){
if (score < 0) {score = 0;}
if (score > 100) {score = 100;}
sum += score;
num++;
}
this.getAverage = function(){
return (sum/num);
}
}
function Exam(){
var score = 0;
var grade = "";
this.Exam = function(Score, Grade)
{
if (Score < 0) {Score = 0;}
if (Score > 100) {Score = 100;}
score = Score;
if (Grade != "A" && Grade != "B" && Grade !="C"
&& Grade !="D" && Grade != "F")
{
console.log("You have submitted a bad grade for an Exam, value of:G.");
Grade = "F";
}
grade = Grade;
}
this.getScore = function(){
return score;
}
this.getGrade = function(){
return grade;
}
}
function Student(){
var firstName;
var lastName;
var midterm;
var finalExam;
var homework = new Coursework();
var inclass = new Coursework();
this.Student = function(first, last){
firstName = first;
lastName = last;
}
this.setMidterm = function(score, grade){
midterm = new Exam(score, grade);
}
this.setFinal = function(score, grade){
finalExam = new Exam(score, grade);
}
this.addGradedHomework = function(score){
homework.addScore(score);
}
this.addGradedActivity = function(score){
inclass.addScore(score);
}
this.getFinalGrade = function(totalScore)
{
var grade = totalGrade(totalScore);
var grade2 = "F";
var midGrade = this.convertGrade(midterm.getGrade());
var finGrade = this.convertGrade(finalExam.getGrade());
if (midGrade < finGrade)
{
grade2 = midterm.getGrade();
}
else
{
grade2 = finalExam.getGrade();
}
if (convertGrade(grade) > convertGrade(grade2))
return(grade);
else
return(grade2);
}
this.totalGrade = function(totalScore)
{
var totalGrade = "F";
if (totalScore >= 90)
totalGrade = "A";
else if (totalScore >= 80)
totalGrade = "B";
else if (totalScore >= 70)
totalGrade = "C";
else if (totalScore >= 60)
totalGrade = "D";
else
totalGrade = "F";
return (totalGrade);
}
this.convertGrade = function(letter)
{
var num = 0;
if (letter === "A")
num = 4;
else if (letter === "B")
num = 3;
else if (letter === "C")
num = 2;
else if (letter === "D")
num = 1;
else
num = 0;
return(num);
}
this.getScore = function()
{
var totalScore = 0;
totalScore += inclass.getAverage() * .15;
totalScore += homework.getAverage() * .25;
totalScore += midterm.getScore() * .25;
totalScore += finalExam.getScore() * .35;
return totalScore;
}
this.getGrade = function()
{
var totalScore = 0;
totalScore += inclass.getAverage() * .15;
totalScore += homework.getAverage() * .25;
totalScore += midterm.getScore() * .25;
totalScore += finalExam.getScore() * .35;
var grade = getFinalGrade(totalScore);
return grade;
}
}
*/
</script>
</head>
<body>
<p><h1>Joe Peterson's Assignment 7</h1></p>
<form name="input" id="form1" onsubmit="return calculateGrade()" style="display:form">
First name: <input type="text" name="FirstName" id="FirstName" value="Joe"><br>
Last name: <input type="text" name="LastName" id="LastName" value="Peterson"><br>
Homework Scores (separate with commas): <input type="text" name="HomeworkScores" id="HomeworkScores" value="90, 80, 98"><br>
Activity Scores (separate with commas): <input type="text" name="ActivityScores" id="ActivityScores" value="71, 65, 96"><br>
Midterm Exam Percentage: <input type="text" name="MidtermScore" id="MidtermScore" value="91"><br>
Midterm Exam Letter Grade: <input type="text" name="MidtermLetter" id="MidtermLetter" value="A"><br>
Final Exam Percentage: <input type="text" name="FinalScore" id="FinalScore" value="75"><br>
Final Exam Letter Grade: <input type="text" name="FinalLetter" id="FinalLetter" value="C"><br>
<input type="submit" value="Submit">
</form>
<p id="p1" style="display:none">Final course grade for <span id="fname">Joe</span> <span id="lname">Peterson</span> is: <span id="span1">X</span> (<span id="span2">yy</span>%)</p>
</body>
</html>

Categories

Resources