SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 29
  1. #1
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    regarding Javascript

    Hi all, im new here, first post.
    Right Im very new to javascript and over the last 2 days iv'e just started learning; im quite chuffed with what i have done.
    http://www.tjsaynor.com/test/Start4.htm

    i know very basic at the moment. Im getting code done then ill spicen things up for the eye. Its a project for education.
    We had a table of details of 15 companies each offering overall normal cost and deductions for certain things.

    I put these in an array as we had to:
    i then made a form and when submitted a function is called passing these values, in the function calculations are worked out 1 by 1 using a for loop and at the then end of each one a document.write displays the final cost after deductions. However if you look it just displays them obviuosly in order they are prossessed! how can i then make sort into cheapest first! in the function do i need to pass these to an array to sort that as at the present all that happens is strings are created or can you sort strings? hope i make sense!

    Another question is because i use document.write > it stays in same page but loads every thing blank white and just displays them, is this all that is possoble or is there a way for some fields then to recieve them in the original display? is this down to making each result a variable which then can be read to display?

    Thanks for any help, need it LOL
    Last edited by abcdef; Nov 12, 2003 at 09:32.

  2. #2
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi abcdef,

    Yes you can sort the array.

    Instead of using document.write you could just display the results in a textarea (html, js).

  3. #3
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sweet! this sorts an array > so the output of my calculations i will have to make go into an array one by one then i can sort these! as for now i have nothing to sort apart from strings on a page using document write.

    i will create a text area for the final results and then pass the details to the fields on completion of the function! could these be passed to another html page with the layout ?
    Thanks

  4. #4
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not sure if I exactly understand... but, yes all the form controls' values can be 'submitted' to another page.

  5. #5
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    right i have successfully made an array out of the result costs!
    result.sort();
    each array has 2 elements NAME & price.
    How do i sort this into price order? what goes in the brackets?

  6. #6
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I can't access your page right now, so I can't see what you have.

    Look at the example code here. It shows how to sort numerically.

  7. #7
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    EACH ARRAY has 2 elements
    result[i].name
    result[i].price
    i need to sort the array result to organise on price!
    I cant follow the function that has to go in the brackets in the sort();
    Im trying, ill post if i get any where! hope this clears things up

  8. #8
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, I can access your page now (my puter problem - not a problem with your link), but I don't see a 'result' array. Perhaps you haven't uploaded your changes yet, but I'll make a few suggestions...

    1) totalCost could be another property of 'insurance' objects. After totalCost is calculated then...
    Code:
    company[i].totalCost = totalCost;
    2) Now sort the 'company' array based on the totalCost property. Use the example I linked to in my last post. Now it's easy to sort the company array on any of its properties, just by writing another 'sort call-back function' which is passed to company.sort(). Or, just have one call-back function and let it sort based on some flag.
    Code:
    <html>
    <head>
    <script type='text/javascript'>
    function recieveValues()
    {
      ...  
      
      company.sort(sortByCost);
      return false;
    }
    // this is the 'callback' comparison function - it is called from sort()
    function sortByCost(c1, c2)
    {
      var cost1 = parseFloat(c1.totalCost);
      var cost2 = parseFloat(c2.totalCost);
      return cost1 - cost2;
    }
    </script>
    </head>
    <body>
    </body>
    </html>
    3) Your onsubmit function needs to return false if you want to cancel the submission (which, in your case, will reload the page).
    Code:
    <html>
    <head>
    <script type='text/javascript'>
    function recieveValues()
    {
      ...  
      
      return false;
    }
    </script>
    </head>
    <body>
    
    <form onsubmit="return recieveValues(...)">
      <input type="submit" />
    </form>
    
    </body>
    </html>
    4) Get in the habit of using all lowercase for html attributes. For example 'onsubmit', 'onclick'

  9. #9
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeh i just made it do the array your way! much easier, dont know why i didnt see it! add an element!
    I were creating a new array and just putting them values in!
    Now i have adapted it !
    the array works fine, i can write and get an of the values in the totalCost in the array.
    But this sorting is still giving me problems!
    i put the function at the top with the other functions.
    then in the other function recieveValues NOT in the forloop! under that i do a comapny.sort(function)
    But problem is when this is in, it stops the script coz non of the documents writes work!
    i wanna be able to see the output of the total price in order!
    the function is there, but it cant be working when i sort or if so i cant tell because the writes stop working!

    Ill be on later tonight > off out > snooker game, wish me luck LOL

  10. #10
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    More suggestions...

    Let recieveValues() do just that - and no more. Write another function perhaps named displayCosts() (or whatever you want to call it) and let it loop thru the company array and display the results in a textarea (for example).

    The idea is to divide your project into distinct 'tasks' and write a separate function for each. Don't complicate one function with so many different tasks.

    In a very generic sense, almost all software can be divided into these tasks:

    1) get input data
    2) manipulate data
    3) do something with output data

    Each of those tasks should be implemented with their own groups of functions - and they should be quite independent of each other so that you could replace the "get data" module (group of functions) with a different module (to "get" from some other source) and not have to modify the "manip" or "output" modules.

    At any rate, that's the general idea to shoot for

  11. #11
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by abcdef
    Ill be on later tonight > off out > snooker game, wish me luck LOL
    "snooker" ? I've seen that word many times now but I haven't taken the time to find out what it means

    I'm from Alabama... you have to talk real slow to me

  12. #12
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Let's take my previous ideas even further (I'm probably getting away from your project, but this is interesting ).

    An object should have methods that allow it to be a distinct entity and encapsulate the data. For example, your 'insurance' object could have methods called getData() and showData(). Now...
    Code:
    function getAllData()
    {
      for (var i = 0; i < company.length; ++i) {
        company[i].getData(...);
      }
    }
    function showAllData()
    {
      for (var i = 0; i < company.length; ++i) {
        company[i].showData();
      }
    }
    Now we can go further and write another object which will encapsulate the array and provide the above functions as methods.

    Ok, I'll stop... just couldn't resist

  13. #13
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeh the simplicity is good,
    ill simplify it now! or try, each function doing its own thing.
    Do i pass the values from the form correctly? to start of i wanted an actual function to get the values from the form and just to call this function on submit!
    like:
    Code:
    function getDetails(){
    document.formName.fieldName.value = varaible
    etc for rest
    }
    or is the way i have it the best?

    for now though ill try and simplify the code! try
    function for calculations
    function to add new varaibles to an array
    function to then sort this array in order then display <<< yet to be achieved

    I love this learning curve!
    You have MSN at all if any easier for you?

    PS > i WON at SNOOKER, thats SNOOKER!!!!!!

    cheers once more

  14. #14
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Right just getting things working at moment and now have the sort taking place, after the array is finished with totalCost i call a function that in turn sorts it using your sample above.
    Code:
    function sortByCost(c1, c2)
    	{
     	 var cost1 = parseFloat(c1.totalCost);
     	 var cost2 = parseFloat(c2.totalCost);
     	 return cost1 - cost2;
    	}
    
    function sortArray(){
    	
       company.sort(sortByCost);
    		
       for(i=0; i<=14; i++){
    	document.write(company[i].totalCost + "<br>")
       }
    }
    This displays them now in correct order
    HOWEVER originally you put "return false" under the sort but with that there it didnt work, when removed it does! why??????

    Also can you talk me through how the sort is working! in that function sortByCost?
    My head spins when i follow it, where does c1 and c2 arguments come from? when called its just company.sort(sortByCost) shouldnt it be sortByCost(c1, c2);

    I know prob me being daft

    hey least works and sorts em

  15. #15
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's the proper way to do a custom sort function
    Code:
    Array.prototype.sortByProperty = function( prop, desc )
    {
    	return this.sort( function( a, b )
    	{
    		if ( a[prop] == b[prop] ) return 0;
    		return ( a[prop] > b[prop] )?
    			( ( desc ) ? -1 : 1 ):
    			( ( desc ) ? 1 : -1 );
    	} );
    }
     
    alert( company.sortByProperty( 'totalCost', false ) ); // ascending
    alert( company.sortByProperty( 'totalCost', true ) );  // descending
    Now, here's how sort functions work. First of all, understand that the valid argument for the Array's sort() method is a function pointer. You use a valid reference, whereas I used an anonymous function -- both essentially the same thing.

    The two parameters (c1 and c2 in yours, a and b in mine) are automatically sent, which we can capture with variables name of our choosing. The two variables are two values of the array being compared for sorting (the sorting method used is a regular bubble sort). Basically, the function we make allows us to customize the nature of the sort -- ascending, descending, sort by property, string length, last letter, whatever you can come up with (the normal sort is lexicographical: 0-9 a-z).

    For a normal, ascending sort, if a is greater than b, return -1. If b is greater than a, return 1. If both are the same, return 0. So, you should always be returning a 1, -1, or 0 from your sort function -- because the built in sort() method uses that number to know how to sort the two values.

    You mention using return false and it causing the function to not work -- it's because of what I describe in the paragraph. A false boolean value casts to 0 as an integer -- so -- by constantly returning zero, you were telling the sort() method that every two values were identical, prompting no change of order.

    Make any sense whatsoever? I really should write an article on this...

    Here's the same example I gave, but with a pointed at function, and not an anonymous one.

    Code:
    function sortByProperty( a, b )
    {
    	if ( a[prop] == b[prop] ) return 0;
    	return ( a[prop] > b[prop] )?
    		( ( desc ) ? -1 : 1 ):
    		( ( desc ) ? 1 : -1 );
    }
     
    Array.prototype.sortByProperty = function( prop, desc )
    {
    	return this.sort( sortByProperty );
    }
     
    alert( company.sortByProperty( 'totalCost', false ) ); // ascending
    alert( company.sortByProperty( 'totalCost', true ) );  // descending
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  16. #16
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In my last post the way i did it is almost the same yes?

    apart from you use:
    Code:
    array.prototype.sortByProperty = function
    and i use
    Code:
    functon sortArray(){
    
    }
    As mine works and you have explained it, i understand a little now how the sort method works!
    Is my way still ok, calling function like i have?

    Works a treat really !

  17. #17
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    im trying to create a function to display the array.name and array.totalCost to a table like format, prefreably on a different page! but how?
    i mean i created a table put how do i pass to a cell?
    i tried text area but looks ugly!

    any suggestions? just dont wanna be writing to display really using document.write().

    Cheers guys

  18. #18
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Excellent post by beetle! Thanks dude!

    abcdef, I'll get back to this as soon as I can.

  19. #19
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OK thanks,
    Just wanna display the result best i can! only simple project as you prob know by now, but want to do quite good.
    Cheers !

  20. #20
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, where are we with this one? The page online hasn't been updated has it? Please update it (or post it here) so we are both looking at and debugging the same page.

  21. #21
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok i'll upload then EDIT this post and put in a link!
    http://www.tjsaynor.com/test/Start6help.htm

    AS you see just to check there in order i write them using document.write in forloop!

    I dont wanna use that! i want to display in html nice table or summat! maybe in different html page
    Last edited by abcdef; Nov 13, 2003 at 14:49.

  22. #22
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here's one way of doing it (there are many). Since this is a school assignment I'm leaving some of this for you to figure out...
    Code:
    function sortArray()
    {
      company.sort(sortByCost);
      var s = '<table><tr><td>Company</td><td>Cost</td></tr>';
      for(i=0; i<company.length; i++) {
        s += ???; 
      }
      s += '</table>';
      document.getElementById('results').innerHTML = s;
    }

  23. #23
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    YEH, i want it that way being educational! but getting lead down the correct path is great mate ! HELPS loads, . . .

  24. #24
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Cool

    btw, I think it's better to put your entire script element in the head element - instead of in the body element.

  25. #25
    always learning . . .
    Join Date
    Nov 2003
    Location
    UK
    Posts
    821
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    really ? ok then, what about me recieving the form details! look how i do it! that ok ? or should i submit calling a function that then does this?
    PS is this DHTML ? should i get book on JS or DHTML


Bookmarks

Posting Permissions

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