I have to fix a program which calculates a total cost for a group of people to go on a certain tour. There are three tours, each with their individual cost for children and adults. I believe I have written the correct java and html to do so, although it appears not to work.
Javascript:
function calculateTotal (){
"use strict";
var adults = document.tour.adults.value;
var children = document.tour.children.value;
var costAdults = [180,120,80]; //stored prices for adults for each tour in an array
var costChildren = [155,120,70];
var tour = document.tour.tours.value; //isnt used
var cost = 0;
if (document.tour.tours.options[0].selected) {
//if option 0 (All Day Dreamer) is selected, then cost = cost of adult [0]*number of adults + cost of children [0]*number of children
cost = costAdults[0]*adults + costChildren[0]*children;
}
if (document.tour.tours.options[1].selected) {
cost = costAdults[1]*adults + costChildren[1]*children;
}
if (document.tour.tours.options[2].selected) {
cost = costAdults[2]*adults + costChildren[2]*children;
}
document.getElementById("cost").innerHTML = "Cost is" + cost;
}
HTML:
<title>Captain Joes Tours</title>
<script src="Captain Joes Tours.js" type="text/javascript"></script>
</head>
<body>
<form id="tour">
Adults:
<select name="adults">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
<option name="3" value="3">3</option>
<option name="4" value="4">4</option>
</select>
<br>
Children:
<select name="children">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
<option name="3" value="3">3</option>
<option name="4" value="4">4</option>
</select>
<br>
Tour:
<select name="tours">
<option name="All Day Dreamer">All Day Dreamer</option>
<option name="Half-Day Safari">Half-Day Safari</option>
<option name="2-Hour Adventure">2-Hour Adventure</option>
</select>
<input id = "submit" type = "button" value = "Submit" onclick = "calculateTotal();">
</form>
<div id="price">
<p id="cost">Cost:</p>
</div>
</body>
The number of adults and children can be from 1 to 4. The value selected is the same as the var adults and var children in the javascript.
If tour [0] is selected which would be All Day Dreamer, the cost can be calculated by multiplying the number of adults by the [0] variable in the costAdults array and adding that to the children's equivalent. The same process can be done for the other tours with the respective variables.
The page looks like this, yes very basic I will fix it later
The problem is, the submit button does not display any cost. It's a very simple program and I'm not experienced in javascript so I cannot find the problem.
Help is much appreciated.
var adults = 1;
var children = 1;
var costAdults = [180,120,80]; //stored prices for adults for each tour in an array
var costChildren = [155,120,70];
var tour = "All Day Dreamer"; //isnt used
var cost = 0;
function myFunctionAdult(sel)
{
adults = parseInt(sel.options[sel.selectedIndex].text);
}
function myFunctionChildren(sel)
{
children = parseInt(sel.options[sel.selectedIndex].text);
}
function myFunctionDreamer(sel)
{
tour = sel.options[sel.selectedIndex].text;
}
function calculateTotal (){
if (tour === "All Day Dreamer") {
//if option 0 (All Day Dreamer) is selected, then cost = cost of adult [0]*number of adults + cost of children [0]*number of children
cost = costAdults[0]*adults + costChildren[0]*children;
}
if (tour === "Half-Day Safari") {
cost = costAdults[1]*adults + costChildren[1]*children;
}
if (tour === "2-Hour Adventure") {
cost = costAdults[2]*adults + costChildren[2]*children;
}
document.getElementById("cost").innerHTML = "Cost is: " + cost;
}
<title>Captain Joes Tours</title>
<script src="Captain Joes Tours.js" type="text/javascript"></script>
</head>
<body>
<form id="tour">
Adults:
<select name="adults" id="adults" onChange="myFunctionAdult(this);">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
<option name="3" value="3">3</option>
<option name="4" value="4">4</option>
</select>
<br> Children:
<select name="children" onChange="myFunctionChildren(this)">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
<option name="3" value="3">3</option>
<option name="4" value="4">4</option>
</select>
<br> Tour:
<select name="tours" onChange="myFunctionDreamer(this)">
<option name="All Day Dreamer">All Day Dreamer</option>
<option name="Half-Day Safari">Half-Day Safari</option>
<option name="2-Hour Adventure">2-Hour Adventure</option>
</select>
<input id="submit" type="button" value="Submit" onclick="calculateTotal();">
</form>
<div id="price">
<p id="cost">Cost:</p>
</div>
</body>
// Register a listener to the form submit event
document.getElementById("tour").addEventListener("submit", showCost);
// Presentation.
function showCost (event) {
var form = event.target.elements;
document.getElementById("cost").innerHTML = "Cost is " +
calculateTotal(
Number(form.adults.value),
Number(form.children.value),
form.tours.selectedIndex
);
event.preventDefault();
}
// Logic.
function calculateTotal (numbOfAdults, numbOfChildren, tourIndex) {
var costAdults = [180,120,80]; //stored prices for adults for each tour in an array
var costChildren = [155,120,70];
var totalCost = costAdults[tourIndex] * numbOfAdults + costChildren[tourIndex] * numbOfChildren;
return totalCost;
}
html
<title>Captain Joes Tours</title>
<script src="Captain Joes Tours.js" type="text/javascript"></script>
</head>
<body>
<form id="tour">
Adults:
<select name="adults">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
<option name="3" value="3">3</option>
<option name="4" value="4">4</option>
</select>
<br>
Children:
<select name="children">
<option name="1" value="1">1</option>
<option name="2" value="2">2</option>
<option name="3" value="3">3</option>
<option name="4" value="4">4</option>
</select>
<br>
Tour:
<select name="tours">
<option name="All Day Dreamer">All Day Dreamer</option>
<option name="Half-Day Safari">Half-Day Safari</option>
<option name="2-Hour Adventure">2-Hour Adventure</option>
</select>
<button type="submit">Calculate</button>
</form>
<div id="price">
<p id="cost">Cost:</p>
</div>
</body>
See the Pen qPzQXg by Jorge Gonzalez (#donmae) on CodePen.
Related
How can I enter multiple tags in a field?
So below is my code so far. I have five fields. The first two are separate, the next two are related, and the last one is where all the tags should go.
I want want the first two drop downs (color and shapes) to only contribute one tag each to the full tag field.
I want the input field and the last drop down to be combined and be able to enter multiple tags. How can I do that?
So as an example the full tag field could be populated with the following:
color: red, shape: circle, food: burgers, food: french fries, drink: coke, drink: pepsi, drink: orange juice, clothes: nike, clothes: adidas, container: pyrex
function myFunction() {
var taginput = $('#taginput').val();
var tagdropdown = $('#tagdropdown').val();
$('#fulltag').val(tagdropdown + ": " + taginput);
}
function myFunction2() {
var tagcolordropdown = $('#tagcolordropdown').val();
var tagdropdown = $('#tagdropdown').val();
$('#fulltag').val("color: " + tagcolordropdown);
}
function myFunction3() {
var tagshapedropdown = $('#tagshapedropdown').val();
$('#fulltag').val("color: " + tagshapedropdown);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label for="tagcolordropdown">What colors are in the picture?:</label>
<select id="tagcolordropdown">
<option value="Blue">Blue</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
<option value="Green ">Green</option>
</select>
<input type="button" value="Add Color As Tag" onclick="myFunction2()"><br><br>
<label for="tagshapedropdown">What shapes are in the pictures:</label>
<select id="tagshapedropdown">
<option value="Circle">Circle</option>
<option value="Square">Square</option>
<option value="Rectangle">Rectangle</option>
<option value="Pentagon ">Pentagon</option>
</select>
<input type="button" value="Add Shape As Tag" onclick="myFunction3()"><br><br>
<label for="taginput">Enter a Tag:</label> Type the name of a food, drink, clothing that relates to your image.
<input type="text" id="taginput" name="taginput"><br><br>
<label for="tagdropdown">Select a Description to Match the Tag:</label> From the drop down, please select the term which best describes your tag.
<select id="tagdropdown">
<option value="Food">Food</option>
<option value="Drink">Drink</option>
<option value="Clothes">Clothes</option>
<option value="Containers ">Containers</option>
</select><br><br>
<input type="button" value="Combine" onclick="myFunction()">
<br><br>
<label for="fulltag">Full tag:</label>
<input type="text" id="fulltag" name="fulltag" disabled><br><br>
</form>
You can store the values in array and join them once the action has been done. See example below.
Your code, however, need some changes. You are using jQuery but assigning events through onclick attribute instead of jQuery way which is using selectors.
let fullArray = [];
function myFunction() {
var taginput = $('#taginput').val();
var tagdropdown = $('#tagdropdown').val();
fullArray.push(tagdropdown + ": " + taginput);
combineValues();
}
function myFunction2() {
var tagcolordropdown = $('#tagcolordropdown').val();
var tagdropdown = $('#tagdropdown').val();
fullArray.unshift("color: " + tagcolordropdown);
combineValues();
}
function myFunction3() {
var tagshapedropdown = $('#tagshapedropdown').val();
fullArray.unshift("shape: " + tagshapedropdown);
combineValues();
}
function combineValues() {
$('#fulltag').val(fullArray.join(","));
}
#fulltag {
width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label for="tagcolordropdown">What colors are in the picture?:</label>
<select id="tagcolordropdown">
<option value="Blue">Blue</option>
<option value="Red">Red</option>
<option value="Yellow">Yellow</option>
<option value="Green ">Green</option>
</select>
<input type="button" value="Add Color As Tag" onclick="myFunction2()"><br><br>
<label for="tagshapedropdown">What shapes are in the pictures:</label>
<select id="tagshapedropdown">
<option value="Circle">Circle</option>
<option value="Square">Square</option>
<option value="Rectangle">Rectangle</option>
<option value="Pentagon ">Pentagon</option>
</select>
<input type="button" value="Add Shape As Tag" onclick="myFunction3()"><br><br>
<label for="taginput">Enter a Tag:</label> Type the name of a food, drink, clothing that relates to your image.
<input type="text" id="taginput" name="taginput"><br><br>
<label for="tagdropdown">Select a Description to Match the Tag:</label> From the drop down, please select the term which best describes your tag.
<select id="tagdropdown">
<option value="Food">Food</option>
<option value="Drink">Drink</option>
<option value="Clothes">Clothes</option>
<option value="Containers ">Containers</option>
</select><br><br>
<input type="button" value="Combine" onclick="myFunction()">
<br><br>
<label for="fulltag">Full tag:</label>
<input type="text" id="fulltag" name="fulltag" disabled><br><br>
</form>
I'm trying to add 2 sums, that are getting fetched by an select option.
All I want is to calculate X + Y, but i get a weird error.
Code:
$( document ).ready(function() {
var id1 = $("#one").val();
$("#final_value").val(id1);
var id2 = $("#two").val();
$("#final_value").val(id2);
$("#final_value").val(this + parseInt(id1) + parseInt(id2));
});
https://jsfiddle.net/xpvt214o/957709/
You have this in your #final_value element. I've also added a change event to your code so it will update when one of the options change:
$(document).ready(function() {
$("#one, #two").on("change", () => {
var id1 = $("#one").val();
var id2 = $("#two").val();
$("#final_value").val(parseInt(id1) + parseInt(id2));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
<select class="full-width select2" name="" id="one" data-placeholder="" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<select class="full-width select2" name="" id="two" data-placeholder="" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<label for="final_value">Result:</label>
<input type="text" value="" id="final_value">
There's a this in the last statement, replace the last line with:
$("#final_value").val(parseInt(id1) + parseInt(id2));
Now it should work.
Remove this value:
From:
$("#final_value").val(this + parseInt(id1) + parseInt(id2));
To:
$("#final_value").val(parseInt(id1) + parseInt(id2));
Cause if you will use this your function returns a string as:
[object HTMLDocument]11
I have altered Gary Thomas Code little bit:
Instead of parseInt(), you can use like this:
var id1 = +$("#one").val();
var id2 = +$("#two").val();
$(document).ready(function() {
$("#one, #two").on("change", () => {
var id1 = +$("#one").val();
var id2 = +$("#two").val();
var total = id1+id2;
$("#final_value").val(total);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td>
<select class="full-width select2" name="" id="one" data-placeholder="" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<select class="full-width select2" name="" id="two" data-placeholder="" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<label for="final_value">Result:</label>
<input type="text" value="" id="final_value">
Just remove this keyword from your summation as so :
$( document ).ready(function() {
var id1 = $("#one").val();
$("#final_value").val(id1);
var id2 = $("#two").val();
$("#final_value").val(id2);
$("#final_value").val(parseInt(id1) + parseInt(id2));
});
I am trying to compute the total price of items in a cart in Javascript. This is by multiplying the quantity by the unit price and then getting the grand total.
The cart is populated by a PHP while loop so I am using class names.
The quantity field is a dropdown/select and the price field is a span.
function sum() {
var sum = 0;
var q = 0;
var s = 0;
$('.itPrice,.qtys').each(function() {
q = $('.qtys').text() || 0; //quantity
s = $('.itPrice').text() || 0; //unit price
sum = sum + (q * s);
});
//display total
$("#sumT").text(sum);
}
<!-- inside PHP while loop -->
<label>Price: </label>
<span class="itPrice"><b>'.$row["price"].'</b></span>
<label>Quantity: </label>
<Select id="qty" name="qty" class="qtys">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Select>
<span id="sumT" name="sumT">*sum goes here*</span>
The output is NaN (Not a Number). Where am I going wrong? There is also a problem with the HTML select, it's not picking the selected option, only working with option '1'.
You can select both related elements, as two collections of object, an iterate one collection (while using the array index to refer to the other); that way you can get the quantity and the price.
To get a select selected element, use jquery val() function instead of text();
As a side note, you should not use duplicate id's or names for inputs in yout html. If you want an input with the same name, you can use qty[] for example.
function sum() {
var sum = 0, // Total sum
it = $('.itPrice'), // All the .itPrice elements
qty = $('.qtys'); // All the .qtys elements
// For each .itPrice element
it.each(function(i, e) {
var current = $(this), // Gets the current .itPrice element
related = $(qty[i]); // Get the related .qtys element, by array index
// Sum
sum += Number(current.find('b').text()) * related.val();
});
// return total
return sum;
}
$('#calc').click(function() {
console.log(sum());
});
console.log(sum());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Price: </label>
<span class="itPrice"><b>100</b></span>
<label>Quantity: </label>
<Select id="qty" name="qty" class="qtys">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Select>
<br>
<br>
<label>Price: </label>
<span class="itPrice"><b>200</b></span>
<label>Quantity: </label>
<Select id="qty" name="qty" class="qtys">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4" selected>4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</Select>
<br>
<br>
<a id="calc" href="javascript:;">Get total</a>
I need your help,
Using javascript, how could I add some sort of data form validation that would be two-fold:
1st Event, [OnKeyUp] attached to all of the input boxes
2nd Event, [OnChange] attached to all of the select boxes
Typical User Scenarios
If there is any data present in any of the input boxes and no selected option values then { enable the search button } else { keep the search button disabled }
If there are any selected option values who’s option value is not null and no data present in all of then { enable the search button } else { keep the search button disabled }
<!DOCTYPE html>
<html>
<head></head>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
</html>
var car=$('#car'); var fruits=$('#fruits');
var veggie=$('#veggie'); var number = $('#number');
$('select').change(function(){
validate();
});
$('input').keyup(function(){
validate();
});
function validate(){
if(($(veggie).val()!='' || $(number).val()!='') &&
$(car).val()=='' && $(fruits).val()==''){
$('#search').prop('disabled',false);
}else if($(veggie).val()=='' && $(number).val()=='' &&
($(car).val()!='' || $(fruits).val()!='')){
$('#search').prop('disabled',false);
}else{
$('#search').prop('disabled',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<br><br>
Vegetable
<input type="input" id="veggie">
<br><br>
Number
<input type="input" id="number">
<br><br>
<input type="button" value="search" id="search" disabled>
</form>
</body>
I'm not 100% sure, but it looks like you want to enable the button if only one of the select elements has a value or one of the input elements has a value, but not if both (or neither) do.
If that's the case then this should work, and it allows you you add as many elements to it as you need by adding IDs to the arrays at the top.
https://jsfiddle.net/j7by6bsz/
var selectInputIds = ['fruits', 'car'];
var textInputIds = ['veggie', 'number'];
function setButtonState() {
var hasVal = function(arr) {
for(var i = 0; i < arr.length; i++) {
if(document.getElementById(arr[i]).value) {
return true;
}
}
return false;
};
var hasSelectValue = function () {
return hasVal(selectInputIds);
}
var hasTextValue = function () {
return hasVal(textInputIds);
}
var theButton = document.getElementById('search');
var s = hasSelectValue();
var t = hasTextValue();
theButton.disabled = ((s && t) || (!t && !s)); // you can do this bit smarter, but this is explicit
}
(function attachStuff (arr, evt) {
function listenIn(arr, evt) {
for(var i = 0; i < arr.length; i++) {
document.getElementById(arr[i]).addEventListener(evt, setButtonState);
}
}
listenIn(selectInputIds, 'change');
listenIn(textInputIds, 'keyup');
}())
Your requirements could use some clarification around what happens if both input types have values though.
<FORM NAME="form1" METHOD="POST" ACTION="survey.php">
<p>q2: Who is your best best friend?</P>
<select name='q2' id='q21'>
<option value='0'>Select a Name</option>
<option value='2001'>Ahmed Ebaid</option>
<option value='2002'>Jaida ElTayeby</option>
<option value='2003'>Farida Ebaid</option>
<option value='2005'>Kenny Andersen</option>
<option value='2006'>Nadine Saad</option>
<option value='2007'>AbdElHai Ebaid</option>
<option value='2008'>Salwa AbdElAal</option>
</select>
<select name='q2' id='q22'>
<option value='0'>Select a Name</option>
<option value='2001'>Ahmed Ebaid</option>
<option value='2002'>Jaida ElTayeby</option>
<option value='2003'>Farida Ebaid</option>
<option value='2005'>Kenny Andersen</option>
<option value='2006'>Nadine Saad</option>
<option value='2007'>AbdElHai Ebaid</option>
<option value='2008'>Salwa AbdElAal</option>
</select>
<P>q3: How do you rate AbdElHai Ebaid?</P>
<P>
<INPUT TYPE='Radio' Name='q3' value='1' >1</P>
<P>
<INPUT TYPE='Radio' Name='q3' value='2' >2</P>
<P>
<INPUT TYPE='Radio' Name='q3' value='3' >3</P>
<P>
<INPUT TYPE='Radio' Name='q3' value='4' >4</P>
<P>
<INPUT TYPE='Radio' Name='q3' value='5' >5</P><span style='color:red' id='radio_error'></span>
<p>q4: Who is your best best friend?</P>
<select name='q4' id='q41'>
<option value='0'>Select a Name</option>
<option value='2001'>Ahmed Ebaid</option>
<option value='2002'>Jaida ElTayeby</option>
<option value='2003'>Farida Ebaid</option>
<option value='2005'>Kenny Andersen</option>
<option value='2006'>Nadine Saad</option>
<option value='2007'>AbdElHai Ebaid</option>
<option value='2008'>Salwa AbdElAal</option>
</select>
<select name='q4' id='q42'>
<option value='0'>Select a Name</option>
<option value='2001'>Ahmed Ebaid</option>
<option value='2002'>Jaida ElTayeby</option>
<option value='2003'>Farida Ebaid</option>
<option value='2005'>Kenny Andersen</option>
<option value='2006'>Nadine Saad</option>
<option value='2007'>AbdElHai Ebaid</option>
<option value='2008'>Salwa AbdElAal</option>
</select>
<p>
<INPUT TYPE="Submit" Name="Submit1" VALUE="Click here to vote">
</P>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
if ($('#'+qNum+'').is(':radio')) {
if (($('input[name='+qNum+']:checked').length == 0) ){
alert("No Selection is made for "+ qNum);
return false;
}
}
else if ($('[name="' + qNum + '"]').is(':radio')) {
var j = 1;
var nominatefriend = qNum+j;
alert (nominatefriend);
}
</script
What I'm trying to do here is to validate the form elements based on their types, for the javascript code, this is already included into a for loop that goes through all questions. I don't know the right syntax of checking whether a form element is a select or not based on the name attribute. qNum at my case is a variable that takes values such as q1, q2,.....
The alert(nominatefriend) never gets executed
I believe the correct syntax is:
$('[name="' + qNum + '"]').is('select')
without the :
You can achieve this in various ways,
var element = $('#'+qNum);
You can do it using jQuery:
if (element.is('input')) {
// do this
} else if (element.is('select')) {
// do this
}
OR
if (element.tagName == "INPUT") {
// do this
} else if (element.tagName == "SELECT") {
// do this
}
OR
if(element.prop('type') == 'select-one' ) {
// do this
}