www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17

Thread: java scripts from hell help please

  1. #1
    Join Date
    May 2014
    Posts
    10

    java scripts from hell help please

    i have 3 scripts bellow that i just cant seem to get work any help = much love (ps i have the appropriate html so i know its not that)

    var num = []

    for (var counter=1;counter<=5;counter++)
    {
    var num = prompt("Enter a number value here");
    num = parseInt(num);
    arr.push(num);
    }


    for (var counter=0; counter<num.length; counter++)
    {
    var cubedNum = cube(num[index]);

    document.write("<br>" + num[index] + " cubed is " + cubedNum)
    }

    var average = average(num);
    document.write("and not forgetting the average is " + average);
    }

    function cube(x)
    {
    var cubed = x * x * x;
    return cubed;


    function average(arr)
    {
    var total = 0;
    for (var counter = 0; counter<5; counter++)
    {
    total+=arr[counter];
    }
    average = total / 5;

    return average;
    }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //doesnt produce alert
    var floor = ["Beech", "Maple", "Tile", "Laminate"];
    var price = [25, 30, 20, 10];
    //arrays

    function calculate()
    {
    var length = document.getElementById("length");
    var width = document.getElementById("width");
    var radioOperator = document.querySelector('input[type=radio]:checked');
    var index = radioOperator.value;

    if(validateText(length)==false)
    {
    return;
    }

    if(validateText(width)==false)
    {
    return;
    }

    length = parseFloat(length.value);
    width = parseFloat(width.value);

    var area = length * width;
    var packs = (area / 2);
    packs = Math.ceil(packs);
    var wholeCost = packs * price[index];

    alert("\n The flooring type chosen was " + floor[index] + "." +
    "\n The area had a length of " + length + " meters and width of " + width + "meters." +
    "\nTotal room area is: " + area.toFixed(2) + " square meters. " +
    "\nYou are going to require " + numpacks + " packs at the price of \u00A3" + price[index].toFixed(2) + " per pack." +
    "\nThe total flooring cost is \u00A3" + wholeCost + ".");

    }
    //calculate cost and display answer plus validation

    function validateText(textbox)
    {
    if(textbox.value=="")
    {
    alert("Please enter a number for Length and width");
    textbox.focus();
    return false;
    }
    else if(isNaN(textbox.value))
    {
    alert("Text box does not contain a number");
    textbox.value="";
    textbox.focus();
    return false;
    }
    else if(textbox.value<=0 || textbox.value>50)
    {
    alert("Number must be between 1 and 50");
    textbox.value="";
    textbox.focus();
    return false;
    }
    return true;
    }

    //validation function

    document.getElementById("calculate").addEventListener('click', calculate);
    // event that listens for the click of the calculate button
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Item titles
    var items = ["Beech", "Maple", "Tile","laminate"];
    //Item prices
    var prices = [0.4, 1.2, 0.8];

    //Array to hold Items
    var shoppingList = new Array();

    function Item() {
    this.item="No description";
    this.price=0;
    this.length=0;
    this.width=0;

    }

    function calculate(){
    displaySummary.innerHTML="";//clear summary paragraph
    var quantity=document.getElementById("length");
    var quantity=document.getElementById("width");
    //validate quantity
    quantity=parseFloat(length.value);
    quantity=parseInt(width.value);

    addItemToShoppingList(length, width);
    clearForm();
    }

    function addItemToShoppingList(length,width){

    //Find out which radio button is selected
    var radioOperator = document.querySelector('input[type=radio]:checked');
    var index=radioOperator.value;

    //Create item and add to shopping list
    var i = new Item();
    i.item = items[index];
    i.price = prices[index];
    i.length = length;
    i.width = width;
    //Add current item to the array
    shoppingList.push(i);

    //Calculate total for current item
    var total = (i.price * (i.width * i.length)) / 2;
    var total = Math.ceil

    alert("Current item: " + "\nType: " + i.item +
    "\nPrice: \u00A3" + i.price +
    "\nLength: " + i.length +
    "\nWidth: " + i.width +
    "\nTotal: \u00A3" + total.toFixed(2)
    );
    }

    function clearForm(){
    document.getElementsByName("floor")[0].checked=true;
    document.getElementById("length").value="";
    document.getElementById("width").value="";

    }

    function showSummary(){
    if (shoppingList.length==0){
    alert("No items to display");
    return;
    }
    displaySummary.innerHTML="";

    for (var index=0;index<shoppingList.length;index++){
    var item = shoppingList[index].item;
    var price = shoppingList[index].price;
    var length = shoppingList[index].length;
    var width = shoppingList[index].width;


    displaySummary.innerHTML+="Item: " + item;
    displaySummary.innerHTML+="<br>Price: &pound;" + price;
    displaySummary.innerHTML+="<br>Length: " + length;
    displaySummary.innerHTML+="<br>Width: " + width;


    var total = (i.price * (i.width * i.length)) / 2;
    displaySummary.innerHTML+="<br>Total: &pound;" + total.toFixed(2);
    displaySummary.innerHTML+="<br>";
    }
    showTotals();
    }

    function showTotals(){
    var totalForItem = [0,0,0,0];//Totals for Baked Beans, Pasta and Soup
    displaySummary.innerHTML+= "<br>Transactions for type";
    for (var index=0;index<shoppingList.length;index++){
    var item = shoppingList[index].item;
    if(item=="Beech"){
    totalForItem[0]++;
    }
    else if(item=="Maple"){
    totalForItem[1]++;
    }
    else if(item=="Tile"){
    totalForItem[2]++;
    }
    else(item=="Laminate"){
    totalForItem[3]++;
    }

    }

    for (var index=0;index<totalForItem.length;index++){
    displaySummary.innerHTML+= "<br>" + items[index] + " " + totalForItem[index];
    }
    }

    document.getElementById("calc").addEventListener('click',calculate);
    document.getElementById("summary").addEventListener('click',showSummary);

    ////spent last week and abit on it and has be in by 20th arh!!!!!!! i suck at java script

  2. #2
    Join Date
    May 2014
    Posts
    628
    In your first code, well... first, five separate prompts would just piss me off; hoping that's just for testing.

    But really the big glaring error is that you seem to be trying to call the function "cube" BEFORE YOU'VE DECLARED IT! If you're not inside a object, and you haven't declared it yet, it doesn't EXIST! You can't call 'cube' or 'average' before you have declared them! Their function declarations MUST go before you call them.

    Another big error is you make num an array, then you assign a value to it, then you try to push to it. Those should be two SEPARATE varaibles with different names... though honestly your array serves no legitimate purpose as you could get rid of most of your loops and just process everything ONCE.

    I would also suggest not wasting memory by making variables for nothing. If all you're going to do with a new var is return it, don't make a new var.

    Likewise, don't recreate existing functionality -- see Math.pow

    Code:
    var total = 0, num, NaN, t;
    
    for (t = 0; t < 5; t++) {
    	nan = false;
    	do {
    		num = prompt(
    			NaN ? "Not a number, please try again\n" : ''
    			'Enter a number value here'
    		);
    	while (NaN = isNaN(num));
    	total += num;
    	document.write(num + ' cubed is ' + Math.pow(num, 3) + '<br />');
    }
    
    document.write('The average of all five digits is ' + total / 5);
    Is how I'd approach that first one. One loop, no extra functions needed, because that's all just code bloat.

    These are gonna take a bit and could get long, I'll make separate posts for each of your sets of code.
    Java is to JavaScript as Ham is to Hamburger.

  3. #3
    Join Date
    May 2014
    Posts
    628
    Let's see... your second code.

    Some advice, if you have multiple VAR declaration in a row, you can say VAR just once and then comma delimit them. Likewise if you're going to have two possible results that both return, make them a single IF using an or. Also beware that querySelector doesn't exist in all browsers, and usually chokes on psuedostates (like :checked) in the ones it does... so Id' get an id on that input (which it should have anyways) and getElementById like you did the others.

    ... and you are lacking the proper eventListener handler since you've only got the 'modern' version. I use this function:
    Code:
    	function eventAdd(e, event, handler) {
    		if (e.addEventListener) e.addEventListener(event, handler, false);
    			else e.attachEvent('on' + event, handler);
    	}
    I'd also be trapping onsubmit, instead of a calculate button -- well, unless you've got other stuff going on there too.

    So as to target all the browsers still in circulation.

    Also, there's no point in saying 'else' if the true condition is a return. Think about it, if you return, the rest of the code won't run anyways.

    I would probably expand your validation function to get the element, and return the value. You can === false as the trap. Likewise I'd try to stuff both the name and the cost into the VALUE attribute of those input, so you can add/remove them from the form without having to rewrite the script.

    I tossed together some proper/semantic markup for my approach to this to operate on:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html
    	xmlns="http://www.w3.org/1999/xhtml"
    	lang="en"
    	xml:lang="en"
    ><head>
    
    <meta
    	http-equiv="Content-Type"
    	content="text/html; charset=utf-8"
    />
    
    <meta
    	http-equiv="Content-Language"
    	content="en"
    />
    
    <title>
    	Size and Material Calculator
    </title>
    
    </head><body>
    
    <form action="#" id="process">
    
    	<h1>
    		Size and Material Calculator
    	</h1>
    	
    	<fieldset id="sizes">
    	
    		<legend>Choose Your Dimensions</legend>
    	
    		<label for="sizeHeight">Length:</label>
    		<input type="text" name="length" id="sizeLength" />
    		<br />
    		
    		<label for="sizeWidth">Width:</label>
    		<input type="text" name="width" id="sizeWidth" />
    		
    	</fieldset>
    		
    	<fieldset id="materials">
    	
    		<legend>Choose your Material</legend>
    		
    		<input
    			type="radio"
    			name="material"
    			id="materialBeech"
    			value="Beech|25"
    		/>
    		<label for="materialBeech">Beech</label>
    		<br />
    		
    		<input
    			type="radio"
    			name="material"
    			id="materialMaple"
    			value="Maple|30"
    		/>
    		<label for="materialMaple">Maple</label>
    		<br />
    		
    		<input
    			type="radio"
    			name="material"
    			id="materialTile"
    			value="Tile|20"
    		/>
    		<label for="materialTile">Tile</label>
    		<br />
    		
    		<input
    			type="radio"
    			name="material"
    			id="materialLaminate"
    			value="Laminate|10"
    		/>
    		<label for="materialLaminate">Laminate</label>
    		
    	</fieldset>
    	
    	<div id="submitsAndHiddens">
    		<input type="submit" value="calculate" />
    	</div>
    	
    </form>
    
    <script type="text/javascript"><!--
    
    /*
    	put it all in an anonymous function to restrict scope
    */
    
    (function() {
    	
    	var d = document; /* just an easy shorthand */
    			
    	function eventAdd(e, event, handler) {
    		if (e.addEventListener) e.addEventListener(event, handler, false);
    			else e.attachEvent('on' + event, handler);
    	}
    
    	function eventPrevent(e) {
    		e.cancelBubble = true;
    		if (e.stopPropagation) e.stopPropagation();
    		if (e.preventDefault) e.preventDefault();
    		e.returnValue = false;
    	}
    	
    	function alertEmptyFocus(e, message) {
    		e.value = '';
    		e.focus();
    		alert(message);
    		return false;
    	}
    
    	function validateField(id, name) {
    
    		var e = d.getElementById(id);
    		
    		if (e.value == '') return alertEmptyFocus(
    			e, 'Please enter a number for ' + name
    		);
    		
    		if (isNaN(e.value)) return alertEmptyFocus(
    			e, name + ' does not contain a number'
    		);
    		
    		var v = Number(e.value);
    		
    		if (v < 1 || v > 50) return alertEmptyFocus(
    			e, name + ' must be between 1 and 50'
    		);
    		
    		return v;
    	}
    
    	/*
    		The ID for radioValue should be a fieldset or DIV around your
    		input[radio]
    	*/
    	function radioValue(id, name) {
    		var
    			radioSet = d.getElementById(id),
    			radioList = radioSet.getElementsByTagName('input'),
    			t;
    		for (t = 0; t < radioList.length; t++) {
    			if (
    				(radioList[t].type == 'radio') &&
    				(radioList[t].checked)
    			) {
    				t = radioList[t].value.split('|');
    				return {
    					name : t[0],
    					cost : Number(t[1])
    				};
    			}
    		}
    		alert('You must select a ' + name);
    		return false;
    	}
    
    
    	eventAdd(d.getElementById('process'), 'submit', function(e) {
    	
    		var
    			length = validateField('sizeLength', 'Length'),
    			width = validateField('sizeWidth', 'Width'),
    			material = radioValue('materials', 'Material');
    			
    		/* again, #operation should be a FIELDSET around the radio buttons */
    		
    		if (
    			(length === false) ||
    			(width === false) ||
    			(material === false)
    		) return;
    		
    		var
    			area = length * width,
    			packs = Math.ceil(area / 2),
    			wholeCost = packs * material.cost;
    			
    		alert(
    			"The flooring type chosen was " + material.name + ". \n" +
    			"The area had a length of " + length + " meters and width of " + width + "meters.\n" + 
    			"Total room area is: " + area.toFixed(2) + " square meters.\n" + 
    			"You are going to require " + packs + " packs at the price of \u00A3" + material.cost.toFixed(2) + " per pack.\n" +
    			"The total flooring cost is \u00A3" + wholeCost + "."
    		);
    		
    		eventPrevent(e);
    		
    	});
    
    })();
    
    --></script>
    
    </body></html>
    Traps the submit, puts it all in an anonymous function so you don't have to fret multiple scripts interfering with each-other, has a cross-browser event attach, and so forth.

    Ok, I'm out the door for a bit, but I'll try to remember to come back and look at your third bit of code.
    Java is to JavaScript as Ham is to Hamburger.

  4. #4
    Join Date
    May 2014
    Posts
    628
    Oh, and I don't think you suck at JavaScript, I think you've just been misled by bad practices.

    ... and actually that third one I'm having trouble figuring out without the markup. If you provide the markup that's processing, I can probably dial it in better.

    THOUGH -- I'm thinking a lot of what you are doing shouldn't be done client-side in the first place; or if you do it client side, don't rely on the values and instead be sure to process it again server-side. Remember, all user input is suspect, and client-side processing is effectively user input.
    Last edited by deathshadow; 05-18-2014 at 09:07 AM.
    Java is to JavaScript as Ham is to Hamburger.

  5. #5
    Join Date
    May 2014
    Posts
    10
    thx i appreciate it just a few things on the first code i need it to have those functions and store them in an array and use a average(arr)

    also i haven't seen math.pow before can you elaborate on the code a bit further

    also your second post i have the html sorted that i need use its similar to that but is just html with length width and radios they are all id'd etc

    but the code it kinda overwhelmed me as i do all the coding in the JavaScript code itself im doing it for a foundation year at uni so kinda need understand what im putting in haha

    2nd is separate to the 3rd as 2nd is just a calculator where as the 3rd does that adds an item to an array that then uses its details to make an alert showing costs etc and then adds it to a summery of all the calculations made

    sorr

  6. #6
    Join Date
    May 2014
    Posts
    10
    also wouldn't the empty array be ok as wont they get pushed into it as index's from well the .push

  7. #7
    Join Date
    May 2014
    Posts
    628
    Quote Originally Posted by teranova View Post
    ti need it to have those functions and store them in an array and use a average(arr)
    WHY? Lemme guess? Homework written by some teacher not qualified to be teaching jack ***? Or are you actually doing something else with those values you aren't showing us?

    Quote Originally Posted by teranova View Post
    also i haven't seen math.pow before can you elaborate on the code a bit further
    It's the power function for javascript. Before you get too deep into javascript I suggest you find a good reference, and read through the methods available on objects like Math, String, Array and Number. The one at MDN is pretty good. (one of the best in fact)

    https://developer.mozilla.org/en-US/docs/Web/JavaScript

    You don't have to remember how all of them work or their exact syntax -- just remember they exist and look them up when you want to use them. In the case of Math.pow

    https://developer.mozilla.org/en-US/...jects/Math/pow

    First number is x, second number is y, returns x^y... so Math.pow (2, 3) would return 8 (2*2*2)... Math.pow(3, 4) would return 81 (3*3*3*3)

    Most complex math operations already exist in JavaScript, you don't have to brute force them. You probably should have been taught that before being handed an assignment that would have code that does... what you're trying to do.

    Quote Originally Posted by teranova View Post
    also your second post i have the html sorted that i need use its similar to that but is just html with length width and radios they are all id'd etc
    Do you have a properly built form for that with fieldsets, legends, labels, etc? Did they even teach you that yet.

    Quote Originally Posted by teranova View Post
    im doing it for a foundation year at uni
    Well, that explains why you've been led down the garden path by bad practices and really aren't learning how this stuff works. Sorry to say, most "educators" when it comes to IT aren't qualified to open their traps on the subjects they have allegedly been taught to teach -- there's a reason when I was hiring people at an IT company 20 years ago we went through two dozen hirings/firings of people with degrees, and ended up finally going to high schools, hiring people who knew nothing and teaching them ourselves -- it was easier that convincing the poor fools with the piece of paper their teachers were full of manure and then making them unlearn all the garbage they'd had their heads filled with.

    Quote Originally Posted by teranova View Post
    2nd is separate to the 3rd as 2nd is just a calculator where as the 3rd does that adds an item to an array that then uses its details to make an alert showing costs etc and then adds it to a summery of all the calculations made
    Not sure I can decipher what you mean by that.

    ... educators... when it comes to web technologies, there really are days I feel like lining every last one of them up against a wall like one of Stalin's purges. Most of them couldn't code their way out of a piss soaked paper bag with a hole in the bottom, and then they're supposed to be teaching you... RIGHT.
    Last edited by deathshadow; 05-18-2014 at 09:49 AM.
    Java is to JavaScript as Ham is to Hamburger.

  8. #8
    Join Date
    May 2014
    Posts
    10
    1st quote yeah its an assignment


    2nd quote THANKS

    3rd quote
    heres a copy

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>task 4</title>
    </head>
    <body>
    <div style="width:30%">
    <fieldset>
    <legend>Floor</legend>
    Beech<input type="radio" name="floor" value="0" checked>
    <br>
    Maple<input type="radio" name="floor" value="1">
    <br>
    Tile<input type="radio" name="floor" value="2">
    <br>
    Laminate<input type="radio" name="floor" value="3">
    <br>
    Length:<input type="text" id="length">
    <br>
    Width:<input type="text" id="width">
    </fieldset>
    </div>

    <input type="button" id="calc" value="Add item">
    <input type="button" id="summary" value="Summary">

    <div style="width:30%">
    <fieldset>
    <legend>Summary</legend>
    <p id="displaySummary"></p>
    </fieldset>
    </div>


    <script type="text/javascript" src="task4v3.js"></script>
    </body>
    </html>

    4th quote

    :0... looking for an apprentice aha

    5th quote

    lol that was probably my bad they are two separate tasks though the 3rd basically incorporates the same fundamentals as the 2nd as a part of it

    Education is a weapon whose effects depend on who holds it in his hands and at whom it is aimed.

  9. #9
    Join Date
    May 2014
    Posts
    10
    so essentially keeping them as they are any tips on getting them to work?

  10. #10
    Join Date
    May 2014
    Posts
    628
    Well on your first one, the two big flaws have to be adjusted -- move the functions before you try to execute them, and make 'num' the array and 'num' the input from PROMPT be two separate values... and also to push to num[] not arr. I would probably also use 'i' instead of 'counter' since ijkl or tnv are industry-standard for loop control vars.

    Code:
    function average(arr) {
    	var total = 0;
    	for (var i = 0; i < arr.length; i++) total += arr[i];
    	return total / arr.length;
    } 
    
    var numList = [];
    
    for (var i = 0; i < 5; i++) {
    	var num = prompt('Enter a number value here');
    	numList.push(parseInt(num));
    } 
    
    
    for (var i = 0; i < num.length; i++){
    	document.write(
    		'<br>' + numList[i] + ' cubed is ' + Math.pow(numList[i], 3)
    	);
    }
    
    document.write(
    	'and not forgetting the average is ' + average(numList); 
    );
    See? Average function BEFORE you try to call it. 'numList and num as two separate variables with the push on numList, not arr since arr doesn't exist outside 'average'.

    Though that's a really jacktarded way of doing things with the 'three loops for nothing' -- but the same could be said for document.write so...
    Java is to JavaScript as Ham is to Hamburger.

  11. #11
    Join Date
    May 2014
    Posts
    10
    aha well thanks for doing the first code for me ill try to incorporate the logic from it into the other 2

  12. #12
    Join Date
    May 2014
    Posts
    10
    just tried this code it didn't work

  13. #13
    Join Date
    May 2014
    Posts
    628
    Oops, typo. Forgot to change one of the variables to the new name:

    for (var i = 0; i < num.length; i++){

    Should be:

    for (var i = 0; i < numList.length; i++) {
    Java is to JavaScript as Ham is to Hamburger.

  14. #14
    Join Date
    May 2014
    Posts
    10
    aha no biggy tbh i should of saw it >.< hehe

  15. #15
    Join Date
    May 2014
    Posts
    10
    though tryed it and still didn't work with the edited bit tbh my mate has practicly the same code on the 2nd task and his works on my pc but mine dosnt the only dif is the var names wierd

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles