SitePoint Sponsor

User Tag List

Results 1 to 22 of 22
  1. #1
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)

    Text Validation Not Working

    Alrighty then!

    I'm trying to create a simple form. The user enters a string of text, presses a button, and the JavaScript validation script does its magic, then an alert pops-up on screen to tell the user they're correct. It isn't working. I've tried various alternatives with names, ids, changing stuff around and so on. Yet, I also have an age validation script and that works fine, I've tried making the text validation into an age validation, but it doesn't work. So it must be something with the form...? I've added both the working age validation and the not-currently-working text validation. Please, if you can (and I know you can!), help me. I've got Head First JavaScript, DOM Scripting, Simply JavaScript, and JavaScript: The Good Parts sprawled on my bed and I've been through them with nothing to help me. Otherwise, I've missed a page or something!

    Text Validation, HTML (quick-question.html)

    HTML Code:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8">
    		<title>Quick Question</title>
    		<link rel="stylesheet" media="screen" href="quick-question.css">
    	</head>
    
    	<body>
    		<div class="quick-question">
    			<p class="header">Quick Question</p>
    
    			<p class="question">Who invented the World Wide Web?</p>
    
    			<form name="question-1" method="post" action="#">
    				<label for="answer">Answer:</label>
    				<input type="text" value="" id="answer-1" name="answer-1" class="required" />
    				<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
    			</form>
    		</div>
    
    		<script src="quick-question.js"></script>
    	</body>
    </html>
    Text Validation, JavaScript (quick-question.js)

    Code:
    function addLoadEvent(func) {
    	var oldonload = window.onload;
    	if (typeof window.onload != 'function') {
    		window.onload = func;
    	} else {
    		window.onload = function() {
    			oldonload();
    			func();
    		}
    	}
    }
    
    function fnAnswers() {
    	if (!document.getElementById) return false;
    
    	// Answer Area
    
    	var answerArea = document.question-1.answer-1.value;
    
    	// Answer Variables
    
    	var ansOne = "Tim Berners-Lee";
    
    	// Question & Answer Logic
    
    	if (answerArea == ansOne) {
    		alert("Correct!");
    	}
    }
    
    function fnSubmitAnswer() {
    	if (!document.getElementById) return false;
    	var btnSubmit = document.getElementById("btnSubmit");
    	btnSubmit.onclick = fnAnswers;
    }
    
    addLoadEvent(fnSubmitAnswer);
    And, as I said, the working age validation:

    Age Validation, HTML (age-checker.html)

    HTML 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">
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    		<title>Age Checker</title>
    		<link rel="stylesheet" type="text/css" media="screen" href="stylesheet.css" />
    		<script type="text/javascript" src="age-checker.js"></script>
    	</head>
    
    	<body>
    		<div id="wrapper">
    			<h1>Age Checker</h1>
    
    			<p>Type your age in the form field below. You will receive a different popup alert depending 
    			on your age. If you are younger than 18 years old then you will be warned however, if you are
    			 older than 18 then you will be welcomed. Try it!</p>
    
    			<form name="myform">
    				<input type="text" name="myagefield" id="myagefield" value="" />
    				<input type="button" name="btnClick" id="btnClick" value="Click" />
    			</form>
    		</div>
    	</body>
    </html>
    Age Validation, JavaScript (age-checker.js)

    Code:
    function addLoadEvent(func) {
    	var oldonload = window.onload;
    	if (typeof window.onload != 'function') {
    		window.onload = func;
    	} else {
    		window.onload = function() {
    			oldonload();
    			func();
    		}
    	}
    }
    
    function fnCheckAge() {
    	if (!document.getElementById) return false;
    	var myAge = document.myform.myagefield.value;
    	
    	if (myAge > 18)
    		{
    			alert("Welcome.");
    		}
    	else
    		{
    			alert("Sorry you are too young.");
    		}
    }
    
    function fnClickCheck() {
    	if (!document.getElementById) return false;
    	var btnClick = document.getElementById("btnClick");
    	btnClick.onclick = fnCheckAge;
    }
    
    addLoadEvent(fnClickCheck);
    So, any takers?

  2. #2
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,806
    Mentioned
    157 Post(s)
    Tagged
    3 Thread(s)
    var answerArea = document.question-1.answer-1.value;

    Think about what that is saying din the JavaScript Andrew.
    question minus one dot answer minus 1

    Change the form input id to use underscores NOT minus signs
    And the JavaScript to:

    var answerArea = document.question_1.answer_1.value;
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  3. #3
    SitePoint Guru Vincent Puglia's Avatar
    Join Date
    Feb 2000
    Location
    where the World once stood
    Posts
    700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Rename the *.js file as well. Never use hyphens; use underscores as spike2 suggests or capitalization and concatenation (question1, questionOne)
    Where the World Once Stood
    the blades of grass
    cut me still

  4. #4
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by spikeZ View Post
    var answerArea = document.question-1.answer-1.value;

    Think about what that is saying din the JavaScript Andrew.
    question minus one dot answer minus 1

    Change the form input id to use underscores NOT minus signs
    And the JavaScript to:

    var answerArea = document.question_1.answer_1.value;
    What am I supposed to say to that Mike? Why is it always such a simple solution that manages to evade me for such a long time? I didn't even think to try that. Hyphens are fine with HTML and CSS, I assumed they were fine with JavaScript too, but, they obviously aren't!

    You know, it almost makes me want to cry a tiny little bit. But thank you. At over 100 views and 0 replies I was beginning to give up hope, and then you come in like a Knight in shining armour. It works Now to actually script it how it should be want it to be.

    You didn't REALLY think I was going to use the alert method in an actual website did you?!

    Quote Originally Posted by Vincent Puglia View Post
    Rename the *.js file as well. Never use hyphens; use underscores as spike2 suggests or capitalization and concatenation (question1, questionOne)
    It's fine with hyphens in the name of the file. Why is it that I should use underscores or capitalization for the file name too?

  5. #5
    SitePoint Guru Vincent Puglia's Avatar
    Join Date
    Feb 2000
    Location
    where the World once stood
    Posts
    700
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    It's fine with hyphens in the name of the file. Why is it that I should use underscores or capitalization for the file name too?
    It makes for consistency. If you avoid hyphens everywhere, you don't need to remember whether languages permit them or not. Then again, that's just the way I see and do things.
    Where the World Once Stood
    the blades of grass
    cut me still

  6. #6
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,806
    Mentioned
    157 Post(s)
    Tagged
    3 Thread(s)
    You're welcome Andrew

    I guess its all a matter of preference but I lean towards Vincent's way of thinking with the hyphens.
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  7. #7
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Vincent Puglia View Post
    It makes for consistency. If you avoid hyphens everywhere, you don't need to remember whether languages permit them or not. Then again, that's just the way I see and do things.
    Ah, yes, that's a fair point to make. I understand your point, and I agree with it completely. But I don't actually call the scripts on live sites anything with hyphens, it'll usually just be scripts.js or script.js. I've decided to go for camelCasing i.e. questionOne, ansOne, etc.

    Now, this thread isn't over yet I've come across another hiccup. I already came across it after replying to this thread, but I wanted to give it a few more tries (and days) before I asked for help again, and, well, I'm here again, because I've failed to fix the issue I'm having.

    I'll post the HTML first and then the JS, you'll be able to see what I'm trying to do from the code. Basically, if the person enters in the form field "Tim Berners-Lee" then it'll alert the user with the message "Correct!" but this isn't working. What I actually want is to do an else after that for a "Wrong!" alert but I thought I'd try to get the first alert working first before the second...But actually, let's do the two birds with one stone.

    HTML File NOT WORKING - quick-question-alert.html

    HTML Code:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8">
    		<title>Quick Question</title>
    		<link rel="stylesheet" media="screen" href="quick-question.css">
    	</head>
    
    	<body>
    		<div class="quick-question">
    			<p class="header">Quick Question</p>
    
    			<p class="question">Who invented the World Wide Web?</p>
    
    			<form name="questionOne" method="post" action="#">
    				<label for="answer">Answer:</label>
    				<input type="text" value="" id="answerOne" name="answerOne" class="required" />
    				<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
    				<div class="answerPlacement"></div>
    			</form>
    		</div>
    
    		<script src="quick-question.js"></script>
    	</body>
    </html>
    And the JavaScript File NOT WORKING - quick-question-alert.js

    Code:
    function addLoadEvent(func) {
    	var oldonload = window.onload;
    	if (typeof window.onload != 'function') {
    		window.onload = func;
    	} else {
    		window.onload = function() {
    			oldonload();
    			func();
    		}
    	}
    }
    
    function fnAnswers() {
    	if (!document.getElementById) return false;
    
    	// Answer Area
    
    	var answerArea = document.questionOne.answerOne.value;
    
    	// Answer Variables
    
    	var ansOne = "Tim Berners-Lee";
    
    	// Question & Answer Logic
    
    	if (answerArea == ansOne) {
    		alert("Correct!");
    	}
    	else {
    		alert("Wrong!");
    	}
    }
    
    function fnSubmitAnswer() {
    	if (!document.getElementById) return false;
    	var btnSubmit = document.getElementById("btnSubmit");
    	btnSubmit.onclick = fnAnswers;
    }
    
    addLoadEvent(fnSubmitAnswer);
    Now, I do have another similar script that works too, so I'll stick this in here just to show you that I can get alerts to work and I can do at least a little bit of basic JavaScript haha. I mean, seriously, I know this is really basic JavaScript, but I don't know why the hell it isn't working again. It's really frustrating me that I know this is really basic but I can't get it to work.

    HTML File WORKING - age-checker.html

    HTML 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">
    	<head>
    		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    		<title>Age Checker</title>
    		<link rel="stylesheet" type="text/css" media="screen" href="stylesheet.css" />
    		<script type="text/javascript" src="age-checker.js"></script>
    	</head>
    
    	<body>
    		<div id="wrapper">
    			<h1>Age Checker</h1>
    
    			<p>Type your age in the form field below. You will receive a different popup alert depending 
    			on your age. If you are younger than 18 years old then you will be warned however, if you are
    			 older than 18 then you will be welcomed. Try it!</p>
    
    			<form name="myform">
    				<input type="text" name="myagefield" id="myagefield" value="" />
    				<input type="button" name="btnClick" id="btnClick" value="Click" />
    			</form>
    		</div>
    	</body>
    </html>
    JavaScript File WORKING - age-checker.js

    Code:
    function addLoadEvent(func) {
    	var oldonload = window.onload;
    	if (typeof window.onload != 'function') {
    		window.onload = func;
    	} else {
    		window.onload = function() {
    			oldonload();
    			func();
    		}
    	}
    }
    
    function fnCheckAge() {
    	if (!document.getElementById) return false;
    	var myAge = document.myform.myagefield.value;
    	
    	if (myAge > 18)
    		{
    			alert("Welcome.");
    		}
    	else
    		{
    			alert("Sorry you are too young.");
    		}
    }
    
    function fnClickCheck() {
    	if (!document.getElementById) return false;
    	var btnClick = document.getElementById("btnClick");
    	btnClick.onclick = fnCheckAge;
    }
    
    addLoadEvent(fnClickCheck);
    So, what did I do wrong this time?

  8. #8
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Woopsy daisy. The HTML file references at the bottom <script src="quick-question.js"></script> but the name of the JavaScript file is quick-question-alert.js...I amended it, and it now works perfectly. Ugh. How embarrassing! Such a careless mistake!

    At the same time, how was there 20 new views on this thread and not a single person spotted my mistake?! Tsk tsk!

    Anyway, I do still have another problem with it, which I won't post yet until I've tried sorting it out myself, but I just wanted to update the thread to inform everyone of my mistake and that it has been fixed and now works.

  9. #9
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Ok, so, I've tried, and failed. The conditional statement works, but I of course don't want to use alerts. I'm trying to insert text using a script, and when I click the Submit button it does insert the text of "Correct!" and "Wrong!"...But only for a flash of a second, then it disappears. But I want it to stay there. Again, here's the code for both files.

    HTML File - quick-question.html

    HTML Code:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8">
    		<title>Quick Question</title>
    		<link rel="stylesheet" media="screen" href="quick-question.css">
    	</head>
    
    	<body>
    		<div class="quick-question">
    			<p class="header">Quick Question</p>
    
    			<p class="question">Who invented the World Wide Web?</p>
    
    			<form name="questionOne" method="post" action="#">
    				<label for="answer">Answer:</label>
    				<input type="text" value="" id="answerOne" name="answerOne" class="required" />
    				<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
    				<div id="answerPlacement"></div>
    			</form>
    
    			<p>Lol</p>
    		</div>
    
    		<script src="quick-question.js"></script>
    	</body>
    </html>
    JavaScript File - quick-question.js

    Code:
    function addLoadEvent(func) {
    	var oldonload = window.onload;
    	if (typeof window.onload != 'function') {
    		window.onload = func;
    	} else {
    		window.onload = function() {
    			oldonload();
    			func();
    		}
    	}
    }
    
    function fnAnswers() {
    	if (!document.getElementById) return false;
    
    	// Answer Response
    
    	function fnAnswerResponseCorrect() {
    		var answerParagraph = document.createElement("p");
    		var answerPlacement = document.getElementById("answerPlacement");
    		answerPlacement.appendChild(answerParagraph);
    		var answerText = document.createTextNode("Correct");
    		answerParagraph.appendChild(answerText);
    	}
    
    	function fnAnswerResponseWrong() {
    		var answerParagraph = document.createElement("p");
    		var answerPlacement = document.getElementById("answerPlacement");
    		answerPlacement.appendChild(answerParagraph);
    		var answerText = document.createTextNode("Wrong");
    		answerParagraph.appendChild(answerText);
    	}
    
    	// Question & Answer One
    
    	if (document.questionOne.answerOne.value == "Tim Berners-Lee") {
    		fnAnswerResponseCorrect();
    	}
    	else {
    		fnAnswerResponseWrong();
    	}
    }
    
    function fnSubmitAnswer() {
    	if (!document.getElementById) return false;
    	var btnSubmit = document.getElementById("btnSubmit");
    	btnSubmit.onclick = fnAnswers;
    }
    
    addLoadEvent(fnSubmitAnswer);
    So, any ideas anyone?

    This particular piece of code:

    Code:
    var answerParagraph = document.createElement("p");
    var answerPlacement = document.getElementById("answerPlacement");
    answerPlacement.appendChild(answerParagraph);
    var answerText = document.createTextNode("Wrong");
    answerParagraph.appendChild(answerText);
    Does work on its own. It's from page 130 of DOM Scripting by Jeremy Keith.

  10. #10
    SitePoint Guru Jason__C's Avatar
    Join Date
    Oct 2009
    Location
    Racoon City
    Posts
    660
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    You have a scope problem by nesting multiple functions, and calling the function that is within another. Could be wrong.
    Chuck Norris is so tough,
    mosquitos ask for permission before they bite him

  11. #11
    dooby dooby doo silver trophybronze trophy
    spikeZ's Avatar
    Join Date
    Aug 2004
    Location
    Manchester UK
    Posts
    13,806
    Mentioned
    157 Post(s)
    Tagged
    3 Thread(s)
    You could just do something like:

    Code HTML4Strict:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8">
    		<title>Quick Question</title>
    		<link rel="stylesheet" media="screen" href="quick-question.css">
    <script>
    	function fnAnswer() {
    		var result = '';
    		var answerParagraph = document.createElement("p");
    		var answerPlacement = document.getElementById("answerPlacement");
    		answerPlacement.appendChild(answerParagraph);
    		/* answers */
    		if (document.questionOne.answerOne.value == "Tim Berners-Lee") {
    			result = "Correct";
    		} else {
    			result = 'Narf!';
    		}
     
    		var answerText = answerPlacement.innerHTML = result;
    	}
    </script>
    	</head>
     
     
    	<body>
    		<div class="quick-question">
    			<p class="header">Quick Question</p>
     
     
    			<p class="question">Who invented the World Wide Web?</p>
     
     
    			<form name="questionOne" onSubmit="return false;">
    				<label for="answer">Answer:</label>
    				<input type="text" value="" id="answerOne" name="answerOne" class="required" />
    				<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" onclick="fnAnswer();" />
    				<div id="answerPlacement"></div>
    			</form>
     
     
    			<p>Lol</p>
    		</div>
     
     
    	</body>
    </html>
    Mike Swiffin - Community Team Advisor
    Only a woman can read between the lines of a one word answer.....

  12. #12
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by spikeZ View Post
    You could just do something like...
    Yes, I could, and that actually works! But there are two problems with that, for me at least. That solution uses innerHTML which isn't part of the JavaScript standard, and I want to keep to the standards, which is why I'm trying to get the standards based version to work that Jeremy Keith uses in his DOM Scripting book. Also, when I try to implement that externally it gives me the same result as my existing script, it appears for a flash of a second then disappears.

    Code:
    function addLoadEvent(func) {
    	var oldonload = window.onload;
    	if (typeof window.onload != 'function') {
    		window.onload = func;
    	} else {
    		window.onload = function() {
    			oldonload();
    			func();
    		}
    	}
    }
    
    function fnAnswers() {
    	if (!document.getElementById) return false;
    
    	// Answer Response
    
    	var result = '';
    	var answerParagraph = document.createElement("p");
    	var answerPlacement = document.getElementById("answerPlacement");
    	answerPlacement.appendChild(answerParagraph);
    
    	// Question & Answer One
    
    	if (document.questionOne.answerOne.value == "Tim Berners-Lee") {
    		result = "Correct!";
    	}
    	else {
    		result = "Wrong!";
    	}
    
    	var answerText = answerPlacement.innerHTML = result;
    }
    
    function fnSubmitAnswer() {
    	if (!document.getElementById) return false;
    	var btnSubmit = document.getElementById("btnSubmit");
    	btnSubmit.onclick = fnAnswers;
    }
    
    addLoadEvent(fnSubmitAnswer);
    I don't see why it can't just bloody work. It does work to some extent using the standards based method, but the result text disappears in the flash of a second. I really don't want to use the innerHTML method, even though it works.

  13. #13
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Can anyone else help with this? I can't find any solutions to this problem anywhere, at least from the searches I've done.

    Anyone...? My JavaScript heroes @paul_wilkins , @markbrown4 , @cpradio , @AussieJohn , @felgall , and @Stomme poes ?

  14. #14
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,108
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    Hi Andrew,

    Event handlers pass the event to the callback where you can cancel the default action.
    The reason you see the flash is that it's actually submitting the form.
    Code javascript:
    function fnAnswers(event) {
        event.preventDefault();
        ...
    }
    There's nothing wrong with using innerHTML too.

  15. #15
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by markbrown4 View Post
    Hi Andrew,

    Event handlers pass the event to the callback where you can cancel the default action.
    The reason you see the flash is that it's actually submitting the form.
    Code javascript:
    function fnAnswers(event) {
        event.preventDefault();
        ...
    }
    There's nothing wrong with using innerHTML too.
    Mark, Mark, Mark...WHAT would I do without you?! Thank you!

    But, in all seriousness, how the hell am I supposed to know about event.preventDefault()? That isn't referenced or mentioned in any of the JavaScript books I have, nor any of the tutorials or articles I've read.

    ...Yet when you type event.preventDefault() in Google...It's an entirely different matter! It's mentioned in the Document Object Model (DOM) Level 3 Events Specification, Mozilla Developer Network, and YUI Library Examples: Event Utility: Simple Event Handling and Processing.

    That's annoying. I mean, if I would have known such a method existed for these purposes, well, I would have used it. But even then, I didn't know what my actual problem was, and if you don't know what the problem is, you can't possibly seek out a solution to it. There's loads of methods I could use...But which is the right one that's going to solve my problem? I don't know until I know what the problem is!

    Anyway, thank you Mark. And also thank you again Mike for helping me with the earlier issues, if you didn't help I wouldn't be at the stage I'm at now! Plus fixing some silly and careless mistakes on my part.

  16. #16
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,108
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by AndrewCooper View Post
    Mark, Mark, Mark...WHAT would I do without you?! Thank you!

    But, in all seriousness, how the hell am I supposed to know about event.preventDefault()? That isn't referenced or mentioned in any of the JavaScript books I have, nor any of the tutorials or articles I've read.
    Which JavaScript books have you got? I would have thought every book teaching anything about events should have it right near the top.
    Simply Javascript is actually quite an excellent little book and includes how to work with events.
    Another one is Eloquent Javascript http://eloquentjavascript.net/chapter13.html
    Actually, flicking through that chapter I remember now there's a compatibility issue with preventDefault, IE needs event.returnValue = false; instead.

    A simpler method is just to return false in an event handler to preventDefault across the board. This doesn't stop event bubbling though.
    I'd really just recommend grabbing one of the addEvent functions to handle the cross browser issues, I just rely on libraries to take care of that these days.

    ...Yet when you type event.preventDefault() in Google...It's an entirely different matter! It's mentioned in the Document Object Model (DOM) Level 3 Events Specification, Mozilla Developer Network, and YUI Library Examples: Event Utility: Simple Event Handling and Processing.

    That's annoying. I mean, if I would have known such a method existed for these purposes, well, I would have used it. But even then, I didn't know what my actual problem was, and if you don't know what the problem is, you can't possibly seek out a solution to it. There's loads of methods I could use...But which is the right one that's going to solve my problem? I don't know until I know what the problem is!

    Anyway, thank you Mark. And also thank you again Mike for helping me with the earlier issues, if you didn't help I wouldn't be at the stage I'm at now! Plus fixing some silly and careless mistakes on my part.
    The moz docs are great and http://www.quirksmode.org/ has all the info on browser compatibility.

  17. #17
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by markbrown4 View Post
    Which JavaScript books have you got? I would have thought every book teaching anything about events should have it right near the top.
    Simply Javascript is actually quite an excellent little book and includes how to work with events.
    Another one is Eloquent Javascript http://eloquentjavascript.net/chapter13.html
    I have Simply JavaScript, DOM Scripting, JavaScript: The Definitive Guide 6th Edition, JavaScript: The Good Parts, and Head First JavaScript. So, quite a few.

    Quote Originally Posted by markbrown4 View Post
    Actually, flicking through that chapter I remember now there's a compatibility issue with preventDefault, IE needs event.returnValue = false; instead.
    Which versions of IE? I just checked the script in IE9 and it's fine.

    To end this thread I wanted to show everyone what I was trying to achieve from the first / original post and have now, finally, achieved, with the help of Mike and Mark Plus, if anyone else wants to do something similar to what I wanted to do, they can just copy, paste, and edit the code here! So, here is the complete working code!

    HTML File

    HTML Code:
    <!DOCTYPE html>
    <html lang="en">
    	<head>
    		<meta charset="utf-8">
    		<title>Quick Question</title>
    		<link rel="stylesheet" media="screen" href="quick-question.css">
    	</head>
    
    	<body>
    		<div id="quick-question">
    			<p class="header">Quick Question</p>
    
    			<p class="question">Who invented the World Wide Web?</p>
    
    			<form name="questionOne" method="post" action="#">
    				<label for="answer">Answer:</label>
    				<input type="text" value="" id="answerOne" name="answerOne" class="required" />
    				<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
    				<div id="answerPlacement"></div>
    			</form>
    		</div>
    
    		<script src="quick-question.js"></script>
    	</body>
    </html>
    JavaScript File

    Code JavaScript:
    function addLoadEvent(func) {
    	var oldonload = window.onload;
    	if (typeof window.onload != 'function') {
    		window.onload = func;
    	} else {
    		window.onload = function() {
    			oldonload();
    			func();
    		}
    	}
    }
     
    function fnAnswers(event) {
    	if (!document.getElementById) return false;
     
    	// Answer Response
     
    	function fnAnswerResponseCorrect() {
    		var answerParagraph = document.createElement("p");
    		var answerPlacement = document.getElementById("answerPlacement");
    		answerPlacement.appendChild(answerParagraph);
    		var answerText = document.createTextNode("Correct");
    		answerParagraph.appendChild(answerText);
    		answerParagraph.style.color = "Green";
    	}
     
    	function fnAnswerResponseWrong() {
    		var answerParagraph = document.createElement("p");
    		var answerPlacement = document.getElementById("answerPlacement");
    		answerPlacement.appendChild(answerParagraph);
    		var answerText = document.createTextNode("Wrong");
    		answerParagraph.appendChild(answerText);
    		answerParagraph.style.color = "Red";
    	}
     
    	function fnRemoveElement() {
    		var answerPlacement = document.getElementById("answerPlacement");
     
    		while (answerPlacement.firstChild) {
    			answerPlacement.removeChild(answerPlacement.firstChild);
    		}
    	}
     
    	// Question & Answer One
     
    	if (document.questionOne.answerOne.value == "Tim Berners-Lee") {
    		event.preventDefault();
    		fnRemoveElement();
    		fnAnswerResponseCorrect();
    	}
    	else {
    		event.preventDefault();
    		fnRemoveElement();
    		fnAnswerResponseWrong();
    	}
    }
     
    function fnSubmitAnswer() {
    	if (!document.getElementById) return false;
    	var btnSubmit = document.getElementById("btnSubmit");
    	btnSubmit.onclick = fnAnswers;
    }
     
    addLoadEvent(fnSubmitAnswer);

    Now that it's actually working correctly, as I intended it to and all of the obvious errors have been fixed, does anyone fancy doing a code review?

  18. #18
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,108
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    Honestly, I'd just do something like this. Keeping your code as small as possible is almost always the right thing to do.
    HTML Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Quick Question</title>
    <link rel="stylesheet" media="screen" href="quick-question.css">
    </head>
    
    <body>
    <div id="quick-question">
    	<p class="header">Quick Question</p>
    
    	<p class="question">Who invented the World Wide Web?</p>
    
    	<form id="questionOne" name="questionOne" method="post" action="#">
    		<label for="answer">Answer:</label>
    		<input type="text" value="" id="answerOne" name="answerOne" class="required">
    		<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit">
    		<div id="answerPlacement"></div>
    	</form>
    </div>
    
    <script>
    var $ = function(id) { return document.getElementById(id) }
    $('questionOne').onsubmit = function(event) {
      $('answerPlacement').innerHTML = $('answerOne').value == "Tim Berners-Lee" ? 'yep': 'nope';
      return false;
    }
    </script>
    </body>
    </html>

  19. #19
    SitePoint Guru bronze trophy AndrewCooper's Avatar
    Join Date
    Sep 2008
    Location
    Manchester, UK
    Posts
    631
    Mentioned
    10 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by markbrown4 View Post
    Honestly, I'd just do something like this. Keeping your code as small as possible is almost always the right thing to do.
    I know that keeping your code as small as possible is always the right thing to do, but at the sacrifice of what?

    I have you, Mike (here), and centered effect (here) telling me I could just use innerHTML to do what I want. And that's great, because it works.

    But then I have Jeremy Keith in his DOM Scripting book telling me, on page 125:

    Quote Originally Posted by Jeremy Keith
    The innerHTML property can be quite useful when you want a quick and easy way to insert a chunk of HTML into a document. Unfortunately, innerHTML doesn't return any references to the content you insert. If you want to manipulate the inserted content, you'll need the precision offered by DOM methods.

    innerHTML compares favorably to document.write. Using innerHTML, you can keep your JavaScript separate from your markup. There's no need to insert <script> tags into the <body> of your document.

    Like document.write, innerHTML is HTML-specific. You won't be able to use it on any other kind of markup document. That means if you are serving up XHTML with the correct mime-type, innerHTML won't work.

    It's aslo worth remember that innerHTML is a proprietary method, not a web standard. I think it's a good idea to avoid any kind of proprietary JavaScript, so that we don't repeat the bad old days of the browser wars. Back then, as I discussed in Chapter 1, competing browsers had different Document Object Models. As it turns out, innerHTML is well supported. Nonetheless, its future existence is far from certain.

    In any case, the standardized DOM can be used instead of innerHTML. It may take slightly more code to achieve the same results but, as you'll see, it offers more precision and power.
    And then Michael Morrison in his Head First JavaScript book telling me, on page 352:

    Quote Originally Posted by Michael Morrison
    Not so fast. I heard innerHTML isn't even a Web standard. Is that true?

    Well, yes, but are web standards really anything to worry about?

    It's true, innerHTML was originally created by Microsoft as a proprietary feature fore the Internet Explorer browser. Since then, other browsers have adopted innerHTML, and it has become an unofficial standard for quickly and easily changing the content of web page elements.

    But the fact remains that innerHTML isn't standard. That may not seem like a big deal but the idea behind standards is to make web pages and applications work on as many browsers and platforms as possible. Besides, there is a standards-compliant way of accomplishing the same task that is ultimately more flexible and more powerful, even if it isn't quite as simple. This approach involves the DOM, or Document Object Model, a collection of objects that provide JavaScript with complete and total control over the structure and content of web pages.
    And then on page 365:

    Quote Originally Posted by Michael Morrison
    The DOM is a web standard way of manipulating HTML that allows more control than using the innerHTML properly.
    So, what do I do? Follow the advice of three people on the SitePoint Community Forums, or what two book authors suggest? Who's right and who's wrong?

    All I want to do is to do it the right way, the web standards way. All of my pages are HTML and CSS validated, why not add JS validation to that too? If I'm using standard HTML and CSS, why not use standard JS too through the DOM?

    I guess my question is, what advantage does using innerHTML have over inserting content through the DOM standard?

    But, please don't get me wrong, I appreciate all that you and others have said and will say in this thread and others. But, it's like in some threads I read on here and over at stackoverflow, some people that are looking to do something in plain old JavaScript want to learn how-to do it and then someone comes along and says "You can do it so much easier and simpler if you use jQuery"...I don't want to use jQuery though, and if I was using it, if it's so much simpler and easier than using plain old JavaScript, why are there as many jQuery books available as there is JavaScript books? It makes me think that just maybe, using jQuery isn't as easy and simple as people make it out to be

  20. #20
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,108
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    Quote Originally Posted by AndrewCooper View Post
    I have you, Mike (here), and centered effect (here) telling me I could just use innerHTML to do what I want. And that's great, because it works.

    But then I have Jeremy Keith in his DOM Scripting book telling me, on page 125:
    And then Michael Morrison in his Head First JavaScript book telling me, on page 352:
    And then on page 365:
    So, what do I do? Follow the advice of three people on the SitePoint Community Forums, or what two book authors suggest? Who's right and who's wrong?
    I really respect Jeremy Keith, but I'm sure he uses innerHTML as well I don't think you're sacrificing anything by using it, and you're gaining a few things.
    If anyone says never to use innerHTML on principle, yes, they're wrong about that.
    Those arguments aren't really relevant to your issue at hand here.

    innerHTML and outerHTML are actually a part of the HTML5 spec. Part paving the cow paths, part it's often the best tool for the job.
    http://html5.org/specs/dom-parsing.html#innerhtml
    All I want to do is to do it the right way, the web standards way. All of my pages are HTML and CSS validated, why not add JS validation to that too? If I'm using standard HTML and CSS, why not use standard JS too through the DOM?
    I guess my question is, what advantage does using innerHTML have over inserting content through the DOM standard?
    The big one is that it has always been much faster than building up a DOM dynamically.
    http://www.quirksmode.org/dom/innerhtml.html

    But, please don't get me wrong, I appreciate all that you and others have said and will say in this thread and others. But, it's like in some threads I read on here and over at stackoverflow, some people that are looking to do something in plain old JavaScript want to learn how-to do it and then someone comes along and says "You can do it so much easier and simpler if you use jQuery"...I don't want to use jQuery though, and if I was using it, if it's so much simpler and easier than using plain old JavaScript, why are there as many jQuery books available as there is JavaScript books? It makes me think that just maybe, using jQuery isn't as easy and simple as people make it out to be
    The "Don't reach for jQuery" argument could be written in support of innerHTML.

    Essentially it says "Don't include a big library to do a small thing"
    I'm saying "Don't include a big script to do a small thing"

    There's no right and wrong, both solutions work. Your script with the DOM methods was a heck of lot more work for not any real benefits though.

  21. #21
    SitePoint Addict
    Join Date
    Dec 2005
    Posts
    336
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    As markbrown noted, innerHTML is faster, less code than the DOM way, and will be part of the HTML5 spec. Additionally, the books you reference are from '05 & '08. Alot has changed since then - not saying the books are bad, just the web moves fast.

    Now, other DOM methods are ok to use as well, when needed. Let's take another look at your code, using my edits form the quick code review with multiple questions:
    Code HTML4Strict:
    <head>
    	<meta charset="utf-8">
    	<style>
    		.incorrect { color: red; }
    		.correct { color: green; }
    	</style>
    </head>
    <body>
    	<div>
    		<p>Quick Questions</p>
    		<form id="questionForm" method="post" action="#">
     
    			<p id="questionOne">Who invented the World Wide Web?			
    				<label for="answerOne">Answer:</label>
    				<input type="text" value="" id="answerOne" name="answerOne" />
    			</p>
     
    			<p id="questionTwo">What does WWW stand for?
    				<label for="answerTwo">Answer:</label>
    				<input type="text" value="" id="answerTwo" name="answerTwo" />
    			</p>				
    			<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
    		</form>
    	</div>

    Code JavaScript:
    var frm = document.getElementById('questionForm'),
    	answers = [
    		{ field: 'answerOne', answer: 'Tim Berners-Lee' },
    		{ field: 'answerTwo', answer: 'World Wide Web' }
    	], i, el, respEl;
     
    // Source: [url]http://www.netlobo.com/javascript-insertafter.html[/url]
    function insertAfter( referenceNode, newNode ) {
    	referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
    }			
     
    frm.onsubmit = function() {
    	for( i = 0; i < answers.length; i++ ) {
    		// Remove the response element, if it exists
    		respEl = document.getElementById(answers[i].field + 'Response');
    		if( respEl ) {
    			respEl.parentNode.removeChild(respEl);
    		}
    		// Create the response element, the add it after the text input
    		el = document.getElementById(answers[i].field);
    		respEl = document.createElement('p');
    		respEl.setAttribute('id', answers[i].field + 'Response');
    		insertAfter(el, respEl);
     
    		if( el.value !== answers[i].answer ) {
    			respEl.setAttribute('class','incorrect');
    			respEl.innerHTML = 'Wrong';
    		} else {
    			respEl.setAttribute('class','correct');
    			respEl.innerHTML = 'Right';
    		}
    	}
    	return false;
    };

    here I am using pure Javascript, DOM methods, and innerHTML as well.

  22. #22
    om nom nom nom Stomme poes's Avatar
    Join Date
    Aug 2007
    Location
    Netherlands
    Posts
    10,272
    Mentioned
    50 Post(s)
    Tagged
    2 Thread(s)
    A little late here, but Simply Javascript describes both preventDefault and the IE (6-8) method, and shows how to assign them both to a new function that works on everyone.


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
  •