Showing an * next to smallest value in a table javascript - javascript

I am trying to find the smallest value of fuel consumption in my table. I am not sure how to find it.
I have a user input the amounts for 5 vehicles. The collection point is an object that has constuctor function with 5 properties. then I have stored the details of the five objects in an array of 5 objects.
when I try to write the code for obtaining the lowest number I get my display as the first with a * and the next lowest with a * and the next lowest as a *. All values after the lowest are blank. I just want the lowest as a *. below is the code after I have had the user input 5 times. All this is within a for loop. one of the properties calculates the consumption in the original object constuctor function.
for (var x = 1; x <= 5; x++) {
registrationPlateNumber = prompt("Please enter a 6 character registration number.", "");
while (String(registrationPlateNumber).length != 6) {
registrationPlateNumber = prompt("Invalid registration number! Please enter a 6 character registration number.", "");
}
fuelTankVolume = prompt("Please enter the volume of the vehicle's fuel tank in litres.", "");
fuelTankVolume = parseInt(fuelTankVolume);
while (isNaN(fuelTankVolume) || fuelTankVolume <= 0) {
fuelTankVolume = prompt("Invalid volume! Please enter the volume of the vehicle's fuel tank in litres.", "");
fuelTankVolume = parseInt(fuelTankVolume);
}
distanceTravelled = prompt("Please enter the distance the vehicle can travel on a full tank of fuel.", "");
distanceTravelled = parseInt(distanceTravelled);
while (isNaN(distanceTravelled) || distanceTravelled <= 0) {
distanceTravelled = prompt("Invalid distance! Please enter the distance the vehicle can travel on a full tank of fuel.", "");
distanceTravelled = parseInt(distanceTravelled);
}
VehicleArray[x] = new Vehicle(registrationPlateNumber, fuelTankVolume, distanceTravelled);
document.writeln("<tr>");
document.writeln("<td>" + VehicleArray[x].registrationPlateNumber + "</td>");
document.writeln("<td>" + VehicleArray[x].fuelTankVolume + "</td>");
document.writeln("<td>" + VehicleArray[x].distanceTravelled + "</td>");
document.writeln("<td>" + VehicleArray[x].fuelConsumption + "</td>");
if (VehicleArray[x].fuelConsumption < LowestConsumption) {
LowestConsumption = VehicleArray[x].fuelConsumption;
MostEfficient = LowestConsumption;
MostEfficient = x;
}
if (x == MostEfficient) {
document.writeln("<td>*</td>");
}
else if (x != MostEfficient) {
document.writeln("<td> </td>");
}
}

In your approach, each time you add an element to the VehicleArray, you are checking if this element is the minimum compared to the previously added ones, and if it is, you are marking it directly with an asterisk.
However, there could be elements that have not been added yet that have smaller values. But as the for loop did not reach these yet, the current element is marked with an asterisk.
Then at the next iteration, if the next vehicle's fuel consumption is even lower, it will also be marked with an asterisk, and so on.
The fix for this is to use two for loops: one for filling the array and getting the minimum, and then another one for displaying the elements in the table.
//first loop: add all elements to the array and get the index of the minimum
var MostEfficient = 0;
for (var x = 1; x <= 5; x++){
//code for user prompts...
//adding the vehicle to the array
VehicleArray[x] = new Vehicle(registrationPlateNumber, fuelTankVolume, distanceTravelled);
//checking if it is the minimum for now; only the final minimum will be used in the next loop
if (VehicleArray[x].fuelConsumption < LowestConsumption){
LowestConsumption = VehicleArray[x].fuelConsumption;
MostEfficient = x;
}
}
//second for loop to write the elements to the document
//now MostEfficient won't update anymore, and will point to the final minimum
for(var x = 1; x <= 5; x++)
document.writeln( "<tr>");
document.writeln( "<td>" + VehicleArray[x].registrationPlateNumber + "</td>");
document.writeln( "<td>" + VehicleArray[x].fuelTankVolume + "</td>");
document.writeln( "<td>" + VehicleArray[x].distanceTravelled + "</td>");
document.writeln( "<td>" + VehicleArray[x].fuelConsumption + "</td>");
if (x == MostEfficient){
document.writeln("<td>*</td>");
}
else if (x != MostEfficient){
document.writeln("<td> </td>");
}
}
Also, on a side note, why are you doing this?
MostEfficient = LowestConsumption;
MostEfficient = x;
Wrong variable name maybe? Otherwise the first statement is useless.

You can't do this in a single loop since you don't know the user's input before it's given.
Separating the algorithm in two loops should be better: one that fills up VehicleArray and one another that display the table. In between you'll need to find MostEfficient.
Since it seems like homework I'll not give you code as an answer but I can schematize:
loop:
-> fetching data and filling the array
-> finding the most efficient
-> displaying the table

Related

Calculating the percentage for label and textbox

I have a input a few input fields that the user can enter the values the first time they visit the particular page, these values get saved to the database and the function is called every time that you enter a value into the textbox as it will display the percentage of the 5 values from the total.
When the user leaves the form and comes back the labels are shown instead of the text boxes. Is the below code the right direction for such a task that would dynamically select the correct parameter ".text" or ".val" specifically to get the values since the labels get populated the next time the user comes back? I would like to automate this process instead of appending each label value by myself.
I have marked where I am having trouble
function calcABC(e) {
//Declare array of numeric selectors
var arr = ["a", "b", "c", "d", "e"];
var x = "";
var y = "";
if (e == "label") {
x = "lbl_"
y = ".text()";
}
else {
x = "txt_"
y = ".val()";
}
//HAVING TROUBLE HERE VVVVVVV
alert(eval("$('#' + x + arr[0]) + y)"));
alert("hello");
//loop through the array and get the value for that array index
var before = 0;
for (var i in arr)
{
before += isNaN(parseInt($("#"+ x + arr[i]).val())) ? 0 : parseInt($("#" + arr[i]).val())
}
//Apply the total to the global variable
ABCTotal = before;
//Loop through the numbers and get the precentage value and append the value to the relevant area
for (var j in arr)
{
console.log($("#" + x + arr[i]).val())
var val = isNaN(parseInt($("#" + x + arr[j]).val())) ? 0 : parseInt($("#" + arr[j]).val());
$("#txt" + arr[j] + "Prec > small").text(calcPrec(val).toFixed(2) + "%");
}
//Set the total field
$("#txt_ABCTotal").text(ABCTotal);
}
// Nice function to quickly calculate the precent value from a total
function calcPrec(val)
{
return (val * 100) / ABCTotal;
}
I hope that makes sense! Anyways any help appropriated!
To avoid use of eval, which is highly recommended it is better to do y = 'text' or y = 'val' and then call the function with the array notation like :
$('#' + x + arr[0])[y]()

Need to remove +=

The program usually displays something like 1+3+5+=9 but i want to get rid of the + after 5. Please help me with this issue that I have right now at the moment.
var userNum = prompt("Pick a number and every odd number between 1 and that
number will be added");
var increase = 0;
var totalSum = 0;
var expression = "+";
document.write("the sum of the odd numbers are:");
// while the increase is less than the userNum , the increase will
increase by one
while(increase < userNum){
increase++
// if the increase is odd , it will be added to the totalSum
if(increase % 2 === 0){
} else {
document.write(increase+ expression)
totalSum = totalSum + increase
}
}
document.write( 0+ "=" + totalSum);
You could put the + sign in front, and on the first iteration, don't add it:
var userNum = prompt("Pick a number and every odd number between 1 and that number will be added");
var increase = 1,
totalSum = 0,
expression = "+",
str = "The sum of the odd numbers is: ";
while(increase < userNum) {
if(increase !== 1) { str += expression; }
str += increase;
totalSum += increase;
increase += 2;
}
document.write( str + "=" + totalSum );
Instead of creating the output while iterating, put your numbers into an array and simply .join("+") (MDN) the final array to create the string 1+3+5 for output at the end.
I leave the implementation for you as an exercise.
add values to array and join with + sign.
HTML:
<div class="sum">
</div>
JS:
var userNum=10;
var increase = 0;
var totalSum = 0;
var expression = "+";
$('.sum').text("the sum of the odd numbers are:");
// while the increase is less than the userNum , the increase will
//increase by one
var txt=[];
while(increase < userNum){
increase++
// if the increase is odd , it will be added to the totalSum
if(increase % 2 === 0){}
else{
txt.push(increase);
totalSum = totalSum + increase
}
}
$(".sum").text(txt.join("+") + "=" + totalSum);
https://jsfiddle.net/u5o9qb0c/
Try checking for the last iteration of the while loop like- (you can replace your while loop with the below one)
while(increase < userNum){
increase++
if(increase % 2 !== 0){
if(increase === userNum){
document.write(increase)
}else{
document.write(increase+ expression)
totalSum = totalSum + increase
}
}
}
Hope this helps.
First and foremost, don't use document.write(). It has very limited use cases and more often than not will overwrite your existing document. Instead, set up an empty HTML element to use as an "output" area and then just write into that area.
Next, you get the extra + symbol because you are writing:
document.write(increase + expression);
and expression is hard-coded to the + symbol.
You'll need to only add that when another operand is added.
It should be like this:
/*
Place all of this code in "script" tags and place those tags
just before the closing body tag (</body>) so that this code won't run
until all of the HTML is parsed
*/
// Get a reference to the output element
var output = document.getElementById("output");
var endNum = prompt("Pick a number and every odd number between 1 and that number will be added");
// Since we know you want to start at 1, initialze the variable to 1
var increase = 1;
var totalSum = 0;
// This will hold the result that will be injected just once into the document
var result = "";
// while the increase is less than the userNum , the increase will increase by one
while(increase < endNum){
// Just check to see if we've already started writing the result
// and prepend the + sign if so.
if(result !== ""){
result += "+";
}
result += increase;
totalSum += increase;
// Just increment by 2 to stay with odd numbers
increase += 2;
}
output.innerHTML += result + "=" + totalSum;
<div id="output">
<h1>The sum of the odd numbers are:</h1>
</div>
What you're doing could be a lot more concise. See below.
Changed this increase variable to initialize to one, because that's always your first value according to the prompt.
Starting the expression as the leading text, because a) I want this printed before anything else, and b) I don't want the plus sign on the first iteration
Regarding the expression assignment in the loop, it's unnecessary to assign this every iteration as I have, it's more concise to just assign it than to check if I need to do it every time.
I move the increment of increase to later in the loop so that the value that gets printed is the what it is at the start of the loop. It's a matter of preference, but I would have had to initialize it to -1 if I wanted this to work with it incrementing before the document.write, which I don't like from the standpoint of conveying clear intent.
I also got rid of the semicolons for no reason at all other than that they weren't necessary. (Addendum: In the context of this discussion, I'm not prescribing making this change. It's my code style, but adding semicolons between the statements would have no relevant impact on the code snippet.)
var userNum = prompt("Pick a number and every odd number between 1 and that number will be added")
var increase = 1
var totalSum = 0
var expression = 'the sum of the odd numbers are:'
while (increase <= userNum) {
document.write(expression + increase)
totalSum += increase
increase += 2
expression = '+'
}
document.write("=" + totalSum)

My Javascript prompt runs before function even if prompt is located after the function

I wrote a small practice program that shows the times table for a prompted number.
I want the table to be shown after the user is asked for which number. If the user enters a different than -1 number, I want to ask for another number.
The sequence that I'm looking for is prompt the user, show the table, prompt the user show the table ... Unfortunately the sequence in which my program works is prompt the user, prompt the user, prompt the user ... AND JUST AFTER THAT show the tables for each input.
Obviously the code is not written in that way.
// get number to show time table for
var aNumber = prompt("Enter the number for time table or -1 to stop the program", "");
while(aNumber != -1) {
timeTableFrom(aNumber); // show time table for the first number
aNumber = prompt("Enter the number for time table or -1 to stop the program", ""); // ask for another number. HERE IS THE PROBLEM - THIS LINE RUNS BEFORE THE PREVIOUS ONE!
}
document.write("stopped");
function timeTableFrom(number)
{
for (var i = 0; i <= 10; i++)
{
document.write(number + " * " + i + " = " + number*i + "<br />");
}
}
// get number to show time table for
var aNumber = null;
var div = document.getElementById("textDiv");
setTimeout(enterNumber, 0);
function enterNumber()
{
aNumber = prompt("Enter the number for time table or -1 to stop the program", "");
if (aNumber != -1) {
timeTableFrom(aNumber); // show time table for the first number
setTimeout(enterNumber, 0);
}
else
div.innerHTML += "stopped"
}
function timeTableFrom(number)
{
for (var i = 0; i <= 10; i++)
{
div.innerHTML += number + " * " + i + " = " + number*i + "<br />";
}
}
<div id="textDiv">
</div>
#Teemu is correct. And I admit, it's a bit sloppy, but this should work. Try to avoid using document.write as it can have unpredictable results. Instead try other methods of output

How do I use innerHTML inside a loop using JavaScript?

Here is the code and snippet:
var amount = prompt("How many list items would you like?");
if(isNaN(amount) || amount < 1) {
alert("Please enter a positive whole number");
} else {
for(i = 0; i <= amount; i++) {
document.getElementById("content").innerHTML = "Loop: " + i + "<br>";
}
}
<div id="content"></div>
Hi, I'm a new to Javascript and I can't figure this out. How can I write into the div tag "content" using the loop to display values inside the div tag per loop?
Change to += instead of = and start the for loop with 1 unless you want to print out as loop 0, loop 1 and so on...
document.getElementById("content").innerHTML += "Loop: " + i + "<br>";
var amount = prompt("How many list items would you like?");
if(isNaN(amount) || amount < 1) {
alert("Please enter a positive whole number");
} else {
for(i = 1; i <= amount; i++) {
document.getElementById("content").innerHTML += "Loop: " + i + "<br>";
}
}
<div id="content"></div>
Your code looks basically correct but you need to understand the context in which a browser executes javascript. For a given computation (event), the browser usually executes all of that computation before it does any redraws of the actual page. What this means in your case is that only the last value of innerHTML will be used. One approach to this is to accumulate the entire innerHTML value before returning (I see IsabelHM just posted that). The second would be to use something like setTimeout to spread the computation out over multiple "sessions" - something like
var i = 0;
count = function() {
document.getElementById("content").innerHTML = "Loop: " + i + "<br>";
i++;
if (i < amount) {
window.setTimeout(count, 100);
}
};
count();
Note - I haven't run that but the idea is there. I basically count at 100ms intervals.

issue with adding values from array

I am writing a small application for the user to enter the name of a book and then its price, push the values of those to an array, output the book name and cost to the page and then display the total.
the issue I am having is with the total, for example:
If I write 2 as the value of each of the values, the "totalOutput" says 022222 instead of 10 as I would expect, I have tried a few different things and read a few articles on here but haven't found any to be much help or that useful.
these are the exact lines I am having issues with:
//go over each item in price and add up the total
price.forEach(function addNumber(value) {
total += value;
});
//write the total
totalOutput.innerHTML = "the total value of the books is " + total;
}
And incase you need it - here is my full javascript code:
//Book shop task
function trackBooks() {
//target the output ul and store in a variable
var output = document.getElementById("booksOutput");
//Setup the two arrays to hold the book names and their prices.
var books = [];
var price = [];
//declare a variable for working out the total
var total = 0;
//target the total output
var totalOutput = document.getElementById("totalOutput");
//set up a counter for the loop
var x = 0;
//setup the loop for entering the names of the books and their prices, for the sample, I have set the loop to run 5 times as stated in the pseudo code
for (var i = 0; i < 5; i++) {
//add one to the counter on each loop
x = x + 1;
//declare a variable to ask the user for the book name and the cost and push those values to their arrays we created above
var bookName = prompt("enter book name number " + x);
books.push(bookName);
var bookPrice = prompt("how much does book number " + x + " cost?");
price.push(bookPrice);
//create a variable to create new li tags on output
var newLi = document.createElement("li");
//add the required info to the new link
newLi.innerHTML = "book " + x + ": " + "<strong>" + books[i] + "</strong>" + " costs " + "<strong>" + price[i] + "</strong>";
//write out the name and price to the page
output.appendChild(newLi);
}
//go over each item in price and add up the total
price.forEach(function addNumber(value) {
total += value;
});
//write the total
totalOutput.innerHTML = "the total value of the books is " + total;
}
var bookPrice = prompt("how much does book number " + x + " cost?");
price.push(bookPrice);
prompt returns a string, and when you add a number (0) and a string ("2"), you get a string ("02"). You should cast to number here:
price.push(+bookPrice);
(unary + casts to a number)
You are adding Strings not a Numbers. For example:
"Hello " + "World";
Will output "Hello World".
"10" + "20";
will output "1020"
Instead you have to convert the String to a Number
Number("10") + Number("20");
will ouput 30
To apply this to your code:
price.push(Number(bookPrice));

Categories

Resources