SitePoint Sponsor

User Tag List

Results 1 to 15 of 15
  1. #1
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Help with Java scrips

    Hello all. I wonder how i can make the function "sistaefternamn" easier/simpler. And an explenation of the simplification would be nice. Here comes the code.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    	"http://www.w3.org/TR/html4/strict.dtd"> 
    <html>  
    <head>  
    <title>Inl&#228;mningsuppgift 4</title>  
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">  
    <script type="text/javascript">
    			
    			
    			//H&#228;r b&#246;rjar mitt JavaScript ^^
    				var fornamn = new Array();
    				// Array f&#246;r f&#246;rnamnen, First name.
    					var efternamn = new Array();
    					// Array f&#246;r efternamnen, Family name.
    						var personnummer = new Array();
    						// Array f&#246;r personnummer
    							var ar = new Array(); 
    							//Variablerna ska inneh&#229;lla de f&#246;rsta fyra siffrorna f&#246;r datum
    								var registrerade = 0; 
    								//Variabel som h&#229;ller koll p&#229; hur m&#229;nga som registrerat sig.
    									var man = 0; 
    									//Variabel som h&#229;ller koll p&#229; hur m&#229;nga m&#228;n som registrerat sig.
    										var kvinna = 0; 
    										//Variabel som h&#229;ller koll p&#229; hur m&#229;nga kvinnor som registrerat sig.
    											var aldst = 0; 
    											//Variabel som h&#229;ller koll p&#229; vem den &#228;ldsta personen &#228;r.
    												// charAt l&#229;ter mig veta vilket tal som &#228;r etta, tv&#229;a, trea osv 
    			
    			
    			
    			function GO() {
    			// denna funktionen anropar funktionerna under.
    				if (rattsymboler()) {
    				//om min funktion rattsymboler &#228;r r&#228;tt s&#229; kallar dem p&#229; dem d&#228;r under. 
    					ok();
    					
    						helaaldern();
    							skrivutinformation();
    								sistaefternamnen();
    								//denna funktionen kollar de tre sista efternamnen
    					
    					
    									}
    						}
    						
    			
    			
    			
    			function ok() { 
    			//denna funktionen g&#246;r:
    				fornamn[registrerade] = document.getElementById('FNAMN');
    				//h&#228;r kollas vad som st&#229;r i mitt formul&#228;r i f&#246;rnamn. Den kollar i en array
    					fornamn[registrerade] = fornamn[registrerade].value;
    					//V&#228;rdet i FNAMN
    						efternamn[registrerade] = document.getElementById('ENAMN');
    						//h&#228;r kollas efternamnet fr&#229;n formul&#228;ret
    							efternamn[registrerade] = efternamn[registrerade].value;
    							//v&#228;rdet i ENAMN
    								personnummer[registrerade] = document.getElementById('PNR');
    									personnummer[registrerade] = personnummer[registrerade].value;
    									//v&#228;rdet i PNR
    										registrerade++;
    										//vi har en variabel som heter r&#228;kna. Har en knapp som r&#246;knar. Tar namnet p&#229; variabeln. &#246;kar. det &#246;kar med ett. Om jag till exempel skriver sju namn och efternamn och personnummer s&#229; visar den i sidan hur m&#229;nga g&#229;nger jag skrivit in information p&#229; sidan. 
    				
    											var h1 = document.getElementById("h0");
    											// h&#228;r g&#246;r jag en ny variabel som heter h1. Den tar v&#228;rdet fr&#229;n h0
    												h1.lastChild.nodeValue = fornamn[registrerade-1] + " , du &#228;r (id) &#229;r gammal ";
    			}									//H&#228;r &#228;r det som skrevs sist i variabeln h1 som skrivs in i rubriken p&#229; hemsidan. Skriver man in ett nytt namn visas det nya namnet bara!. 
    			
    
    
    			function kollapersonnummer() {
    			//denna funktionen anropar andra funktioner som kollar mitt personnummer
    					var personnummer = "";
    					//variabeln bersonnummer = tom
    						personnummer = document.getElementById('PNR');
    						//variabeln personnummer blir till det som finns i formul&#228;ret
    							personnummer = personnummer.value;
    								if (kolladatum(personnummer) == true) {
    								//om kolladatum i personnummer &#228;r sant - 
    									if (kollaPlusEllerMinus(personnummer) == true) {
    									// och om kollaplusellerminus &#228;r r&#228;tt
    										if (kollasymboler(personnummer) == true) {
    										//och om kollasymboler &#228;r r&#228;tt 
    											return true;
    											//S&#229; &#228;r det sant och den kan g&#229; vidare. 
    																				 }
    																				   }
    																	  }
    											 }
    			
    			
    
    
    
    			function kollaPlusEllerMinus(personnummer) {
    			//denna funktionen kollar om det sjunde tecknet &#228;r ett plus eller minus
    					var number = personnummer;
    					//h&#228;r g&#246;r jag en lokal variabel som tar personnummret
    						var sign = personnummer.charAt(6);
    						//h&#228;r g&#246;rs en variabel som kollar det sjunde tecknet
    							if (sign == "-" || sign == "+") {
    							//om det sjunde tecknet &#228;r ett + eller - 
    								return true;
    								// d&#229; &#228;r det r&#228;tt
    															}
    									else {
    									//annars
    										alert("Nej nej nej, innan dina fyra sista siffror s&#229; m&#229;ste du ha ett plus eller minus");
    											return false;
    											//skriv en popup som skriver detta och g&#246;r det till fel
    										 }
    															}
    			
    			
    
    
    
    
    			function kollasymboler(personnummer) {
    				//funktionen ....
    				var number = personnummer;
    				//Variabeln nummer &#228;r det samma som arrayen personnummer
    					var code = "";
    					// det betyder att det inte st&#229;r n&#229;got i code
    						for (var i = 7; i <=10; i++) {
    							// s&#229; l&#228;nge som i &#228;r mindre eller lika med tio s&#229; plussar man p&#229; ett. 
    							code = code + personnummer.charAt(i);
    							
    													 }
    								if (!(isNaN(code))) {
    									//Om koden &#228;r ett nummer
    									if ((code.charAt(2) &#37; 2) == 1) {
    										//om siffrorna &#228;r delbara med 2 och 
    										man++;
    										//du &#228;r en man
    											else {
    												kvinna++;
    												//annars &#228;r du en kvinna
    												 }
    													return true;
    													}
    														else {
    															alert("Du har skrivit fel p&#229; dina sista fyra siffror");
    																return false;
    																//H&#228;r kommer det ut en alert som s&#228;ger att sista fyra siffrorna &#228;r fel. Den g&#246;r detta till false. 
    															 }
    													}
    			
    		
    			
    
    
    
    			function kolladatum(personnummer) {
    				var date = "";
    					var number = personnummer;
    						for (var i = 0; i <=5; i++) {
    							date = date + personnummer.charAt(i);
    													}
    								if (!(isNaN(date))) {
    									return true;
    													}
    										else {
    											alert("Du har skrivit fel p&#229; dina f&#246;rsta sex siffror ");
    												return false;
    											 }
    											  }
    			
    
    
    
    
    			function kollaar(temp) {
    				if (personnummer[registrerade-1].charAt(0) != 0) {
    					temp = (personnummer[registrerade-1].charAt(0) + personnummer[registrerade-1].charAt(1));
    																 }
    						else {
    							temp = personnummer[registrerade-1].charAt(1);
    							 }
    								return temp;
    									}
    			
    			
    
    
    
    
    			function skrivutinformation() {
    			//denna funktionen skriver ut funktionen skrivutalder och annat som beskrivs under
    				skrivutalder();			
    					var p0 = document.getElementById("p0");
    					// jag g&#246;r en variabel som &#228;r p0 och som tar det som st&#229;r i mitt p0 ID
    						p0.lastChild.nodeValue = "Antalet registrerade m&#228;n: " + man;
    						//
    							var p1 = document.getElementById("p1");
    								p1.lastChild.nodeValue = "Antalet registrerade kvinnor: " + kvinna;
    									var p4 = document.getElementById("p4");
    									// denna variabeln tar det som st&#229;r i ID't p4
    										p4.lastChild.nodeValue = fornamn[aldst] + " " + efternamn[aldst] + " du &#228;r " + ar[aldst] + " &#229;r och &#228;ldst bland de registrerade.";
    				
    										  }
    				
    				
    				
    				
    				
    
    
    				function skrivutalder() {
    				var temp = fornamn[registrerade-1] + ", du &#228;r " + ar[registrerade-1] + " &#229;r gammal. ";
    					if (ar[registrerade-1] == 17) {
    						temp = temp + "Du &#228;r snart vuxen!!!"
    				
    												  }
    							else if (ar[registrerade-1] >= 65) {
    								temp = temp + "Du &#228;r pension&#228;r!!!";
    				
    																}
    									else if (ar[registrerade-1] > 10 && ar[registrerade-1] < 13) {
    										temp = temp + "Du &#228;r snart ton&#229;ring!!!";
    																								 }
    											else {
    												temp = temp;
    												 }
    													var h1 = document.getElementById("h0");
    														h1.lastChild.nodeValue = temp;
    									}
    			
    			
    
    
    
    
    			function sistaefternamnen() {
    				var temp = "";
    					for (var i = 1; i < 4; i++) {
    							if ((registrerade-i) == 0 || i == 3 && (registrerade-i) >= 0) {
    								temp = temp + efternamn[registrerade-i];
    																						  }
    									else if ((registrerade-i) > 0) {
    										temp = temp + efternamn[registrerade-i] + ", ";
    																   }
    											else {
    												break;
    												 }
    												}
    													var tempP = document.getElementById('p3');
    														tempP.lastChild.nodeValue = temp;
    										}
    				
    		
    			
    			
    
    			function artonhundratalet(temp) {
    				var tTemp = temp;
    					if (tTemp <= 9) {
    						ar[registrerade-1] = 100 + 9 - tTemp;
    									}
    							else{
    								ar[registrerade-1] = ((200-tTemp) + 9);
    								}
    									if (ar[registrerade-1] >= ar[aldst]) {
    										aldst = registrerade-1
    																		 }
    											 }
    			
    
    
    
    
    			function nittonhundratalet(temp) {
    				var tTemp = temp;
    					if (tTemp <= 9) {
    						ar[registrerade-1] = 9 - tTemp;
    									}
    							else{
    								ar[registrerade-1] = ((100-tTemp) + 9);
    								}
    									if (ar[registrerade-1] >= ar[aldst]) {
    										aldst = registrerade-1
    																		 }
    											 }
    
    
    
    			 function helaaldern() {
    				var temp = 0;
    					temp = kollaar(temp);
    						temp = parseInt(temp);
    							var sign = (personnummer[registrerade-1].charAt(6));
    								if (sign == "-") {
    									//om det &#228;r ett minus
    									nittonhundratalet(temp);
    									//anv&#228;nd nittonhundratalet
    												 }
    										else {
    											artonhundratalet(temp);
    											//annars anv&#228;nd artonhundratalet
    											 }
    									}
    				
    
    
    
    			function rattsymboler() {
    				var temp = document.getElementById('FNAMN');
    				//h&#228;r g&#246;r jag en tempor&#228;r variabel som tar efelentet f&#246;rnamn 
    					var temp2 = document.getElementById('ENAMN');
    					//samma sak fast med efternamn
    						if ((isNaN(temp.value)) && (isNaN(temp2.value))) {
    							//om temp inte &#228;r ett tal och temp2 inte &#228;r ett tal
    							var temp3 = document.getElementById('PNR');
    							//samma som temp 1 och 2.
    								if (temp3.value.length == 11) {
    									//Kolla hur l&#229;ngt det &#228;r
    									if (kollapersonnummer()) {
    										//om det i kollapersonnummer
    										return true;
    										//g&#246;r det till r&#228;tt
    															 }
    															  }
    											else {
    												alert("Ditt personnummer &#228;r inte r&#228;tt!!!");
    													return false;
    													// annars skirv alerten som s&#228;ger det som st&#229;r och g&#246;r det till false
    												 }
    																		  }
    														else {
    															alert("Ditt namn och/eller efternamn &#228;r felskrivet");
    																return false;
    																//annars skriv alerten som s&#228;ger det som st&#229;r och g&#246;r det till false
    															 }
    									}
    			
    			
    			
    			
    </script>
    </head>  
    <body>  
    <h1>Registrering</h1>
    	<form action="#" method="post">
    		<fieldset>
    			<legend>Personuppgifter</legend>
    
    				<label for="FNAMN">F&#246;rnamn:</label>
    					<input type="text" id="FNAMN"><br>
    						<label for="ENAMN">Efternamn:</label>
    							<input type="text" id="ENAMN"><br>
    								<label for="PNR">Personnummer:</label>
    									<input type="text" id="PNR"><br>
    										<input type="button" id="sendButton" value="Spara" onclick="GO();">
    
    		</fieldset>
    </form>
    	<h1 id="h0">...</h1>
    		<p id="p0">Antalet registrerade m&#228;n: 0</p>
    			<p id="p1">Antalet registrerade kvinnor: 0</p>
    				<p id="p2">De tre senaste registrerade heter i efternamn: </p>
    					<p id="p3">ingen registrerad</p>
    
    						<p id="p4">Det finns ingen registrerad.</p>
    </body> 
    </html>
    Last edited by ralph.m; Aug 9, 2010 at 07:40. Reason: code tags added.

  2. #2
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can you post the code correctly indented? It's running outside the box, and much of it appears to be indented without good reason. It's very difficult to read this way.

  3. #3
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    	"http://www.w3.org/TR/html4/strict.dtd"> 
    <html>  
    <head>  
    <title>Inlämningsuppgift 4</title>  
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">  
    <script type="text/javascript">
    			
    			
    			
        var fornamn = new Array();
        var efternamn = new Array();
        var personnummer = new Array();
        var ar = new Array(); 
        var registrerade = 0; 
        var man = 0; 
        var kvinna = 0; 
        var aldst = 0; 
    
        function GO() {
    	if (rattsymboler()) {
    	    ok();
    	    helaaldern();
    	    skrivutinformation();
    	    sistaefternamnen();
    	
    					
    				}
    			}
    						
    		
    	function ok() { 
    	    fornamn[registrerade] = document.getElementById('FNAMN');
    	    fornamn[registrerade] = fornamn[registrerade].value;
    	    efternamn[registrerade] = document.getElementById('ENAMN');
    	    efternamn[registrerade] = efternamn[registrerade].value;
    	    personnummer[registrerade] = document.getElementById('PNR');
    	    personnummer[registrerade] = personnummer[registrerade].value;
    	    registrerade++;
                var h1 = document.getElementById("h0");
    	    h1.lastChild.nodeValue = fornamn[registrerade-1] + " , du är (id) år gammal ";
    			}
    			
    
    
    	function kollapersonnummer() {
    		var personnummer = "";
    		personnummer = document.getElementById('PNR');
    		personnummer = personnummer.value;
    		if (kolladatum(personnummer) == true) {
    		    if (kollaPlusEllerMinus(personnummer) == true) {
    			if (kollasymboler(personnummer) == true) {
    		return true;
    										 }
    									 }
    						 }
    				 }
    			
    			
    
    
    
    	function kollaPlusEllerMinus(personnummer) {
                var number = personnummer;
                var sign = personnummer.charAt(6);
    		if (sign == "-" || sign == "+") {
    		    return true;
    								
    				}
    		else {
    		    alert("Nej nej nej, innan dina fyra sista siffror så måste du ha ett plus eller minus");
    		    return false;
    			 }
    															}
    			
        function kollasymboler(personnummer) {
    	var number = personnummer;
    	var code = "";
    	for (var i = 7; i <=10; i++) {
    	    code = code + personnummer.charAt(i);
    			 }
    	if (!(isNaN(code))) {
    	    if ((code.charAt(2) % 2) == 1) {
    		man++;
    										
    	    else {
    	        kvinna++;
    												
    		 }
    		return true;
    			}
    	    else {
    		alert("Du har skrivit fel på dina sista fyra siffror");
    		return false;
    													
    			 }
    		}
    
        function kolladatum(personnummer) {
    	var date = "";
    	var number = personnummer;
    	for (var i = 0; i <=5; i++) {
    	    date = date + personnummer.charAt(i);
    							}
    		if (!(isNaN(date))) {
    		   return true;
    					}
    		else {
    		   alert("Du har skrivit fel på dina första sex siffror ");
    		   return false;
    			}
    		 }
    			
        function kollaar(temp) {
    	if (personnummer[registrerade-1].charAt(0) != 0) {
    	   temp = (personnummer[registrerade-1].charAt(0) + personnummer[registrerade-1].charAt(1));
    						 }
    	else {
    	    temp = personnummer[registrerade-1].charAt(1);
    							 }
    	    return temp;
    		}
    			
        function skrivutinformation() {
    	skrivutalder();			
    	var p0 = document.getElementById("p0");
    	p0.lastChild.nodeValue = "Antalet registrerade män: " + man;
            var p1 = document.getElementById("p1");
    	p1.lastChild.nodeValue = "Antalet registrerade kvinnor: " + kvinna;
    	var p4 = document.getElementById("p4");
    	p4.lastChild.nodeValue = fornamn[aldst] + " " + efternamn[aldst] + " du är " + ar[aldst] + " år och äldst bland de registrerade.";
    		 }
    				
        function skrivutalder() {
    	var temp = fornamn[registrerade-1] + ", du är " + ar[registrerade-1] + " år gammal. ";
    	if (ar[registrerade-1] == 17) {
    	    temp = temp + "Du är snart vuxen!!!"
    	else if (ar[registrerade-1] >= 65) {
    	    temp = temp + "Du är pensionär!!!";
    	    }
    	else if (ar[registrerade-1] > 10 && ar[registrerade-1] < 13) {
    	    temp = temp + "Du är snart tonåring!!!";
    		 }
    	else {
    	    temp = temp;
    	 }
    	    var h1 = document.getElementById("h0");
    	    h1.lastChild.nodeValue = temp;
             }
    			
        function sistaefternamnen() {
    	var temp = "";
    	for (var i = 1; i < 4; i++) {
    	    if ((registrerade-i) == 0 || i == 3 && (registrerade-i) >= 0) {
    		temp = temp + efternamn[registrerade-i];
    		 }
    	    else if ((registrerade-i) > 0) {
    		temp = temp + efternamn[registrerade-i] + ", ";
    				 }
    	    else {
    		break;
    			}
    		}
    													                var tempP = document.getElementById('p3');
    		tempP.lastChild.nodeValue = temp;
    		}
    				
        function artonhundratalet(temp) {
            var tTemp = temp;
    	if (tTemp <= 9) {
    	    ar[registrerade-1] = 100 + 9 - tTemp;
    		}
    	else{
    	    ar[registrerade-1] = ((200-tTemp) + 9);
    								}
    		if (ar[registrerade-1] >= ar[aldst]) {
    		    aldst = registrerade-1
    			 }
    		 }
    	function nittonhundratalet(temp) {
    	    var tTemp = temp;
    		if (tTemp <= 9) {
    		    ar[registrerade-1] = 9 - tTemp;
    			}
    		else{
    		    ar[registrerade-1] = ((100-tTemp) + 9);
    								}
    		if (ar[registrerade-1] >= ar[aldst]) {
    		    aldst = registrerade-1
    			}
    		 }
        function helaaldern() {
    	var temp = 0;
    	temp = kollaar(temp);
    	temp = parseInt(temp);
    	var sign = (personnummer[registrerade-1].charAt(6));
    	    if (sign == "-") {
    		 }
    	    else {
    		artonhundratalet(temp);
    	 }
    }
    				
        function rattsymboler() {
    	var temp = document.getElementById('FNAMN');
    	var temp2 = document.getElementById('ENAMN');
    	if ((isNaN(temp.value)) && (isNaN(temp2.value))) {
    	    var temp3 = document.getElementById('PNR');
    	    if (temp3.value.length == 11) {
    		if (kollapersonnummer()) {
    		    return true;
    			 }
    		  }
    		else {
    		alert("Ditt personnummer är inte rätt!!!");
    			return false;
    				 }
    			 }
    														else {
    	    alert("Ditt namn och/eller efternamn är felskrivet");
    	    return false;
    															 }
    	}
    			
    			
    			
    			
    </script>
    </head>  
    <body>  
    <h1>Registrering</h1>
    	<form action="#" method="post">
    	<fieldset>
    	<legend>Personuppgifter</legend>
    
    	<label for="FNAMN">Förnamn:</label>
    	<input type="text" id="FNAMN"><br>
    	<label for="ENAMN">Efternamn:</label>
    	<input type="text" id="ENAMN"><br>
    	<label for="PNR">Personnummer:</label>
    	<input type="text" id="PNR"><br>
    	<input type="button" id="sendButton" value="Spara" onclick="GO();">
    
    </fieldset>
    </form>
    	<h1 id="h0">...</h1>
    	<p id="p0">Antalet registrerade män: 0</p>
            <p id="p1">Antalet registrerade kvinnor: 0</p>
    	<p id="p2">De tre senaste registrerade heter i efternamn: </p>
    	<p id="p3">ingen registrerad</p>
            <p id="p4">Det finns ingen registrerad.</p>
    </body> 
    </html>

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,712
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by slugisen View Post
    I wonder how i can make the function "sistaefternamn" easier/simpler.
    It appears that the sistaefternamnen() function takes efternamn which might contain

    ['Wilkins', 'Williams', 'Wilson', 'Woodburn', 'Woolsworth']

    and shows the first three items, reversed, resulting in:

    Wilson, Williams, Wilkins

    You're right; there are easier ways to go about that:

    Code javascript:
    function sistaefternamnen() {
        var temp = efternamn.splice(0, 3).reverse().join(', ');
        document.getElementById('p3').lastChild.nodeValue = temp;
    }

    Quote Originally Posted by slugisen View Post
    And an explenation of the simplification would be nice.
    The splice(0, 3) part limits the array to only the first three items. If there are less than three items then the array just stays the same.

    The reverse() method reverses the resulting array.

    The join(', ') part makes use of some useful properties of the join() method
    • Where the array is empty, it just returns an empty string
    • Where one item is in the array, only that item is returned
    • Where multiple items are in the array, a separator is used
    Last edited by paul_wilkins; Aug 12, 2010 at 06:26.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You could also simplify kollapersonnummer():
    Code JavaScript:
    function kollapersonnummer() {
        var personnummer = document.getElementById('PNR').value;
        if (kolladatum(personnummer) &&
                kollaPlusEllerMinus(personnummer) &&
                kollasymboler(personnummer)) {
            return true;
        }
        else return false;
    Explanation:
    1. You can set personnummer all in one line. You don't need to declare it, get the element, then get the value in three separate steps. However, if doing so makes the code more readable to you, then it's OK to do it your way, as long as you keep in mind that you're making your JS code longer than it needs to be.
    2. Your nested if statements can be combined, making for simpler code. I spread the if statement onto multiple lines for easier viewing on the forum, but in actual code, I'd likely write it on one line.
    3. Saying
      Code JavaScript:
      if(something == true)
      is equivalent to
      Code JavaScript:
      if(something)
      except where the value of something could be either true or another value interpreted as true in a boolean context. Generally speaking, if a function returns a boolean, it should only return a boolean. Thus, you should be able to shorten and simplify your code.
    4. Your code returned true if all the conditions applied, and nothing otherwise. I'm guessing that JS functions have some sort of default return value (possibly undefined), but it's best if you're writing a function that returns a boolean to make sure it always returns a boolean.

  6. #6
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for the answers. realy helpful. I apreciate it. Thank you again =)

  7. #7
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for the help. But i just noticed that it dosen't show all the names, just the first one, then colen comes

    Example

    Jhonson, ,

    or sometimes
    , jhonson ,

    It would be very useful it this would work like i want it to. It's suposed to put a new last name after you press ok. It's suposed 2 do it all the time. :P. You can see what i mean if you test my code.



    Quote Originally Posted by pmw57 View Post
    It appears that the sistaefternamnen() function takes efternamn which might contain

    ['Wilkins', 'Williams', 'Wilson', 'Woodburn', 'Woolsworth']

    and shows the first three items, reversed, resulting in:

    Wilson, Williams, Wilkins

    You're right; there are easier ways to go about that:

    Code javascript:
    function sistaefternamnen() {
        var temp = efternamn.splice(0, 3).reverse().join(', ');
        document.getElementById('p3').lastChild.nodeValue = temp;
    }



    The splice(0, 3) part limits the array to only the first three items. If there are less than three items then the array just stays the same.

    The reverse() method reverses the resulting array.

    The join(', ') part makes use of some useful properties of the join() method
    • Where the array is empty, it just returns an empty string
    • Where one item is in the array, only that item is returned
    • Where multiple items are in the array, a separator is used

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,712
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by slugisen View Post
    It's suposed to put a new last name after you press ok. It's suposed 2 do it all the time. :P. You can see what i mean if you test my code.
    My apologies, it is quite tricky to interpret what your code is supposed to do, due to its heavy reliance global variables, and that the functions accept no parameters.

    Would you like to provide us with a clearer understanding of how the sistaefternamnen function is supposed to work?

    Is it feasable for us to rewrite that part of your assignment so that it doesn't rely on globals or other troubling issues?
    Last edited by paul_wilkins; Aug 13, 2010 at 19:10.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  9. #9
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Simply put every time you klick on ok a person is registerd. the function sistaefternamn is suposed to show the three last last names of the people that registerd. an example:

    i registerd three people, Willson, Jhonson, Anderson,
    so the thext shows these names.
    but if i register one more person that's maybe named Smith. Then the text should show: Jhonson, Anderson, Smith

    Hope i clarified the issue for you =)


    Quote Originally Posted by pmw57 View Post
    My apologies, it is quite tricky to interpret what your code is supposed to do, due to its heavy reliance global variables, and that the functions accept no parameters.

    Would you like to provide us with a clearer understanding of how the sistaefternamnen function is supposed to work?

    Is it feasable for us to rewrite that part of your assignment so that it doesn't rely on globals or other troubling issues?

  10. #10
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,712
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by slugisen View Post
    the function sistaefternamn is suposed to show the three last last names of the people that registerd
    Quote Originally Posted by slugisen View Post
    It's suposed to put a new last name after you press ok. It's suposed 2 do it all the time.
    Here's an update that should do what you require.

    Code javascript:
    function sistaefternamnen() {
        var temp = efternamn.slice(-3).reverse().join(', ');
        document.getElementById('p3').lastChild.nodeValue = temp;
    }

    This uses the slice() method which creates a cloned copy, of the last three items in this case, so that we can then reverse and joined together those items without affecting your global array.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  11. #11
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,712
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    After reworking the code in different ways (many thanks to Google translate), I wind up with a few objects called registration and validatePersonalId, a constructor called Person, and a function called luhnChecksum.

    The luhnChecksum is for the personal identification number, which uses the luhn algorithm to check if the number is correct.

    Here's the restructured code.

    Code javascript:
    function luhnChecksum (digits) {
        // a simple checksum formula used to validate a variety of identification numbers
        var sum, i, digit;
        digits = digits.toString();
        sum = 0;
        for (i = 0; i < digits.length; i += 1) {
            digit = parseInt(digits[i], 10);
            sum += (i &#37; 2) ? digit : (digit > 4) ? digit * 2 % 10 + 1 : digit * 2;
        }
        return (sum % 10) === 0;
    }
     
    var validatePersonalId = {
        checkDate: function (personalId) {
            var date = personalId.substring(0, 6);
            if (!(isNaN(date))) {
                return true;
            } else {
                alert("The first six digits are the date of birth (yymmdd).");
            }
            return false;
        },
        checkPlusOrMinus: function (personalId) {
            var sign = personalId.charAt(6);
            if (sign !== "-" && sign !== "+") {
                alert("The last four digits must come after a plus or minus sign.");
            } else {
                return true;
            }
            return false;
        },
        checkSymbols: function (personalId) {
            var checksum = luhnChecksum(personalId.slice(0, 6) + personalId.slice(-4));
            if (!checksum) {
                alert("The personal identification number has the wrong checksum.");
            } else {
                return true;
            }
            return false;
        },
        check: function (personalId) {
            if (personalId.length !== 11) {
                alert("The personal identification should be the following format: yymmdd-nnnn");
                return false;
            }
            if (this.checkDate(personalId) && this.checkPlusOrMinus(personalId) && this.checkSymbols(personalId)) {
                return true;
            }
            return false;
        }
    };
     
    function Person (firstname, lastname, personalId) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.personalId = personalId;
        this.isValid = true;
        this.isValid &= function validNames(firstname, lastname) {
            if (!isNaN(firstname) || !isNaN(lastname)) {
                alert("Your first name and/or last name is missing");
            } else {
                return true;
            }
        }(this.firstname, this.lastname);
        this.isValid &= validatePersonalId.check(this.personalId);
     
        function yearsSince(year, month, day) {
            var then = new Date(year, month, day);
            var now = new Date();
            var diff = new Date(now - then);
            return diff.getYear() - new Date(0).getYear();
        }
        this.age = function calculateAge (personalId) {
            var parts = /(\d\d)(\d\d)(\d\d)([+\-])/.exec(personalId);
            var age = yearsSince(parts[1], parts[2], parts[3]);
            var sign = parts[4];
            if (sign === "+") {
                age += 100;
            }
            return age;
        }(this.personalId);
     
        this.sex = personalId.charAt(9) % 2 ? 'male' : 'female';
    }
     
    registration = {
        people: [],
        calculateOldest: function () {
            var i, oldest;
            oldest = this.people[0];
            for (i = 0; i < this.people.length; i += 1) {
                if (this.people[i].age > oldest.age) {
                    oldest = this.people[i];
                }
            }
            this.oldest = oldest;
        },
        add: function (person) {
            this.people.push(person);
            this.calculateOldest();
        },
        numberOfMen: function () {
            var i, count;
            count = 0;
            for (i = 0; i < this.people.length; i += 1) {
                if (this.people[i].sex === 'male') {
                    count += 1;
                }
            }
            return count;
        },
        numberOfWomen: function () {
            var i, count;
            count = 0;
            for (i = 0; i < this.people.length; i += 1) {
                if (this.people[i].sex === 'female') {
                    count += 1;
                }
            }
            return count;
        },
        mostRecent: function () {
            var recent, lastnames, i;
            recent = this.people.slice(-3).reverse();
            lastnames = [];
            for (i = 0; i < recent.length; i += 1) {
                lastnames.push(recent[i].lastname);
            }
            return lastnames.join(', ');
        },
        showAge: function (firstname, age) {
            var text = firstname + ", you are " + age + " years old. ";
            if (age === 17) {
                text += "You will soon be an adult!!!";
            } else if (age >= 65) {
                text += "You are retired!!!";
            } else if (age > 10 && age < 13) {
                text += "You are soon a teen!!!";
            }
            document.getElementById("h0").lastChild.nodeValue = text;
        },
        showInformation: function (person) {
            this.showAge(person.firstname, person.age);
            document.getElementById("p0").lastChild.nodeValue = "The number of registered men: " + this.numberOfMen();
            document.getElementById("p1").lastChild.nodeValue = "The number of registered women: " + this.numberOfWomen();
            document.getElementById('p3').lastChild.nodeValue = this.mostRecent();
            document.getElementById("p4").lastChild.nodeValue =  this.oldest.firstname + " " + this.oldest.lastname + " you are " + this.oldest.age + " years and the oldest among those registered.";
        },
        addFromForm: function () {
            var person = new Person(
                document.getElementById('FNAME').value,
                document.getElementById('LNAME').value,
                document.getElementById('PNR').value
            );
            if (person.isValid) {
                registration.add(person);
                registration.showInformation(person);
            }
            return false;
        }
    };
     
    document.getElementById('registration').onsubmit = registration.addFromForm;

    The HTML is not very much different. Only the ID attribute on the form, and placing the script at the end.

    Code html4strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" 
    	"http://www.w3.org/TR/html4/strict.dtd"> 
    <html>  
    <head>  
    <title>Assignment 4</title>  
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">  
    </head>  
    <body>  
    <h1>Registration</h1>
    <form id="registration" method="post" action="#">
        <fieldset>
            <legend>Personal Information</legend>
            <label for="FNAME">First Name:</label>
            <input type="text" id="FNAME" value="Paul"><br>
            <label for="LNAME">Last Name:</label>
            <input type="text" id="LNAME" value="Wilkins"><br>
            <label for="PNR">Personal ID:</label>
            <input type="text" id="PNR" value="740104-1234"><br>
            <input type="submit" value="Submit">
        </fieldset>
    </form>
        <h1 id="h0">...</h1>
        <p id="p0">The Number of registered male: 0</p>
        <p id="p1">The number of registered women: 0</p>
        <p id="p2">The last three people registered by last name: </p>
        <p id="p3">Number registered</p>
        <p id="p4">There is no registration.</p>
    <script type="text/javascript" src="registration-oo.js"></script>
    </body> 
    </html>
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  12. #12
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you so much. This was exactly what i needed. I cant understand why you put so much effort into this but I realy apreciate it. I see that you have a lot of skills in web development. If I ever have some trouble or need someone to do a job for me privately or when i have a job and my boss asks me to find someone who can do a job for us. I would gladly recomend you =)

  13. #13
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,712
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by slugisen View Post
    Thank you so much. This was exactly what i needed. I cant understand why you put so much effort into this but I realy apreciate it.
    One reason why is that it helps me to improve. While doing it I noticed that there are other things that I would also improve on too. Despite that though, the code is close enough to the original structure of the code, which makes comparisons between them easier to perform.

    The new code was arrived at by noting down the global variables that the functions depended on, and then gradually reworking things until the globals were corralled to just a few main areas. That's when the object oriented work began, which resulted in what you see here.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  14. #14
    SitePoint Member
    Join Date
    Aug 2010
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you. I'm done with this thread =). An administrator can delete it if he wants.

  15. #15
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,712
    Mentioned
    102 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by slugisen View Post
    Thank you.
    You're very welcome.

    Quote Originally Posted by slugisen View Post
    I'm done with this thread =). An administrator can delete it if he wants.
    Threads are not normally closed here, which allows others to add to them if they have anything else to say.
    Last edited by paul_wilkins; Aug 14, 2010 at 13:48.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


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
  •