Introduction

JavaScript’s increasing popularity throughout the web makes it more important than ever to make sure our client side code is implemented with a nice mix of stability, speed, and reusability. One of the best ways for accomplishing this is to use a simple library and syntax to use as a foundation for every project. Thankfully, Sam Stephenson created an amazing library of functions that we can rely on called Prototype.js to ease our JavaScript development practices.

HTML Form Builder

After our readers pointed out in an previous feature that our frequent use of Prototype syntax was making things a bit confusing, we decided it would be best to create a quick reference page for the library to help ease the learning curve for a lot of developers out there. The following tutorial will explain the most common methods used in Particletree projects with simple examples of how to implement them. This guide is meant to be used hand-in-hand with the more exhaustive unofficial Prototype documentation by Sergio Pereira, and the script.aculo.us documentation wiki, which I highly recommend every serious JavaScript / Prototype developer read.

Getting Started

After you have downloaded the files and placed them in your preferred directory, all you need to do is include them in your html document like so:

<script src="/scripts/prototype.js" type="text/javascript"></script>

Boom. JavaScript just got 10x easier to develop. Now, let’s looks at some of the cool new weapons you just acquired.

Note - This tutorial is based off of version 1.3.1.

$() Function

The most used and convenient function, $(), provides an easy way of getting a handle on a DOM element. Normally, if you would like to access an element in the DOM, it would look like this:

node = document.getElementById("elementID");

Using $(), we can shorten it up.

node = $("elementID");

Other than being short and sweet, the $() function is also more powerful than document.getElementById() because the ability to retrieve multiple elements is built into the function.

allNodes = $("firstDiv", "secondDiv");
for(i = 0; i < allNodes.length; i++) {
    alert(allNodes[i].innerHTML);
}

In this example, we see the $() function now returning an array of our elements, which can then be accessed with a simple for loop.

Form Helper Functions

Yes, not only are forms a pain in the ass from an HTML and CSS perspective, but also on the JavaScript side of things. Prototype.js provides useful and creative functions that make dealing with forms almost fun.

The $F() function returns the value of the form element or ID passed in. If we put together the following HTML fields:

<input type="text" id="textfield" name="textfield" />
<textarea rows="5" cols="5" id="areafield" name="areafield"></textarea>
<select id="selectfield" name="selectfield">
    <option value="1" selected>One</option>
    <option value="2">Two</option>
</select>
<input type="checkbox" id="checkfield" name="checkfield" value="1" checked />

We can then access the values in the form easily by using the $F() function.

$F("textfield");      // returns the value of the text input
$F("areafield");      // returns the value of the textarea
$F("selectfield");    // returns the selected value of the select
$F("checkfield");     // returns undefined if not checked, or the value

The ability to get a value regardless of the control makes processing forms incredibly easy in most circumstances. There are only two drawbacks I could find with this function: 1) there is no easy way of accessing the selected value of a radio group (only the individual value of a single radio element) and 2) it is not possible to pass in multiple ID’s, like you can with the $() function.

*Another function, Form.getElements() will return an array of every form element, regardless of the type.

allNodes = Form.getElements("myform");
for(i = 0; i < allNodes.length; i++) {
    //do something to each form field
}

In this example, we’re getting every element from a form with the id of myform. If you want to add an onclick effect, or a help window popup to each form field, you can loop through as shown above.

The next method we will look at is Form.serialize(). When building an Ajax request, you often need to format your own post string to pass the data. When the form is submitted, that string is built. serialize() makes the process easy.

allNodes = Form.serialize("myform");// returns field1=value1&field2=value2&field3=value3 and so on...

Building the string for us helps out, but what makes the method even nicer is that it is not biased towards the type of field. We saw before that $F() had some problems with radio groups, but serialize() processes all of the values correctly for any type of field. These are not the only form methods available, so go check out the Sergio’s documentation for the rest.

getElementsByClassName

Why getElementsByClassName()is not already built into JavaScript is beyond me, but it’s not and so Prototype had added to it to the arsenal as an extension of the document object. It behaves exactly like document.getElementsByTagName(), the only difference being that it checks for className.

allNodes = document.getElementsByClassName("red");
for(i = 0; i < allNodes.length; i++) {
    alert(allNodes[i].innerHTML);
}

An array is returned containing all elements that match the given className. This will also work with elements that have multiple classNames, which is nice. getElementsByClassName() has become a function used in nearly every project around here, mainly to attach DOM events so I suggest every developer give it a try.

Element Helper Functions

The Element Object provides a load of helper functions (increasing with each release) that assist in common DOM manipulation practices. Some of these functions create no new ease, while others simplify 10+ lines of code into one call. Let’s take a look at some examples.

Retrieving the height of an element without the helper:

$("first").offsetHeight

And now with the helper:

Element.getHeight("first")

In this case, the helper arguably provides no benefit. Now, what if we wanted to remove a className from an element? Here is the long way (taken from the Prototype.js source code):

element = $(element);
if (!element)
    return;
var newClassName = '';
var a = element.className.split(' ');
for (var i = 0; i < a.length; i++) {
    if (a[i] != className) {
        if (i > 0)
            newClassName += ' ';
        newClassName += a[i];
    }
}
element.className = newClassName;

And now with the helper function:

Element.removeClassName("elementID", "red");

Nice, eh? Unlike the first example, most of the helper functions save a lot of time and effort by making common tasks easy. And for the sake of consistency, it may be best just to use the Element syntax throughout the project. For a full list of helper functions and how to use them, check out Sergio’s Prototype documentation.

Try.these Function

Try.these() is a great function for helping developers create code that will work regardless of the different JavaScript implementations across browsers. Instead of doing object or browser detection on your own, this function will attempt to execute one path of code until it encounters an error, and then switch to the next path.

return Try.these(
    function() {
        alert("first");
        jkgjhgjhg        //intentional error
        alert("firsterror");
        return 1;
    },
    function() {
        alert("second");
        return 2;
    }
);

In the example above, the first path will stop executing at the intentional error. Knowing that, it is important to be cautious with our code because everything before the error will get executed, we must be careful not to execute code twice (once in each try). Overall, Try.these() is not a function we use often around here, but it is nice to know it exists and how it functions.

Ajax Support

There is no shortage of Ajax support functions in this library, and I would like to give you a look at how we primarily create Ajax applications with the help of Prototype.js. Taken from the documentation, we can see a normal Ajax request can be made as follows:

var myAjax = new Ajax.Request(
    url,
    {method: 'post', parameters: data, onComplete: ajax_response}
);

Where method is post or get, parameters is the name/value paired query string, and onComplete is the function that should be called when everything is finished. Once the core functionality is understood, it is easy to make repetitive Ajax calls by creating our own functions that utilize the library. First, a simple function to process the Ajax request.

function ajax_request(url, data) {
    var myAjax = new Ajax.Request(
        url,
        {method: 'post', parameters: data, onComplete: ajax_response}
    );
}

And after the request is finished, send it over to ajax_response().

function ajax_response(originalRequest) {
    if(!bHasRedirect) {
        //process originalRequest.responseText;
    }
    else {
        bHasRedirect = false;
        ajax_request(originalRequest.responseText, "");
    }
}

After you make an Ajax request, the response is always sent to ajax-response(). From there, another Ajax request will be made if bHasRedirect is set to true (a global variable), and if not then the proper code will be executed based on a global array of functions and originalRequest.responseText() (the return value).

PeriodicalExecuter

Once the PeriodicalExecuter object is initialized, it repeatedly calls a desired function at a given interval. This comes in handy when you wish to auto update an Ajax portion of your site.

function periodicalUpdate() {
    new PeriodicalExecuter(refreshNews, 10);
}function refreshNews() {
    //Ajax code to grab news and update DOM
}

The PeriodicalExecuter constructor expects the function to call as its first parameter, and the time interval as its second. Don’t get confused with the time though - the common setInterval() is handled with milliseconds, but in this function we’re dealing with seconds. Also note that while this example assumes Ajax is involved, it can update the page for any reason. Prototype.js also has a Ajax.PeriodicalUpdater class that can ease the process when dealing solely with Ajax.

Additional Enhancements

While I can’t cover every single function or method that Prototype.js offers, it is still important to emphasize some of the ones not covered here (all of which can be found in the documentation).

observe - This method functions like addEvent(), and should be used to unobtrusively attach events to the DOM.

User Interaction - You can find built in globals, such as KEY_TAB to evaluate what key presses the user is making. Additionally, you can find out the coordinates of the mouse, and if it has been clicked.

Class Creation - Why stop with what Prototype.js provides? Using the same syntax and functions, we can build our own classes to keep things consistent. Adding a constructor and additional methods has never been easier. Lookup Class.create() in the documentation.

Wrap It Up

Is it acceptable to use public code/libraries when you do not know the author and do not intimately understand what happens behind the scenes? My answer is yes, as long as you thoroughly test the code and trust the person/community that is behind the development of it. In the case of Prototype.js, trust is built from two sources. First, Ruby on Rails has integrated prototype support. Since Ruby on Rails has a respectable developer base, it is likely that many bugs have been found and ironed out to make Prototype.js more stable. Second, the developer works for 37signals, who happen to employ the creator of Ruby on Rails. Not only do I trust the development practices of the company, but I trust that Prototype.js will continue to be tested and improved upon. Given that, and testing within my own projects, I confidently use this library in nearly all my projects.

Prototype.js more than doubles the functionality listed in this tutorial, and it is definitely worth checking out. If you’re scared of the file size (it’s 30k as of this writing), remember that you can always take out classes that you don’t use (minus the few that have dependencies) and/or compress your JavaScript files with PHP before serving them out to your user. Also, once you have tried a few of the methods, the rest are easy to learn, so the learning curve is very minimal. Basically, there is no excuse not to give it a try. The examples shown above are how we handle things at Particletree, and should not be used without testing. Remember, this is meant to be an introduction to Prototype.js, so always reference and give credit to the unofficial Prototype documentation and the script.aculo.us documentation wiki for all of the hard work put in to find out the various methods. As always, if you find any mistakes or possible improvements, please point them out.

HTML Form Builder
Ryan Campbell

Quick Guide to Prototype by Ryan Campbell

This entry was posted 5 years ago and was filed under Features.
Comments are currently closed.

· 131 Comments! ·

  1. Remi Prevost · 5 years ago

    Great tutorial! It helped me a lot since I’m kinda new at using Prototype. :-)

  2. Mislav · 5 years ago

    Here is another comprehensive prototype reference that provides a quick overview. I like it the best (after absorbing the other two, naturally).

    Note that the Scriptaculous library ships with Prototype version 1.4.0_rc2 that has some changes and many additions, most notable of which is JSON support in AJAX requests. Sadly, JSON in Protoype hasn’t yet been documented or discussed.

  3. Ryan Campbell · 5 years ago

    Good find Mislav. I have not come across that link before, but it deserves a mention. I agree with the JSON documentation problem. I am just starting to play with it, and better documentation would make the barrier to entry much lower. Once I feel confident with it, I will begin writing more about it.

  4. Peter Mescalchin · 5 years ago

    Nice heads-up and some very useful functions, definately a fan of $();

  5. Jonathan Snook · 5 years ago

    You don’t really explain the global variable bHasRedirect. I can gather why it’s there but is it a global variable set by Prototype or one that you’ve defined?

  6. Ryan Campbell · 5 years ago

    bHasRedirect has nothing to do with Prototype. It is just a variable I set to keep track of the Ajax calls. Sorry for not making that clear.

  7. Zach Inglis · 5 years ago

    Brilliant, I was told to look into it for my form extraction needs yesterday and today I see this.

  8. Dustin Diaz · 5 years ago

    It’s good to see some solid documentation. I know that the scriptaculous wiki has a fair amount of prototype documentation and to this day there really seems to be no place to ‘find it all’. Nevertheless this article can prove to be another solid reference.

    The Prototype Element object (aside from $()) has by far been my favorite subset of the library. It includes other methods like Element.hide, Element.show, Element.toggle, Element.remove… even Element.cleanWhitespace which has helped immensely when trying to walk the DOM correctly.

  9. Justin Palmer · 5 years ago

    Great write up Ryan. Just to clear up some things that might confuse your readers, getElementsByClassName behaves exactly like getElementsByTagName with one exception:

    var children = $('header').getElementsByTagName('p'); //var children2 = $('header').getElementsByClassName('foo'); // will not work var children3 = document.getElementsByClassName('foo', 'header'); alert(children3.length);

    When you want to specify a parent object to start from, the tagName approach would be to retrieve the partent node first and then parentNode.getElementsByTagName, but with the className approach you can’t do this, you need to pass the parent as the second argument in the function (e.g. getElementsByClassName(‘foo’, ‘parentNode’);

    -Cheers

  10. Ryan Campbell · 5 years ago

    Ahh, good call Justin. I wasn’t aware of that.

  11. Robert Nyman · 5 years ago

    Ryan,

    Thanks for this article. I just feel the need to mention some things:

    1) While I think it’s good to get people to use JavaScript more, it’s also essential that they do understand how it works. If they just use some magic funtion without knowing why it actually works, or more importantly, what’s the problem when it doesn’t work, then they have a problem. Basically, I just encourage learning JavaScript as well. Then, after that, use libraries if you like it.

    2) I find it a bit inconsistent to use $ in some cases, and then methods of objects, like document.getElementsByClassName in others. Choose either a functions or a methods approach, and then go with it.

    3) Of course I have to blow my own trumpet (or something) and mention the getElementsByClassName that Jonathan Snook and I came up with. I think it’s more flexible, and more importantly, better performance-wise. However, I would see it as an easy thing to implement it in Prototype.js

    From my point of view, libraries are seldom interesting. While Prototype.js seems very competent, there’s always more functions in a library that one will use in a solution. Since we’re in the days of always trimming, optimizing etc, I only want the functions included that are used.

    On the other hand, I do understand that it might be good for beginners to at least see the possibilites of what can be accomplished.

  12. Ryan Campbell · 5 years ago

    Robert,

    You make some good points. Let me respond to them in the same order:

    1) Learning is always the most important. I have a soft spot in my heart for libraries (especially Prototype) because they teach me things that I am not aware of. First, I learn new syntax or more efficient ways of doing things. Second, some of the functions are very clever, and I may have never thought of them. But then again, I went through the entire source code line by line, and I don’t expect every person will do that.

    Here’s an interesting thought. People will use the library without understanding it. Two negatives can come out of this. First, people may misuse functions. Second, people may blindly use “bad” libraries that hurt more than they help. So what if people endorse certain libraries (such as Prototype) that are safe to use. That is worth it, because good libraries probably produce better code than the coders would on their own (myself included).

    2) That’s very true and it never occured to me. A $C() function for classnames could easily be made to stay consistent with the other $() syntax. I don’t know if that’s a real solution, but I think it comes down to personal preference. I know I am in love with the $() syntax.

    3) I agree that your function is much more powerful. I actually have it implemented in the version of Prototype that I use, and I would recommend others to do the same.

  13. Robert Nyman · 5 years ago

    Ryan,

    1) If one’s willing to learn, libraries can definitely be a good source for learning and understanding. However, I don’t think most people do that, they just want it to work. Which is ok, I guess, but I recommend learning as well, if things go awry.

    Then, the bulk argument still stands with superfluous functions one doesn’t use in the library. :-)

    2) Absolutely, I love the syntax too!

    3) A humble thank you! :-)

  14. Ryan Campbell · 5 years ago

    Yes, there is no answer to solve the unnecessary additional functions for people who don’t browse the source code. Unless someone comes along and writes a “Build Your Library” program that allows you to pick and choose functions and dynamically generates the source code. That’s taking it to far though, but it would be cool to see.

    I am just being difficult. I agree with your argument.

  15. Justin Palmer · 5 years ago

    Robert, I believe libraries do less harm than good. The extra functions you won’t ever use are sometimes used internally by the functions you do use and they are just there when you need them.

    When your building an application, your not aware of what you’ll need before you start. If you have a flat tire on the side of the road, you can be sure the mechanic brings more than just a lug wrench.

    Libraries also encourage consistency in programming style. Prototype encourages you to use OO Javascript, and when I read someone else’s code it’s easier to point out what’s coming from where. Now you don’t need any library for this to do it on your own, but Prototype has been widely adopted and it has become easier for me to read other peoples code.

    Last point, the LOC will more than likely be less by using a library in a large application than going at it alone because of abstraction. When you want to attach an event, you have a unified approach, no need to bother with crowding your own Javascript with something the library takes care of for you.

    -Cheers

  16. Robert Nyman · 5 years ago

    Justin,

    Agreed; it definitely depends on where and when they are being used, as well as who uses it.

    What I see from time to time, though, is libraries included in solutions that are huge, and maybe 25% are being used in practice. But by the time the whole web site is due to be released, no one dares to remove anything from the library, because things might break and they’re not sure if/when that will happen.

    However, I do have to give the new libraries that are popping up credit. They’re being smaller in size and more optimized, so some are decent to use.

    When it comes to consistency in programming style, I’m all for it. But, as I pointed out in point number two above, most libraries aren’t all that conistent, so I really encourage library builders to strive for that.

    Then, naturally, I also have some code that I bring with me from project to project, but that code is basically just the getElementsByClassName mentioned above and code for attaching events.

  17. Jorj Ives · 5 years ago

    In regards to having superfluous functions in prototype, how about splitting prototype up into seperate files for each function. A single function could be called, with the functions needed as parameters. This way, only the functions needed would be loaded, and different function sets could be loaded for different pages without having to have multiple libraries stored.

    I’m not a javascript developer (yet) so I’m not sure whether there are server load issues with loading multiple files, but this seems a sensible solution to me.

  18. Dave · 5 years ago

    Is there a “minimal” version of Prototype.js floating around somewhere for those concerned about the file size?

  19. Jorj Ives · 5 years ago

    I noticed Justin mentioned that some functions are needed by other functions even when they aren’t needed directly by the user.

    Could a function check whether another function existed? If so, in the system I suggested above the function could load in the required function if it wasn’t available.

  20. Ryan Campbell · 5 years ago

    Dave, I believe the moo.fx package comes with a stripped version.

  21. Bradley · 5 years ago

    Since you asked, I have combined a few prototype “stripped” versions to make Ajax and moo.fx possible. 6.4kb total.

    Click my name, it’s on the homepage. Sorry for the plug, but I’m not even tracking downloads so I’m just trying to be helpful. :)

  22. Rogers Reilly · 5 years ago

    The dojo toolkit (http://www.dojotoolkit.org) is an AJAX/DHTML widget library that provides a lot of Prototype-like helper functions, plus graphical widgets, drop-n-drag, effects, and other stuff.

    Not having used Prototype, I can’t recommend one over the other; but I’m posting here because dojo actually does have a utility that allows you to pick and choose which parts of the library to include in your source, and even compresses that JS code into the smallest possible file for use in deployment. (don’t try debugging w/it … all the variable/function names go “poof,” shrank to tiny pieces :) )

    Here’s the link:

    http://blog.dojotoolkit.org/2005/08/14/making-code-smaller-safely

  23. William · 5 years ago

    Very helpful artical Ryan. Thankyou for your examples and clarification on the use of the convenient Prototype functions as I could not find any docs untill now.

  24. Mislav · 5 years ago

    Ruby-like features in Prototype explained: A Look at Enumerable, Array and Hash. Really nice!

  25. Abba Bryant · 5 years ago

    In response to Ryan Campbell’s Build Your Own Prototype Library idea.

    Does this sound like a prototype project / AJAX experiment waiting to happen to anyone else?

    Yeah? Email me.

  26. Mislav · 5 years ago

    I think that Build Your Own Prototype Library ideas are dangerous. Prototype is huge, but it’s still less than 30kB - and that compressed would be around 5kB. Still too much for you? Once it is cached, a user seldom needs ever to download it again.

    Why are dynamic pieces of prototype dangerous? Sure, it can be written and sure, it would effectively strip down those unwanted helpers, but you have to realize that one part of your site would not need Ajax, one would, one would need the Position object, one would need Forms… So in this example we face downloading 4 different dynamically created javascript files that still have most of their parts equal, thus creating redundant downloads for a person that browses different parts of your site.

    The problem described here could be solved by creating static pieces (atoms) of Prototype in separate files and link them dynamically into our pages so we can benefit from caching, but how much requests would that be? Is it really worth it.

    The perfect world would be in which we would all link to Prototype directly on Sam’s site. That way a user browsing through several different sites would only need to download one copy of Prototype and cache it :)

  27. Jon · 5 years ago

    Can someone tell my why someone would use the $F() function when you can just use the $() function? Thanks.

  28. Ryan Campbell · 5 years ago

    Jon, the $() function just grabs an element by ID, while the $F() function gets the value inside of an element. For example, to grab what someone typed in a textbox with the two functions:

    $(“tBox”).value

    or

    $F(“tBox”)

    That is a simple example, but it becomes even more useful with the different types of form elements.

  29. Owen · 5 years ago

    Hi everyone, I am new to webprogramming and AJAX in specific. I am very proficient in Java and have created and used XML tags for servers, but have never set anything up on my own.

    I read through the tutorial, but there are still some issue I am unclear on. I understand that the code goes in the html file for my webpage. However, I am unclear where I use functions, such as $F(). These certainly arent HTML commands.

    An explanation on how to set everything up would be nice. Right now, I am completely in the dark.

  30. Rob Elkin · 5 years ago

    Brilliant artice Ryan, Treehouse subscriber here, glad to find some more of your work.

    Owen, you need to use the $F() functions and the Element.getElementByClassName eetc in tags, then in the script tags write functions like :

    function doSomething() {

    //put my $F() coding here

    }

    and call the function on the click of a html button or anywhere where you want it to work.

  31. Mark Barton · 5 years ago

    Hi Ryan,

    Quick question about making multiple AJAX calls using the library. Assuming the responses may not come back in the same order you sent them how can you use a generic response handler?

    You state you use a Global variable to determine whether a subsequent AJAX call should be made (bHasRedirect ) but how do you know that the returned call relates to that instance of the global variable?

    Thanks

    Mark

  32. Ryan Campbell · 5 years ago

    Mark - Actually the application I used that code in had no chance of Ajax calls overlapping each other, so it was not important. But you are right, the code I provided does not take that into consideration, and would have to be built in.

  33. wahyu · 5 years ago

    are there any dummies or more real life use documentation for prototype, i try to start learning ajax but i still can not do such as things like populating labels. How is it if i habe php which output in a loop and i use ajax.updater on the other side to populate the , how can i display the options and assign a value to each option.

  34. wahyu · 5 years ago

    ups seemed like the comment i wrote above has been cuted off maybe because of i wrote some html code. ok the point is how can i populate a dropdown form element after a loop of the php script output the option tags (html) with the label and value. How can i update the dropdown form element.

  35. Galen · 5 years ago

    Nice article. I feel like I am slowly coming to grips with the AJAX thing but I still have not managed to actually figure out where to start to include AJAX in a web application. I would love to be able to allow users to add new categories to a drop-down menu (somewhat like the categories feature in WordPress 2.0) but can’t find info on this anywhere. It would be great if someone came up with a simple, real-life tutorial for web designers/programmers who know PHP/MySQL/HTML and a bit of JavaScript. Keep up the good work folks!

  36. Noah Winecoff · 5 years ago

    Thanks for the write up on prototype. It helped me really see and understand what all prototype has to offer. Great work.

  37. peter · 5 years ago

    possibly I haven’t looked through it enough; but i think an obj -> XML ; XML -> obj method would be a very useful addition to your Ajax class.

    I need/want a JS library that provides the following:

    data (objs) -> XML -> encryption (optional) -> AJAX request

    and then the reverse AJAX/decrypt/deXML handler

    anyone know if this exists somewhere

  38. Vortex · 5 years ago

    hello im from mexico and so sorry but , i want to know something, im neophite on Ajax technologies, and i wanna know if i have to configurate something on my server, cause, i been trying example codes, and i cant to fly with ajax, i need an explanation, well add me to contacts… guarnizzz h o t m a i l

    greetings!!

  39. Matt · 5 years ago

    I’m wondering if anyone has addressed the points brought up regarding the altered behavior of Arrays which result from the prototype.js library?

    http://blog.metawrap.com/blog/WhyIDontUseThePrototypejsJavaScriptLibrary.aspx

  40. K2 · 5 years ago

    I need to do a server-side validation in my form which I intend to do without refreshing the page. This would require an synchronous call to the server. Any idea, how I can achieve this using ProtoType? This won’t require a callback and I am interested only in the responseText.

    Thanks in advance!

  41. snag · 5 years ago

    Everyone needs a hug.

  42. Russ · 5 years ago

    This may be a really dumb question but from what I can gather the prototype lib only works on Safari 1.2+ and this seems to be confirmed when I get limited functionalty and unexpected behavious in Safari 1.0.2.

    Is there a simple way to quit if a browser does not support the library?

    i.e. if (! blah.blah) return;

    Prior to prototype I would use

    if (! document.getElementByID(“el”)) return;

    Or maybe my head’s too full trying to get to grips with this and I’m missing something glaringly obvious? :-)

  43. Jim Hunter · 5 years ago

    I see that you can easily create new Classes using the Class.create() call but I want to make my site 100% Javascript so I need to create new HTML elements. How is everyone doing that? Or are you? And once you have a new HTML object, how are you getting the HTML out of it to add to another object via Insertion.Top or one of the other Insertion methods? I just found Prototype yesterday and I am trying to hit the ground running and currently my application is all Javascript (longhand) and I want to streamline it with Prototype.

    Thanks!

  44. Tony · 5 years ago

    Is there a way of grabbing an XML document and parsing it using Prototype and if there is does anyone have a tutorial or even better yet a code snippet on how to do that?

    I could really use the help.

    Thanks, Tony

  45. Gary · 5 years ago

    Everyone needs a hug.

  46. Nicola · 5 years ago

    It’s a great tutorial but with a little online example or demo could be better ;)

  47. Clemente · 5 years ago

    I’m trying to use Event.observe in IE (in FireFox it seems to work fine), but when the event hanling function is called, the only parameter is the event object, so how do I access the DOM element which captured the event?

    I have tried event.srcElement, event.boundElements, and this, but neither contain the DOM element in question.

    I would appreciate any help.

    Thanks a lot.

  48. Clemente · 5 years ago

    I forgot. I also tried Event.element(event), and nothing yet… :(

  49. Ryan Campbell · 5 years ago

    Event.element(e) will get it for you. Also, you can use the prototype bind() function to make it so that the this keyword will reference the element.

  50. Lycos Greg · 5 years ago

    couldn’t find anyting in Prototype to do a get/set on a form radio element, so i came up with this and though i’d share.

    given a form id , radio element name, and an optional value, this will do the dirty work for you.

    feedback appreciated. =)

    function radio_value (form, name) { var set_value = arguments[2]; var elements = Form.getElements( $(form) ); for (var i = 0; i couldn’t find anyting in Prototype to do a get/set on a form radio element, so i came up with this and though i’d share.

    given a form id , radio element name, and an optional value, this will do the dirty work for you.

    feedback appreciated. =)

    function radio_value (form, name) { var set_value = arguments[2]; var elements = Form.getElements( $(form) ); for (var i = 0; i

  51. Allan · 5 years ago

    K, this is my dumb question for the day, but being new and finding the ajax response time to be a bit ‘sluggish’

    Is it good practice, does it add to overhead, to reinitialize the Ajax.Updater object on each call?

    var MyAjax = new Ajax.Updater(…

    I can’t seem to create once and reuse so perhaps thats just the way things work ;)

  52. Nilanjan · 5 years ago

    if I want to grab the responseText instead of replacing the div id in prototype then how to do it

  53. DantoNetwork · 4 years ago

    PeriodicalExecuter why do i need this? Is there any advantages over setInterval?

    Ajax.PeriodicalUpdater now this makes sense, but the PeriodicalExecuter i can’t see why they created it…

  54. gibex · 4 years ago

    good article. helped me to solve my radio boxes problem.

  55. Tom Loudon · 4 years ago

    Someone may have already added this but as an addition to the following.

    allNodes = $(“firstDiv”, “secondDiv”); for(i = 0; i

    You can use the following which I find a little more readable.

    allNodes = $(“firstDiv”, “secondDiv”); allNodes.each(function(node) { alert(node.innerHTML); });

    You can even shorten it by getting rid of allNodes.

    $(“firstDiv”, “secondDiv”).each(function(node) { alert(node.innerHTML); });

    I hope someone finds that useful.

  56. 454 · 4 years ago

    Everyone needs a hug.

  57. Rob McMichael · 4 years ago

    This is really helpful! Prototype is missing a good bit of coverage of what it can really do!

  58. jen · 4 years ago

    Thanks! This is useful

  59. ia this ajax? · 4 years ago

    Everyone needs a hug.

  60. HaveAjaxWillTravel · 4 years ago

    i needs a hug.

  61. MT · 4 years ago

    Great, but it’s not jQuery….

  62. skonealone · 4 years ago

    Here is another http://www.sergiopereira.com/articles/prototype.js.html comprehensive prototype reference that provides a quick overview. I like it the best referance around the internet n hope this line will be usefull every one.

  63. alex · 4 years ago

    Everyone needs a hug.

  64. Rocky4wEB · 4 years ago

    Please guide me how to validate a form field through validation.js i have four fields and all are required, but i need to check one box value by clicking on a text.

    1: currently when i click says(validate email) on that text it display all the required fileds but i just want to display only that filed

    and

    2: the message for all the fields when i click on submit.

    i have solved the second one but i am not able to solve the first one.

  65. stone · 4 years ago

    I don’t know if anyone is actually paying attention to this post anymore, but…

    Am I crazy or does $F not work with form elements that don’t have an ID under firefox? Seems to work fine under IE, but I can’t get prototype to return form field values using the $F notation without ID’s…

    (PS: if you tell me my email is optional, you shouldn’t throw an error when I don’t enter it)

  66. Colombia · 4 years ago

    This is the good way to get the value of the selected input radio in a group.

    var radiovalue; Form.getInputs(‘formHere’,’radio’).each(function(input) { if(input.checked) {radiovalue=input.value}; });

  67. Colombia · 4 years ago

    There is a problem, if you have more than one radio group you will to need check the name too, so:

    var radiovalue; Form.getInputs(‘formHere’,’radio’).each(function(input) { if(input.name==”nameofradios”&&input.checked) {radiovalue=input.value}; });

  68. Pozycjonowanie · 4 years ago

    This may be a really dumb question but from what I can gather the prototype lib only works on Safari 1.2+ and this seems to be confirmed when I get limited functionalty and unexpected behavious in Safari 1.0.2.

    Is there a simple way to quit if a browser does not support the library?

  69. dibakar · 4 years ago

    Can anybody told me how can I use prototype for uploading file though I know javascript cannot read local files. But, is there any way around through which I can use both prototype feature and file upload together.

  70. Httpete · 4 years ago

    I have developed a Prototype based HTML table filtering script, which looks at a table column, populates a DD menu with those values, and filters the rows based on that value. Here it is:

    http://httpete.com/htmlTableFiltering

  71. Dotan Cohen · 4 years ago

    Does anybody know of a Prototype forum? I’m having problems with Forum.serialize, and I’ve nowhere to ask. I’ve asked in Javascript forums, to no avail. A link would be nice, thanks.

  72. rahul · 4 years ago

    coolest tutorials ever seen, thnx man

  73. tuxaanand · 4 years ago

    Its absolutely cool. i was searching for a good Prototype tutorial. Thanks

  74. Internetfirma Köln · 4 years ago

    Yup, absolutely cool, helpful and simply explained - that what i needed, thanks!

  75. Arkilus · 4 years ago

    Really Nice, thanks Ryan.

  76. Thomas Hansen · 4 years ago

    Everyone needs a hug. ;) About the each function, check also out this one: http://www.frostinnovation.com/Blog.aspx?blogId=7e3e7b5e-e41c-4c1b-998f-1e7b7750cb7a

  77. Phani Medicherla · 4 years ago

    Great article Ryan. Many thanks for putting it out here. This helped me out in understanding about what Prototype is and what we can do with it. Cool…

    As of Dojo, do we have any concept like ‘Widget’ supported in Prototype?

    Thanks

  78. jc · 4 years ago

    Entirely wonderful thank you - just what I needed!

  79. Alex · 4 years ago

    Here is another source for Prototype documentation with a bunch of examples:

    http://www.formar.se/prototype

  80. Arthur · 4 years ago

    Congratulations. This tuto helps me a lot.

  81. Eylon · 4 years ago

    Hi,

    I am building a new site in Hebrew using prototype.js Everything works fine, but not the new Ajax.Request(‘./nextPage.php’, {method:’post’,…. In nextPage.php I get strange character although I added header(‘Content-Type: text/html; charset=WINDOWS-1255’); in the start of the PHP.

    Do you know if and how I can specify the Ajax.Request to use charset=WINDOWS-1255?

    Thanks and Best regards, Eylon

    The site which I am building: http://www.yaldut.com

  82. Aukcje · 4 years ago

    Thanks! This is very useful. Greetings

  83. Ali · 4 years ago

    I want to submit a form that contain photo file, form is submitted by update js class but file is not posted. please guide me how to use updater event for file submitting.

    thaks,

  84. AjaxNedir · 4 years ago

    Very helpful informations. Thanks…

  85. Graham · 4 years ago

    100th Comment. Nice but would be good to have it updated for prototype 1.5

  86. Thomas Hansen · 4 years ago

    Everyone needs a hug. Wow, I would seriously consider getting some “no-bot” protection here if I were you, but since everybody obivously is posting commercial here I’ll be no different… ;) http://ajaxwidgets.com There, now you’ve had it… ;) Though We’re actually USING prototype.js so I think we have more “rights” to be here than the viagra guys… ;)

  87. net · 4 years ago

    Everyone needs a hug.

  88. ethics business · 4 years ago

    Nice layout great content on this site - congratulations!

  89. Opel Astra · 4 years ago

    Nice layout great content on this site - congratulations!, Espaccialy Super Layout

  90. ATC · 4 years ago

    can anybody sugest a tutorial for integrating php with prototypes using ajax

  91. BMW Gebrauchtwagen · 4 years ago

    Everyone needs a hug.

  92. Titleist · 4 years ago

    Everyone needs two hugs.

  93. CMS · 4 years ago

    Nice layout great content on this site - congratulations!, Espaccialy Super Layout

  94. Horoskop · 4 years ago

    Its absolutely cool. i was searching for a good Prototype tutorial. Thanks

  95. Kinder am Nachmittag · 4 years ago

    it´s still a big impact to read this! thanks!

  96. gutschein · 4 years ago

    I searched a long time for such an great article. Thank you very much.

  97. Kooperation · 4 years ago

    Everyone needs a hug. this really is true!

  98. Srinivas · 4 years ago

    Great work and really makes life easier to everyone who use it. Iam new to it and really impressed me a lot.

    Thanks.

  99. Olbernhau · 4 years ago

    interesting site. very good work

  100. Herbal · 4 years ago

    I was looking for any article about this from several weeks. And I foud it here. Many thanks. Good job, man.

  101. Regenbekleidung · 4 years ago

    I think these blog is really useful for new comers and Excellent resource list. It´s a very interesting Blog and simple answer of many questions. Keep up the good work!

  102. josh · 3 years ago

    Great article Ryan. Many thanks for putting it out here. This helped me out in understanding about what Prototype is and what we can do with it. Cool…

  103. mike · 3 years ago

    The best article for newbies! But could you help with one problem: I want to check form using prototype’s Ajax.Request and if user fills form right, then redirect(!) he to second page for registration with(!) right GET or POST variables from form otherwise, show him message. Could you help me?

  104. Blumen · 3 years ago

    Nice article. good explanation of the topic and simple examples

  105. Forum · 3 years ago

    Good article for everyone. Want more ! :)

  106. Pokoje · 3 years ago

    I just found Prototype yesterday and I am trying to hit the ground running and currently my application is all Javascript (longhand) and I want to streamline it with Prototype.

    Nox Tox.

  107. Thomas · 3 years ago

    prototype is the best javascript library out there. i’ll use it for all my new projects. and btw that’s a great tutorial.

  108. Handwerkersoftware · 3 years ago

    A large number of humans in a the position the fundamental ideas of this honor language are to be learned by the visible complexity. Also I rank myself among this majority. My interest lies not in the handling of a Programiersprache separates in the ability to learn of a technology for the publication of contents on my Website. With HTML4 I can begin already very much. But I am grateful and content.

  109. Thomas Ericcson · 3 years ago

    Hi, all the informations on this website helps a lot, thanks. keep on doing and kind regards from germany !!

  110. Baz L · 3 years ago

    Everyone needs a hug.

  111. Yash · 3 years ago

    Everyone needs a hug. and here I’m giving you mine…Its nice tutorials.I would like to know whether prototype provides functions for XML also..plz include those also in ur tut.

  112. Esteban · 3 years ago

    Everyone needs a hug. Thanks good article…this resolve my problem in some forms…excuseme my english.

  113. David · 3 years ago

    Thanks for this doc, it’s the one i need !

  114. Christoph · 3 years ago

    A great instruction. We see: Everyone needs a hug.

  115. otomo · 3 years ago

    Thanks for the short and sweet introduction.

  116. Antonio · 3 years ago

    Thankss!!!!

  117. sklep rowerowy · 3 years ago

    Everyone needs two hugs.

  118. Motoryzacja · 3 years ago

    Why it isn’t working with IE7 ?

  119. Konin · 3 years ago

    Thanks for very interesting article. Can I translate your article into polish and publish at my webblog? I will back here and check your answer. Keep up the good work. Greetings

  120. Fotka · 3 years ago

    Great tutorial.. usefull when I have empty mind :D

  121. Fotka · 3 years ago

    Everyone needs a hug.

  122. ludo · 3 years ago

    I am interested in the topics discussed but have been feeling a little intimidated by the thought of the work

  123. Jahangir · 3 years ago

    Finally a good concise and well written tutorial on prototypes.js Good job Ryan Campbell

  124. Noosa · 3 years ago

    Nice article Ryan,

    the more stability we can provide on our sites the better in my opinion, and these tips certainly help when it comes to that. Thanks again.

  125. kursy i szkolenia · 3 years ago

    hi has nothing to do with Prototype. It is just a variable I set to keep track of the Ajax calls. Sorry for not making that clear.

  126. Sportfahrwerke · 3 years ago

    Very helpful artical! Thankyou for your examples and clarification on the use of the convenient Prototype functions as I could not find any docs untill now.

  127. Fábio Salata · 3 years ago

    Great tutorial, thanx.

  128. Gry Komputerowe · 3 years ago

    The best article for newbies! But could you help with one problem: I want to check form using prototype’s Ajax.Request and if user fills form right, then redirect(!) he to second page for registration with(!) right GET or POST variables from form otherwise, show him message. Could you help me?

  129. Plau · 3 years ago

    Very cool. A detailed tutorial I was searching for a good prototype tutorial. Thanks

  130. pozycjonowanie · 3 years ago

    Thankyou for your examples and clarification on the use of the convenient Prototype functions as I could not find any docs untill now.

  131. Dan · 3 years ago

    Tried to comment on your entry ‘Prototype and the This Keyword; however, no ‘add comment’ section was available. You have a typo. this:

    this.className = 'testing';

    should be

    this.ctrl.className = 'testing';

    . Thanks for excellent insights.

    And yes, Everyone ‘does’ needs a hug.