Using Prototype to Access Form Data

Prototype has a powerful API for accessing and manipulating the Document Object Model, A.K.A the DOM. The following code will let you interact with a simple web form.

Suppose we have a form that contains hidden/or locked inputs and they need to be updated dynamically. If the user changes a select field or if a checkbox is de/selected, other values in the form need updating. This could be required when products have options and associated price points. If you want to offer the user the option to switch options without refreshing or navigation this is a simple and effective approach.

… Sample form…

<input type="hidden" name="option_plan_id" id="option_plan_id" value="1"><br/>
<input type="hidden" name="amount" value="150" id="amount">

<select name="select-plan" id="select-plan">
<option value="1, 150">
USD 150 - 1 person
</option>
<option value="2, 200">
USD 200 - 2 people
</option>
</select>

In this example I want to update the values on the amount and option_plan_id input fields. The first thing I need to make sure of is that the page has fully loaded. I’ll make sure that my code executes in this context by placing it inside the document.observe method. I’ll then set up an observer on my select field and if it changes, make assignments. Now, in this example, I just saved the plan id and amount information as a string. In my javascript code I split apart the string and then make the assignments. There are other, probably better, ways of doing this. For instance you could store serialized data/json, and then work with it inside your event. This seems simple enough, however, you’ll have to pay attention in the future, if your storage format changes! Here is the sample Prototype javascript code

<script type="text/javascript" charset="utf-8">
document.observe("dom:loaded", function(){ //when dom is fully loaded do -
//update fields when option is selected
Event.observe('select-plan', 'change', function(event){
var data = this.getValue();
var plan = data.split(",").first(); //breaks apart by comma
var amount = data.split(",").last();
$('plan_option_id').setAttribute('value', plan);
$('amount').setAttribute('value', amount);
});
});
</script>

Thats it for now!

Related posts:

  1. Rails Prototype JS and TinyMCE Autosave
  2. Parse for Links with Prototype JS
  3. Double Click Event Using Prototype Javascript Framework
  4. Accessing Links in Nested TD Cells with Prototype
  5. Onchange Event Fired from Select Field in Rails Form
This entry was posted in Programming and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>