Jump to content

Another Form Validation Question


twilitegxa

Recommended Posts

Here is the full 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>
<title>E-Mail Form</title>
<link rel="stylesheet" href="js_styles.css" type="text/css" />
<meta http-equiv="content-type"
content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
/*<![CDATA[*/
function validateSubmission() {
var retValue = true;
if (document.forms[0].subject.value.length > 40) {
window.alert("The subject must be 40 characters or less!");
return false;
}

retValue = validateEmail(document.forms[0].sender_email);
if (retValue ==  false)
return retValue;
retValue = validateEmail(document.forms[0].recipient_email);
if (retValue == false)
return retValue;
}
function validateEmail(formObject) {
var email = formObject.value;
formObject.value = email.toLowerCase();
return true;
}
/*]]>*/
</script>
</head>
<body>
<form action="FormProcessor.html" method="get"
onsubmit="return validateSubmission()">
<table frame="border" rules="cols" >
<tr>
<td valign="top">
<h2>Sender</h2>
<p>Name<br />
<input type="text" name="sender_name" size="40" /></p>
<p>E-Mail Address<br />
<input type="text" name="sender_email" size="40" /></p>
<hr /><h2>Recipients</h2>
<p>Name<br />
<input type="text" name="recipient_name" size="40" /></p>
<p>E-Mail Address<br />
<input type="text" name="recipient_email" size="40" /></p>
</td>
<td valign="top">
<h2>Message Details</h2>
<p>Subject<br />
<input type="text" name="subject" size="53" /></p>
<p>Message<br />
<textarea name="message" rows="14" cols="40"></textarea></p>
<p style="text-align: center"><input type="submit" value="Send" /><input type="reset" />
<input type="hidden" name="recipientsList" /></p>
</td></tr>
</table>
</form>
</body>
</html>

 

The instructions say:

 

Add the following if...else statement after the statement in the validateSubmission() function that declaresthe retValue variable. Notice that the length property is appended to the value property of the subject object. If the length of the subject is greater than 40 characters, a message displays to the user that she has exceeded the maximum number of characters and the if statement ensures that the sender_email, recipient_email, and subject fields are filled in.

 


if (document.forms[0].subject.value.length > 40) {
window.alert("The subject must be 40 characters or less!");
return false;
}
else if (document.forms[0].sender_email.value == ""
|| document.forms[0].recipient_email.value == ""
|| document.forms[0].subject.value == "") {
window.alert("You did not fill in one of the
following required fields: sender e-mail,
recipient e-mail, or subject.");
retValue = false;
}

 

The first part works, if I leave out this part:

 

else if (document.forms[0].sender_email.value == ""
|| document.forms[0].recipient_email.value == ""
|| document.forms[0].subject.value == "") {
window.alert("You did not fill in one of the
following required fields: sender e-mail,
recipient e-mail, or subject.");
retValue = false;
}

 

What is wrong with this part of the code?

 

Then after that, the next instruction is:

 

Add the following statements after the closing brace of the else clause to check if the retValue variable was set to false:

 

if (retValue == false)
      return retValue;

 

But when I tried to add this code, the form still wasn't working. Can you guys tell me where this code goes and why the previous code wasn't working also?

Link to comment
Share on other sites

That is what I'm doing. This is what this script does, but it's also doing other things, and I'm using a tutorial trying to learn more things I can do with JavaScript, but I'm doing something wrong because the code isn't working, so I'm trying to figure out what I'm doing wrong.

Link to comment
Share on other sites

<script type="text/javascript">

function limitText(limitField, limitCount, limitNum) {

if (limitField.value.length > limitNum) {

limitField.value = limitField.value.substring(0, limitNum);

} else {

limitCount.value = limitNum - limitField.value.length;

}

}

 

</script>

</head>

<body>

<form name="myform">

<input name="limitedtextfield" type="text" onKeyDown="limitText(this.form.limitedtextfield,this.form.countdown,15);"

onKeyUp="limitText(this.form.limitedtextfield,this.form.countdown,15);" maxlength="15"><br>

<font size="1">(Maximum characters: 15)<br>

You have <input readonly type="text" name="countdown" size="3" value="15"> characters left.</font>

</form>

</body>

</html>

Link to comment
Share on other sites

It's not that I don't appreciate your help, but I really want to work from this tutorial. I just need some help figuring out what I'm doing wrong on my script. Anyone that can spot the problem?

 

To be honest, I think that you should start over.  Online tutorials, especially JavaScript tutorials, tend to be crap.  They teach you just enough to code incorrectly, causing most new JavaScript coders to hate the language.  I was one of those people myself before I was shown the right way to do things.

 

The key to good JavaScript design is to write the code to be inobtrusive.  There's no need for any JavaScript to be written directly in the HTML.  The whole point of JavaScript is to add dynamic behavior to sites without impacting the markup.

 

So, in your test script, you're trying to do some simple e-mail validation, correct?  Let's start with the form first:

<form name="myForm" action="#" method="post">
   Sender Name: <input name="sender_name" type="text" /><br />
   Sender E-mail: <input name="sender_email" type="text" /><br /><br />

   Recipient Name: <input name="recipient_name" type="text" /><br />
   Recipient E-mail: <input name="recipient_email" type="text" /><br /><br />

   Subject: <input name="subject" type="text" /><br />
   Message: <textarea name="message"></textarea><br />
   <input name="submit" type="submit" value="Submit" />
</form>

 

Nothing fancy, but this more or less is the same as what you originally had.  Now, it's time for the JavaScript.

 

The first, and perhaps most important, thing to do is to ensure that the JavaScript code doesn't initialize until the entire HTML document is loaded.  One of the most common things that a rookie JS coder doesn't know/realize is that JavaScript tends to be loaded before the actual document is loaded.  This causes a host of errors, as the script attempts to gain access to elements that don't exist.  So, in order to combat that, you must wait for the document to load.

 

Another thing to keep in mind is that you don't need to hide your JS code within HTML comments or CDATA blocks.  All modern browsers recognize and can handle JavaScript.  If you see code within HTML comments or CDATA blocks, run away, the tutorial is crap.

 

So, with that said, a properly coded unobtrusive bit of JavaScript starts out as:

<script type="text/javascript">
   window.onload = function()
   {
      //script goes here
   }
</script>

 

Putting everything in an anonymous function tied to the window's onload event ensures that the code won't initialize until the document is completely loaded.

 

Now, we go to the validation iself:

<script type="text/javascript">
      window.onload = function()
      {
         var myForm = document.forms["myForm"];
         var senderEmail = document.forms["myForm"].elements["sender_email"];
         var recipientEmail = document.forms["myForm"].elements["recipient_email"];
         var subject = document.forms["myForm"].elements["subject"];

         myForm.onsubmit = validateForm;

         function validateForm()
         {
            if(subject.value.length >= 40)
            {
               alert("E-mail subject must be shorter than 40 characters!");
               return false;
            }
            else if(senderEmail.value == "" || recipientEmail.value == "" || subject.value == "")
            {
               alert("You did not fill out one or more of the required fields: Sender E-mail, Recipient E-mail, Subject");
               return false;
            }
            else
            {
               return true;
            }
         }
      }
</script>

 

I've tested this code in both IE and Firefox, and it works.  It may not be 100% what you're striving for, but as a learning exercise, it should do.  Notice how the script doesn't interfere with the actual HTML document.  All of the code is within the script tags.  There's no function calls within the form elements themselves.  Also note how assigning the form element info to variables saves on typing and makes for more readable code.  This is the professional way of writing JavaScript, and is something that most tutorials don't address.

Link to comment
Share on other sites

twilitegxa, your code was mostly right, you just didn't have something in the right place I think.

  What this code is doing is telling itself to set retValue to false if anything is wrong.  It then checks if retValue = false , and if so, it returns false, which is the same as not doing anything.  The return is referring to how the thing is being called... from the form like: onsubmit="return validateSubmission()"  if it returns true(nothing wrong), then the form submits, if it's false, it stops.

 

Here's the javascript in the correct order:

<script type="text/javascript">
/*<![CDATA[*/
function validateSubmission() {
if (document.forms[0].subject.value.length > 40) {
   window.alert("The subject must be 40 characters or less!");
   return false;
}
else if (document.forms[0].sender_email.value == ""
   || document.forms[0].recipient_email.value == ""
   || document.forms[0].subject.value == "") {
   window.alert("You did not fill in one of the following required fields: sender e-mail, recipient e-mail, or subject.");
   retValue = false;
}
if (retValue == false)
      return retValue;

retValue = validateEmail(document.forms[0].sender_email);
if (retValue ==  false)
   return retValue;
retValue = validateEmail(document.forms[0].recipient_email);
if (retValue == false)
   return retValue;
}
function validateEmail(formObject) {
   var email = formObject.value;
   formObject.value = email.toLowerCase();
   return true;
}
/*]]>*/
</script>

 

While others may argue that you shouldn't be learning this way, I disagree.  Some people, myself included, need to see how others do it, step by step in a big picture in order to understand how something works.  However, I do encourage you if you do plan to become a serious JS programmer to look into frameworks(if that's the right word) such as mooTools, JQuery, Prototype, Script.acu.lous(or however it's punctuated), if anything, to save you learning time, and just accept that it does work.

 

Those names listed above allow you to not reinvent the wheel and accomplish cool effects as well as useful functions.  However, I do encourage you to reinvent the wheel on some occasions so that you get a thorough understanding of how things work.  And hell, if you end up learning Prototype, please teach me :)

 

Lastly, there's no such thing as the right way to do things.  There is an accepted, less argued/challenged way.  If things weren't challenged, we wouldn't be using Ajax the way we do now; it has existed for years before it became popular, just no one had the nerve to do something new.  So don't let people stop you from doing things the way you want to.

Link to comment
Share on other sites

Okay, I'm hoping you can help again, xtopolis. Same code we're working with from before. Next instruction says:

 

Add the following bolded statements to the validateEmail() function. The function uses search() and lastIndexOf() methods to determine whether the string passed to it contains an ampersand and a period. If the string does contain both, a value of true is returned. If not, a value of false is returned.

 

function validateEmail(formObject) {

var email = formObject.value;

  if (email.search("@") == -1

  || email.lastIndexOf(".") == -1) {

window.alert("One or more of the e-mail addresses

you entered does not appear to be valid.");

return false;

}

formObject.value = email.toLowerCase();

return true;

}

 

For some reason this isn't working. When I added it, it just sends the information in the form to the next page. It is supposed to alert you if the e-mail address fields don't contain an @ or . Do you see what I'm doing wrong? Maybe there is an error in the coding? Anyone can answer, not JUST xtopolis :-)

Link to comment
Share on other sites

I somehow lost a line of code in my previous fix.  retValue = true;  (right after function validateSub...)

 

<script type="text/javascript">
/*<![CDATA[*/
function validateSubmission() {
  var retValue = true;

if (document.forms[0].subject.value.length > 40) {
   window.alert("The subject must be 40 characters or less!");
   return false;
}
else if (document.forms[0].sender_email.value == ""
   || document.forms[0].recipient_email.value == ""
   || document.forms[0].subject.value == "") {
   window.alert("You did not fill in one of the following required fields: sender e-mail, recipient e-mail, or subject.");
   retValue = false;
}
if (retValue == false)
      return retValue;

retValue = validateEmail(document.forms[0].sender_email);
if (retValue ==  false)
   return retValue;
retValue = validateEmail(document.forms[0].recipient_email);
if (retValue == false)
   return retValue;
}

function validateEmail(formObject) {
  var email = formObject.value;
     if (email.search("@") == -1
        || email.lastIndexOf(".") == -1) {
        window.alert("One or more of the e-mail addresses you entered does not appear to be valid.");
        return false;
    }
  formObject.value = email.toLowerCase();
  return true;
}
/*]]>*/
</script>

Otherwise a copy/paste of what you posted seems to work.

Link to comment
Share on other sites

I swear, every time I try something, I do something wrong. Here is the next instruction:

 

Add the following statements to the end of the validateSubmission() function. The first statement calls a function named compareAddresses(), which you create next. Notice that parameters are passed to the compareAddresses() function: one for the sender e-mail object and one for the recipient e-mail object. The second statement returns the retValue variable from the validateSubmission() function.

 

retValue = compareAddresses(document.forms[0].sender_email,

document.forms[0].recipient_email);

return retValue;

 

Add the following compareAddresses() function to the end of the script section. The function accepts two parameters for the sender and recipient e-mail objects, which it assigns to two variables: senderEmail and recipientEmail. Both variables are converted to lowercase with the toLowerCase() method and then compared with the localeCompare() method. If both e-mail addresses are the same, a message displays to the user and the function returns a value of false.

 

function compareAddresses(senderObject, recipientObject) {

var senderEmail = senderObject.value;

var recipientEmail = recipientObject.value;

senderEmail = senderEmail.toLowerCase();

recipientEmail = recipientEmail.toLowerCase();

if (senderEmail.localeCompare(recipientEmail) == 0) {

window.alert("You entered the same e-mail address for

sender and recipient.");

return false;

}

else

return true;

}

 

What am I doing wrong this time? LOL I either can't read/type, or there is something wrong in the coding? Or am I putting the code in the wrong places maybe??

Link to comment
Share on other sites

While others may argue that you shouldn't be learning this way, I disagree.  Some people, myself included, need to see how others do it, step by step in a big picture in order to understand how something works.  However, I do encourage you if you do plan to become a serious JS programmer to look into frameworks(if that's the right word) such as mooTools, JQuery, Prototype, Script.acu.lous(or however it's punctuated), if anything, to save you learning time, and just accept that it does work.

 

Those names listed above allow you to not reinvent the wheel and accomplish cool effects as well as useful functions.  However, I do encourage you to reinvent the wheel on some occasions so that you get a thorough understanding of how things work.  And hell, if you end up learning Prototype, please teach me :)

 

Lastly, there's no such thing as the right way to do things.  There is an accepted, less argued/challenged way.  If things weren't challenged, we wouldn't be using Ajax the way we do now; it has existed for years before it became popular, just no one had the nerve to do something new.  So don't let people stop you from doing things the way you want to.

 

I can't help but think that this is directed at me.  ;-)

 

I learn in a step-by-step manner myself.  I've found, when looking back on the years of struggle I've had in trying to truly grasp JavaScript, that the vast majority of tutorials were severely lacking.  That's why I never recommend w3schools - they teach only enough to fulfil certain simple problems, and never anything about how to be a better coder.

 

While there may not be a right and a wrong way to code, there is a professional way and an unprofessional way.  I firmly believe that teaching best practices, even to new coders, is the way to go.

 

Keep in mind that these best practices don't exist in a vacuum.  There's a lot of logic behind them.  Unobtrusive JavaScript is easier to debug, easier to update, and can be placed in external files.  This, in turn allows an entire site's behavior to be stored in a central location, much like CSS files.  The markup is then separated from the script, making it easier to maintain as well.  A change in one does not necessitate a change in the other.  Also, placing referenced elements in variables improves readablity and execution speed.  It's cheaper for the script to call a variable repeatedly than to continually traverse the DOM with document.forms["myForm"].elements... statements.  In addition, I daresay that my solution to the problem is a hell of a lot easier to read than the tutorial's code.

 

And, honestly, your AJAX comment is a non sequitur.  When the technology behind AJAX was developed, we were living in the dark ages.  It was the age of frequent script errors, user ignorance, and embedded MIDI files.  Many users were distrustful of JavaScript, and turned it off.  Those that weren't as savvy tried to avoid JS enhanced sites where they could.  AJAX, rightfully, wasn't viewed as a practical solution at that time.

 

To the OP, I recommend two books:

 

The first is The JavaScript and DHTML Cookbook by Danny Goodman.  It'll teach you the basics of the language, but not best practices.  Some of his examples are lacking, but it's still a decent introduction to the language.

 

The second is Pro JavaScript Techniques by John Resig, the guy who created the jQuery framework.  This book, quite simply, changed my JavaScript life.  I consider it the most important JavaScript resource ever written.  It's a pretty easy read if you understand the basics of the language, and I guarantee it'll change the way you see JavaScript as a whole. 

 

Once you're comfortable with the language, you should check out jQuery itself.

 

I truly believe that if you want to become a talented, professional JavaScript developer this is the way to go.  My $0.02.

Link to comment
Share on other sites

@Nightslyr

Firstly, I admit, I was a little bored at work while writing my previous comment, and may have gone a bit overboard.  For that, I apologize.

 

However, I was just getting angry that you and the other posters were telling twi.. that he/she was doing it wrong, and to give up and start over.  Hardly encouraging, even if suggesting alternative means.  I figured since most of these errors were placement, and small syntax things, he/she would be best following it to the T until he/she could get it down to and understand what things made it break and what not.  With that understanding, it's much easier to make the jump to external js files, passing variables instead of "full DOM path references" each time, etc..

 

Anyway, I think I'll check out and buy that Pro JS Technique book, going to the bookstore today.  I wanted to learn some better JS, especially to create something along the lines of Relay (http://ecosmear.com/relay/) which uses JS I didn't quite understand.

 

Also, I have looked briefly at JQuery, and more at Prototype.  The others: mooTools, scriptaculous,etc.. don't interest me.  Is it safe to assume they are similar in function (JQuery vs Prototype)?

Link to comment
Share on other sites

Well, I am using Safari, but I opened the file in FireFox and looked at the Error Console as you suggested, but I don't really know the problem still. It is saying several times that the line with the alert in it is an "unterminated literal string" but I don't see where it is not terminated. It is also saying that validateSubmission is not defined. This is how I added the code:

 

<script type="text/javascript">
/*<![CDATA[*/
function validateSubmission() {
  var retValue = true;

if (document.forms[0].subject.value.length > 40) {
   window.alert("The subject must be 40 characters or less!");
   return false;
}
else if (document.forms[0].sender_email.value == ""
   || document.forms[0].recipient_email.value == ""
   || document.forms[0].subject.value == "") {
   window.alert("You did not fill in one of the following required fields: sender e-mail, recipient e-mail, or subject.");
   retValue = false;
   retValue = compareAddresses(document.forms[0].sender_email,
   document.forms[0].recipient_email);
return retValue;
}
if (retValue == false)
      return retValue;

retValue = validateEmail(document.forms[0].sender_email);
if (retValue ==  false)
   return retValue;
retValue = validateEmail(document.forms[0].recipient_email);
if (retValue == false)
   return retValue;
}

function validateEmail(formObject) {
  var email = formObject.value;
     if (email.search("@") == -1
        || email.lastIndexOf(".") == -1) {
        window.alert("One or more of the e-mail addresses you entered does not appear to be valid.");
        return false;
    }
  formObject.value = email.toLowerCase();
  return true;
}
function compareAddresses(senderObject, recipientObject) {
   var senderEmail = senderObject.value;
   var recipientEmail = recipientObject.value;
   senderEmail = senderEmail.toLowerCase();
   recipientEmail = recipientEmail.toLowerCase();
   if (senderEmail.localeCompare(recipientEmail) == 0) {
      window.alert("You entered the same e-mail address for
         sender and recipient.");
      return false;
   }
   else
      return true;
}

/*]]>*/
</script>

 

Can you see what I'm doing wrong? I'm guessing I'm adding the first statement in the wrong place, but I don't understand where to put it other than where I put it according to the directions. Can you help me understand what I'm doing wrong?

Link to comment
Share on other sites

The unterminated literal string is coming from the compareAddresses() function.  It doesn't like the text being split across multiple lines like that.

 

window.alert("You entered the same e-mail address for
         sender and recipient.");

Make it on one line:

window.alert("You entered the same e-mail address for sender and recipient.");

 

And that error will go away, which might solve the other errors.

Link to comment
Share on other sites

Well, I tried that, and now the both errors have gone away, but the script is not working. It is supposed to check to make sure the sender and recipient e-mail addresses are not the same, but it lets them be the same and passes them to the FormProcessor page. But no errors are coming up now on the Error Console. Is my coding still wrong?

 

The script:

 

<script type="text/javascript">
/*<![CDATA[*/
function validateSubmission() {
  var retValue = true;

if (document.forms[0].subject.value.length > 40) {
   window.alert("The subject must be 40 characters or less!");
   return false;
}
else if (document.forms[0].sender_email.value == ""
   || document.forms[0].recipient_email.value == ""
   || document.forms[0].subject.value == "") {
   window.alert("You did not fill in one of the following required fields: sender e-mail, recipient e-mail, or subject.");
   retValue = false;
   retValue = compareAddresses(document.forms[0].sender_email,
   document.forms[0].recipient_email);
return retValue;
}
if (retValue == false)
      return retValue;

retValue = validateEmail(document.forms[0].sender_email);
if (retValue ==  false)
   return retValue;
retValue = validateEmail(document.forms[0].recipient_email);
if (retValue == false)
   return retValue;
}

function validateEmail(formObject) {
  var email = formObject.value;
     if (email.search("@") == -1
        || email.lastIndexOf(".") == -1) {
        window.alert("One or more of the e-mail addresses you entered does not appear to be valid.");
        return false;
    }
  formObject.value = email.toLowerCase();
  return true;
}
function compareAddresses(senderObject, recipientObject) {
   var senderEmail = senderObject.value;
   var recipientEmail = recipientObject.value;
   senderEmail = senderEmail.toLowerCase();
   recipientEmail = recipientEmail.toLowerCase();
   if (senderEmail.localeCompare(recipientEmail) == 0) {
      window.alert("You entered the same e-mail address for sender and recipient.");
      return false;
   }
   else
      return true;
}
/*]]>*/
</script>

 

And these were the instructions again:

 

Add the following statements to the end of the validateSubmission() function. The first statement calls a function named compareAddresses(), which you create next. Notice that parameters are passed to the compareAddresses() function: one for the sender e-mail object and one for the recipient e-mail object. The second statement returns the retValue variable from the validateSubmission() function.

 

retValue = compareAddresses(document.forms[0].sender_email,

  document.forms[0].recipient_email);

return retValue;

 

Add the following compareAddresses() function to the end of the script section. The function accepts two parameters for the sender and recipient e-mail objects, which it assigns to two variables: senderEmail and recipientEmail. Both variables are converted to lowercase with the toLowerCase() method and then compared with the localeCompare() method. If both e-mail addresses are the same, a message displays to the user and the function returns a value of false.

 

function compareAddresses(senderObject, recipientObject) {

  var senderEmail = senderObject.value;

  var recipientEmail = recipientObject.value;

  senderEmail = senderEmail.toLowerCase();

  recipientEmail = recipientEmail.toLowerCase();

  if (senderEmail.localeCompare(recipientEmail) == 0) {

      window.alert("You entered the same e-mail address for

        sender and recipient.");

      return false;

  }

  else

      return true;

}

 

Link to comment
Share on other sites

Hi,

 

You need to add the common check of the return value like you have been doing to your code:

if (retValue == false)
      return retValue;

retValue = validateEmail(document.forms[0].sender_email);
if (retValue ==  false)
   return retValue;
retValue = validateEmail(document.forms[0].recipient_email);
if (retValue == false)
   return retValue;
}

//ADD 
retValue = compareEmail.....
  if(retValue == false)
  return retValue;
}//end of validateSubmission

(as well as add the function to your javascript, just like you wrote on here, but not yet in your code tags)

I am going to say that after this tutorial is finished, you find a nice book (if you don't mind books) that is current to teach you better methods of doing things.  Nightslyr was correct when saying these aren't the best methods of learning, but they still hold some value.

Link to comment
Share on other sites

@Nightslyr

Firstly, I admit, I was a little bored at work while writing my previous comment, and may have gone a bit overboard.  For that, I apologize.

 

However, I was just getting angry that you and the other posters were telling twi.. that he/she was doing it wrong, and to give up and start over.  Hardly encouraging, even if suggesting alternative means.  I figured since most of these errors were placement, and small syntax things, he/she would be best following it to the T until he/she could get it down to and understand what things made it break and what not.  With that understanding, it's much easier to make the jump to external js files, passing variables instead of "full DOM path references" each time, etc..

 

Anyway, I think I'll check out and buy that Pro JS Technique book, going to the bookstore today.  I wanted to learn some better JS, especially to create something along the lines of Relay (http://ecosmear.com/relay/) which uses JS I didn't quite understand.

 

Also, I have looked briefly at JQuery, and more at Prototype.  The others: mooTools, scriptaculous,etc.. don't interest me.  Is it safe to assume they are similar in function (JQuery vs Prototype)?

 

Hey, it's all good. :)

 

jQuery and Prototype are a bit different from one another.  I haven't played with Prototype myself, but a quick scan of its API makes it seem like both a decent framework and a way to integrate inheritance-driven OOP into JavaScript.  jQuery is primarily focused on being a simple (but powerful) lightweight framework.  It's not much more than that.  That said, it's still immensely powerful.

 

A quick example of jQuery in action.  Let's say you have an element that, when clicked, you want to toggle between two colors, and the original state.  So, the element would go from blue, to red, to normal, and back again, depending on the click.  In 'normal' JavaScript, you'd have to write something like:

 

<script type="text/javascript">
   window.onload = function()
   {
      var toggledElement = document.getElementById('toggle');

      toggledElement.onclick = function()
      {
         if(this.style.color == "black")
         {
            this.style.color = "blue";
         }
         else if(this.style.color == "blue")
         {
            this.style.color = "red";
         }
         else
         {
            this.style.color = "black";
         }
      }
   }
</script>

 

In jQuery, it'd be:

<script type="text/javascript">
   $(document).ready(function()
   {
      $("#toggle").toggle(
         function(){ $(this).css({"color : blue"}); },
         function(){ $(this).css({"color : red"}); },
         function(){ $(this).css({"color : "}); }
      ); //end toggle function
   }); //end ready function
</script>

 

jQuery really comes into its own when you start playing with AJAX.  It's really nice to simply write something like:

$.post("backendScript.php", {name : "Bubba", age : "23"});

 

Without having to worry about creating xmlhttp objects, or keeping tabs of the ready state.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.