...

View Full Version : Beginner: Why won't my script work??



Mishelm
11-20-2012, 03:00 AM
Please help me!! I am an absolute beginner with javascript. I can not seem to make this script work and am frustrated and not sure what i am doing wrong!! Can some kind soul help me? I want the script to check to make sure the user city is filled in and if not alert them. Should be simple, why can't I make it work?? AAARGHH
<code>
<script type='text/javascript'>
function required()
{
var empt = document.forms["form"]["userCity"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
}
</script>

</head>
<body>
<h1> JavaScript Form Handling</h1>
<form name="jsform" method="post"
action="http://webdevfoundations.net/scripts/formdemo.asp"
onsubmit="return validateform();">
<p>
<label for= "userName">Name: </label>
<input type="text" name="userName" id="userName"><br />
<label for= "userAge">Age: &nbsp;&nbsp; </label>
<input type="text" name="userAge" id="userAge"><br />
<label for= "userCity">City:&nbsp;&nbsp; </label>
<input type="text" name="userCity" id="userCity">
</p>
<p>
<input type="submit" value="Send Information" id="submit" />
</p>
</form>
</code>

Logic Ali
11-20-2012, 03:32 AM
It would be easy to point out your error, but as the error console is doing it already, why ask?

Mishelm
11-20-2012, 05:21 AM
It would be easy to point out your error, but as the error console is doing it already, why ask?

What part of beginner did you not understand. I do not know what I am doing that is why I am in here asking. I thought someone might, just might be kind enough to help me. Obviously that someone is not you. Have a nice day.

felgall
11-20-2012, 06:17 AM
Which browser are you using?

In Firefox you can get to the error console by going into the "Tools" menu and then into the "Web Developer" sub-menu.

It is in a similar location in other browsers.


Also alert() is intended to be used only as a debugging tool. You shouldn't be using it in a live web page but including alerts between various statements and commenting out pieces of code are quick ways of locating problems.

Old Pedant
11-20-2012, 06:20 AM
That really was the best possible answer for you, in the long run.

You will never be able to get proficient in JavaScript if you don't learn to use the debugging tools--including the error console--that are built into almost all browsers.

I would suggest that you use the Chrome browser, though MSIE 9 is actually quite usable for this as well. (FireFox doesn't include a full debugger; you have to install the FireBug plugin. Not hard to do, but if you are just starting out I'd just stick with Chrome.)

To activate the debugger, including the error console, just push the F12 key on your keyboard. If you are indeed using Chrome, you will be presented with a list of "tabs" in the debug area at the bottom of the page. The rightmost tab--which will normally be the one that comes up automatically--is the error console.

You should see a list of the errors on your page as detected by the JS engine. If you don't understand the error message for any one/all of them, just click on the thing on the right side of the tab that looks like an <a> link (it will have the name of the page and the line number with the error) and up will pop the JS code from your page with the point of the error highlighted.

Fix the error and hit F5 (refresh page) and repeat the process until you get no more error messages.

There is much more that the debugger console can do for you (you will notice all the other available tabs), so when you have a little time start exploring what is available.

Old Pedant
11-20-2012, 06:22 AM
And I'll give you the first error for free:

You coded

<form name="jsform" ... onsubmit="return validateform();">

Where, pray tell, do you see any function named validateform in your code?

Philip M
11-20-2012, 07:46 AM
What part of beginner did you not understand. I do not know what I am doing that is why I am in here asking. I thought someone might, just might be kind enough to help me. Obviously that someone is not you. Have a nice day.

I am sorry that you seem to have had unsympathetic and less than entirely helpful replies when you made it clear that you were an absolute beginner. It is certainly true that you ought to learn to use the debugging tools and error console, but it may be that is too advanced for you at this stage and your teacher has not yet got around to explaining it.

Here is your code corrected:-


<script type='text/javascript'>
function validateform() {
var empt = document.getElementById("userCity").value;
if (empt == "") {
alert ("Please input a Value");
document.getElementById("userCity").focus();
return false;
}
}
</script>

</head>
<body>
<h1> JavaScript Form Handling</h1>
<form name="jsform" method="post"
action="http://webdevfoundations.net/scripts/formdemo.asp" onsubmit="return validateform();">
<p>
<label for= "userName">Name: </label>
<input type="text" name="userName" id="userName"><br />
<label for= "userAge">Age: &nbsp;&nbsp; </label>
<input type="text" name="userAge" id="userAge"><br />
<label for= "userCity">City:&nbsp;&nbsp; </label>
<input type="text" name="userCity" id="userCity">
</p>
<p>
<input type="submit" value="Send Information" id="submit" />
</p>
</form>

Two comments:-

empt is not a very descriptive name for a variable which is supposed to contain the name of a city.

Form validation of the pattern if (document.formname.formfield.value == "") - that is blank - is barely worthy of the name, and virtually useless, as even a single space, an X or a ? will return false, that is pass the validation. And the name of a city can only include letters (and perhaps hyphens), not numbers or punctuation. This topic has been covered many times before in this forum.

As felgall says, you should not use alerts in a live web page.


“The expert at anything was once a beginner”

Logic Ali
11-20-2012, 11:22 AM
What part of beginner did you not understand. I do not know what I am doing that is why I am in here asking.

Forums start where searching (http://lmgtfy.com/?q=javascript+%2Bhow+to+use+the+error+console) ends.

Philip M
11-20-2012, 01:10 PM
Forums start where searching (http://lmgtfy.com/?q=javascript+%2Bhow+to+use+the+error+console) ends.

Can I ask - what is the question you expect the OP to enter into Google's search box?

Mishelm
11-20-2012, 04:52 PM
I am sorry that you seem to have had unsympathetic and less than entirely helpful replies when you made it clear that you were an absolute beginner. It is certainly true that you ought to learn to use the debugging tools and error console, but it may be that is too advanced for you at this stage and your teacher has not yet got around to explaining it.

Here is your code corrected:-

As felgall says, you should not use alerts in a live web page.


Thank you so much for being a decent human being.. you give me hope. I am a complete beginner and did not know where to start. I will install Chrome and try that going forward. I had searched and searched on google and could not understand. I think that some forget that they were once exactly where I am. I refused to feel shame for not knowing and trying to learn. Thank you again for taking the time to help... you made my day.

Philip M
11-20-2012, 05:03 PM
Thank you so much for being a decent human being.. you give me hope. I am a complete beginner and did not know where to start. I will install Chrome and try that going forward. I had searched and searched on google and could not understand. I think that some forget that they were once exactly where I am. I refused to feel shame for not knowing and trying to learn. Thank you again for taking the time to help... you made my day.

That is very pleasing. Good luck!

Logic Ali
11-20-2012, 06:29 PM
Can I ask - what is the question you expect the OP to enter into Google's search box?

It's provided in the link I gave.

Philip M
11-20-2012, 06:41 PM
It's provided in the link I gave.

Hmm. Looking at the sites returned they seem singularly unhelpful. Especially for an absolute beginner.

Logic Ali
11-20-2012, 08:20 PM
Hmm. Looking at the sites returned they seem singularly unhelpful. Especially for an absolute beginner.

If they add to the query the name of their browser they must find something, that's if they haven't seen it at some time when going through the browser's menus. In any case for future occasions to avoid further criticism from those who expect to be spoon-fed, I have now drafted a detailed standard response. Here's its debut:


All programming languages provide a means of reporting syntax and runtime errors. While it would be simple just to point you to the problem, your question makes it clear that you are not using your browser's Error Console, which must be indicating the nature of at least one error.
If you are studying solely from written materials, they should have made you aware of the existence and use of the The Error Console. If you have any form of tutor, he/she should have instructed and disciplined you in the use of The Error Console during your first lesson/lecture. If the latter is the case, it is your duty both to yourself and future students to take your tutors to task on the matter, so that the oversight is never repeated. If your tutors disclaim any such obligation, you are encouraged to refer them to this or any similar forum, on which they may explain their rationale.
Searching for how to access your particular browser's error console/developer tools is a simple matter and something you must do immediately. By so doing you will save yourself incalculable time, frustration and the humiliation of requesting unnecessary assistance.

Philip M
11-20-2012, 09:03 PM
If they add to the query the name of their browser they must find something, that's if they haven't seen it at some time when going through the browser's menus. In any case for future occasions to avoid further criticism from those who expect to be spoon-fed, I have now drafted a detailed standard response. Here's its debut:

Does that not sound rather ... pompous?

It is really just your version of "Read The Flipping Manual". May be strictly correct, but seems to me unnecessarily supercilious and patronising.
You should bear in mind that you will catch more flies with honey than with vinegar. :)

Old Pedant
11-20-2012, 10:06 PM
Am curious as to what others think about the various debuggers available.

I have stated that, all in all, I find Chrome's to be the most beginner-friendly.

For example, when you hit F12, Chrome comes up BY DEFAULT exhibiting the error console and reports errors ALREADY FOUND on the current page.

In contrast, MSIE 9 comes up with the HTML tab active and even after you click on the CONSOLE tab you are told you must refesh the page to see the errors.

And of course with Firefox you must first install the debugger before you can use it. It's a nice debugger, but it's just one more step for the beginner.

None of the browsers do the best job they could with *meaningful* (and self-explanatory) error messages, but Chrome's are at least as good as the others and when you click on the "link" at the right you are shown your JS source along with the error message is nice readable form.

I do agree with LogicAli that the best thing a beginner can do--especially a beginner who is a student under time pressure to finish his/her homework--is *IMMEDIATELY* learn to at least use the error console, if not the full debugger. It will save HOURS AND HOURS of time, not the least of which might be waiting for many hours for an answer in some forum.

Philip M
11-21-2012, 09:04 AM
I certainly do not disagree with anything you have said, but I have to say that I think it is unreal to expect beginnners to come to grips with the error console (still less the full debugger) while they are still struggling with elementary concepts, such as loops and arrays. They are likely to not have any awareness of these tools (perhaps the fault of their teachers who we have often agreed are not always 100% competent) - until they come to this forum hoping for assistance and receive a flea in their ear from Logic Ali. And these tools are meaningless until you have learned some Javascript.

At that level simple error detection can often be carried out with strategically placed alerts to inspect values. And debugging tools do not correct errors of logic, such as lines of code in the wrong place.

I would prefer to take a more sympathetic and helpful attitude to students/beginners, especially those who have clearly made a serious effort. I remember from my schooldays how much I loathed teachers (and naturally by association their subjects) who dealt with mistakes by being supercilious and patronising.

As I said in a previous post, you will catch more flies with honey than with vinegar. By all means suggest (in a pleasant manner) using the error console - but that in addition to giving more helpful advice, such as actually pointing out the errors in the code (and perhaps going further with an explanation/commentary about why something is incorrect). It would be nice to think that you were encouraging the student's interest in Javascript - not suppressing or destroying it.

As an aside, I tried to validate this page

http://validator.w3.org/check?verbose=1&uri=http%3a%2f%2fwww.codingforums.com%2fshowthread.php%3ft%3d282598&page=2

and received 94 errors and 59 warnings. :eek: Shome mishtake, shurely.

Logic Ali
11-21-2012, 01:55 PM
I certainly do not disagree with anything you have said, but I have to say that I think it is unreal to expect beginnners to come to grips with the error console (still less the full debugger) while they are still struggling with elementary concepts, such as loops and arrays.
I see no reason for any mutual interference between the two processes of learning a language and learning to interpret its associated error messages.
In any compiled language, compile-time error messages are displayed overtly and users benefit immediately by learning to interpret them concurrently.
It is a matter of responsibility to ensure that the above situation is maintained for all languages.

Philip M
11-21-2012, 04:23 PM
I see no reason for any mutual interference between the two processes of learning a language and learning to interpret its associated error messages.
In any compiled language, compile-time error messages are displayed overtly and users benefit immediately by learning to interpret them concurrently.
It is a matter of responsibility to ensure that the above situation is maintained for all languages.

I may get an infraction, but I am tempted to say that with that level of pomposity you ought to be an MP! :)

felgall
11-21-2012, 06:48 PM
The simplest debugging tools for a beginner to use are

alert()

and

/* */

by placing alerts in their code and commenting out parts of it they can determine which pieces of the code work and which pieces don't. By changing what is commented out and examining the values of different fields at different points they should be able to track down which statement has the problem even without using the error console or debugger.

That's the reason the alert (and confirm and prompt) calls still exist in JavaScript and why most browsers display an extra checkbox so you don't get stuck in an infinite loop of alerts.

AndrewGSW
11-21-2012, 07:28 PM
console.log() is one step above alert() but, of course, requires knowing that the console exists :rolleyes:

@Old Pedant

I was always a fan of Firebug, but FF became slower than Chrome and I had issues with updates to FF (it kept over-riding my home page, and showing additional tabs at start-up).

There is not much difference between the various browser-debuggers, but it is a pain to reload the page to examine scripts (in FF and IE).

If I recall correctly there was another debugger in FF (Venkman?) that enabled us to edit the JS..?

Logic Ali
11-21-2012, 07:45 PM
By changing what is commented out and examining the values of different fields at different points they should be able to track down which statement has the problem even without using the error console or debugger.
You think people should start commenting-out lines instead of using the error console, which was developed to prevent having to waste time doing that?
If they knew basic debugging techniques like that, we'd never hear from them in the first place. Typically when they click the button they think 'nothing happens', whereas in reality something is happening, but it's happeinng in the place they haven't been taught to look.

Philip M
11-21-2012, 08:06 PM
Another helpful technique is to use Notepad++ or some other editor which highlights different parts of the code in different colours rather than simple Notepad. It also finds missing matching braces.

felgall
11-21-2012, 08:21 PM
You think people should start commenting-out lines instead of using the error console, which was developed to prevent having to waste time doing that?

No, I think people should learn to use the debugger so that they can work out exactly what is going on instead of having to try to work it out from obscure messages in the error console.

It does take time to learn how to use the debugger or error console though and so using alert and comments provides an easy to understand way for those who still haven't got to JavaScript lesson four, and so have yet to learn about the error console, to find errors in their scripts.

If everyone were to use the error console and debugger then the alert, confirm and prompt dialogs would then serve no useful purpose and could then be removed from JavaScript completely (since their only use currently is as a debugging tool for those who haven't learnt how to use the error console).

felgall
11-21-2012, 08:24 PM
Another helpful technique is to use Notepad++ or some other editor which highlights different parts of the code in different colours rather than simple Notepad. It also finds missing matching braces.

Yet another is to paste your script into the textarea at jslint.com then check the "use a browser" checkbox and submit the form. You then get a list of all the syntax errors and poor coding constructs in your code so you can then fix them. Doing that will just leave potential runtime errors where the script runs but produces the wrong answer for subsequent testing.

Old Pedant
11-21-2012, 08:43 PM
I don't think expecting a newbie to use a debugger, per se, is realistic. Though I do think that it might be nice for somebody to post a tutorial on working with debuggers.

However, I don't think it is unreasonable to teach them the use of the error console as a first line of defense against errors.

Even a newbie should be able to learn to use the error console in 10 to 30 minutes, max.

Will the newbie understand the all too often obscure error messages that JS pumps out? No. But often that's not important. Often all that is needed is to know WHERE an error is.

For example, in the case of the post that started this thread: Surely as soon as the error console marked the call to validateForm as the source of an error even a newbie could look at his code and notice that the function didn't exist. Okay, maybe not on first try, but given just a nudge or two in the right direction...

Will it help a newbie solve all his/her problems? Of course not! But the few minutes it takes to learn how to use the error console can save the newbie (or anyone!) *HOURS* of frustration, including hours of waiting for an answer in some forum.

Philip M
11-22-2012, 11:57 AM
Useful advice on debugging is posted on this site at

http://www.codingforums.com/showthread.php?p=178016

JsLint is useful as well, but many of its reported errors are not such in my book:-

for (var i=0; i<text.length; i++) {
Move 'var' declarations to the top of the function.

Old Pedant
11-22-2012, 04:55 PM
JsLint is useful as well, but many of its reported errors are not such in my book:-

for (var i=0; i<text.length; i++) {
Move 'var' declarations to the top of the function.

Yes, I agree on that one.

It's true that such a var declaration actually does declare the variable at function scope if the loop is in function (or page scope if not), but there's no requirement in JavaScript that variables be declared at the beginning of a function. That's just what the jslint authors think is the right style. So you are being held at the mercy of their preferences.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum