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

    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);

    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++)
    average = total / 5;

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

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



    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)
    alert("Please enter a number for Length and width");
    return false;
    else if(isNaN(textbox.value))
    alert("Text box does not contain a number");
    return false;
    else if(textbox.value<=0 || textbox.value>50)
    alert("Number must be between 1 and 50");
    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";


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

    addItemToShoppingList(length, width);

    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

    //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(){


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

    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);

    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;
    else if(item=="Maple"){
    else if(item=="Tile"){


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


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

  2. #2
    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

    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.

  3. #3
    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:
    	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:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    	content="text/html; charset=utf-8"
    	Size and Material Calculator
    <form action="#" id="process">
    		Size and Material Calculator
    	<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 id="materials">
    		<legend>Choose your Material</legend>
    		<label for="materialBeech">Beech</label>
    		<br />
    		<label for="materialMaple">Maple</label>
    		<br />
    		<label for="materialTile">Tile</label>
    		<br />
    		<label for="materialLaminate">Laminate</label>
    	<div id="submitsAndHiddens">
    		<input type="submit" value="calculate" />
    <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 = '';
    		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
    	function radioValue(id, name) {
    			radioSet = d.getElementById(id),
    			radioList = radioSet.getElementsByTagName('input'),
    		for (t = 0; t < radioList.length; t++) {
    			if (
    				(radioList[t].type == 'radio') &&
    			) {
    				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) {
    			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;
    			area = length * width,
    			packs = Math.ceil(area / 2),
    			wholeCost = packs * material.cost;
    			"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 + "."
    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.

  4. #4
    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.

  5. #5
    Join Date
    May 2014
    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


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

  7. #7
    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)


    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


    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.

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

    2nd quote THANKS

    3rd quote
    heres a copy

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

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

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

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

    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
    so essentially keeping them as they are any tips on getting them to work?

  10. #10
    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.

    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');
    for (var i = 0; i < num.length; i++){
    		'<br>' + numList[i] + ' cubed is ' + Math.pow(numList[i], 3)
    	'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...

  11. #11
    Join Date
    May 2014
    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
    just tried this code it didn't work

  13. #13
    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++) {

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

  15. #15
    Join Date
    May 2014
    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



X vBulletin 4.2.2 Debug Information

  • Page Generation 0.12422 seconds
  • Memory Usage 3,056KB
  • Queries Executed 15 (?)
More Information
Template Usage (37):
  • (1)ad_footer_end
  • (1)ad_footer_start
  • (1)ad_global_above_footer
  • (1)ad_global_below_navbar
  • (1)ad_global_header1
  • (1)ad_global_header2
  • (1)ad_navbar_below
  • (1)ad_showthread_firstpost_sig
  • (1)ad_showthread_firstpost_start
  • (1)ad_thread_first_post_content
  • (1)ad_thread_last_post_content
  • (4)bbcode_code
  • (5)bbcode_quote
  • (1)footer
  • (1)forumjump
  • (1)forumrules
  • (1)gobutton
  • (1)header
  • (1)headinclude
  • (1)headinclude_bottom
  • (15)memberaction_dropdown
  • (1)navbar
  • (4)navbar_link
  • (1)navbar_moderation
  • (1)navbar_noticebit
  • (1)navbar_tabs
  • (2)option
  • (1)pagenav
  • (1)pagenav_curpage
  • (1)pagenav_pagelink
  • (15)postbit
  • (15)postbit_onlinestatus
  • (15)postbit_wrapper
  • (1)spacer_close
  • (1)spacer_open
  • (1)tagbit_wrapper 

Phrase Groups Available (6):
  • global
  • inlinemod
  • postbit
  • posting
  • reputationlevel
  • showthread
Included Files (26):
  • ./showthread.php
  • ./global.php
  • ./includes/class_bootstrap.php
  • ./includes/init.php
  • ./includes/class_core.php
  • ./includes/config.php
  • ./includes/functions.php
  • ./includes/functions_navigation.php
  • ./includes/class_friendly_url.php
  • ./includes/class_hook.php
  • ./includes/class_bootstrap_framework.php
  • ./vb/vb.php
  • ./vb/phrase.php
  • ./includes/functions_facebook.php
  • ./includes/functions_calendar.php
  • ./includes/functions_bigthree.php
  • ./includes/class_postbit.php
  • ./includes/class_bbcode.php
  • ./includes/functions_reputation.php
  • ./includes/functions_notice.php
  • ./packages/vbattach/attach.php
  • ./vb/types.php
  • ./vb/cache.php
  • ./vb/cache/db.php
  • ./vb/cache/observer/db.php
  • ./vb/cache/observer.php 

Hooks Called (75):
  • init_startup
  • friendlyurl_resolve_class
  • init_startup_session_setup_start
  • database_pre_fetch_array
  • database_post_fetch_array
  • init_startup_session_setup_complete
  • global_bootstrap_init_start
  • global_bootstrap_init_complete
  • cache_permissions
  • fetch_postinfo_query
  • fetch_postinfo
  • fetch_threadinfo_query
  • fetch_threadinfo
  • fetch_foruminfo
  • load_show_variables
  • load_forum_show_variables
  • global_state_check
  • global_bootstrap_complete
  • global_start
  • style_fetch
  • global_setup_complete
  • showthread_start
  • showthread_getinfo
  • strip_bbcode
  • friendlyurl_clean_fragment
  • friendlyurl_geturl
  • forumjump
  • cache_templates
  • cache_templates_process
  • template_register_var
  • template_render_output
  • fetch_template_start
  • fetch_template_complete
  • parse_templates
  • fetch_musername
  • notices_check_start
  • notices_noticebit
  • process_templates_complete
  • friendlyurl_redirect_canonical
  • showthread_post_start
  • showthread_query_postids
  • showthread_query
  • bbcode_fetch_tags
  • bbcode_create
  • showthread_postbit_create
  • postbit_factory
  • postbit_display_start
  • postbit_imicons
  • bbcode_parse_start
  • bbcode_parse_complete_precache
  • bbcode_parse_complete
  • postbit_display_complete
  • memberaction_dropdown
  • pagenav_page
  • pagenav_complete
  • tag_fetchbit
  • tag_fetchbit_complete
  • forumrules
  • navbits
  • navbits_complete
  • build_navigation_data
  • build_navigation_array
  • check_navigation_permission
  • process_navigation_links_start
  • process_navigation_links_complete
  • set_navigation_menu_element
  • build_navigation_menudata
  • build_navigation_listdata
  • build_navigation_list
  • set_navigation_tab_main
  • set_navigation_tab_fallback
  • navigation_tab_complete
  • fb_like_button
  • showthread_complete
  • page_templates