It’s time for the last, 3rd part of basic Prototype JS course, where we focus on the use of forms, associative arrays, strings and others, but this time on the rules of Prototype JS.
Further delving into the Prototype JS framework
Let’s start with the forms.
Form
Prototype JS encapsulates and / or extends to us many aspects of programming, including forms support.
Available methods:
– disable() – deactivate element, for example:
form[form.disabled ? 'enable' : 'disable'](); form.disabled = !form.disabled;
– enable() – activate the element
– findFirstElement(formElement) – find the first element
– focusFirstElement() – go to the first element (item)
– getElements() – get all elements of the form
– getInputs() – get input fields, for example:
var form = $('myform'); form.getInputs(); // -> all INPUT elements form.getInputs('text'); // -> all text inputs // only radio buttons with the name "education" var buttons = form.getInputs('radio', 'education'); // set disable = true for these buttons buttons.invoke('disable');
– request() – automatically creates the Ajax.Request, where the parameters are built on the basis of form fields, e.g.:
<form id="person-example" method="POST" action="file.php"> … $('person-example').request(); // sending // add a callback: $('person-example').request({ onComplete: function(){ alert('Form data saved!') } }) // get $('person-example').request({ method: 'get', parameters: { interests: 'JavaScript', 'hobbies[]' : ['programming', 'music'] }, onComplete: function(){ alert('Form data saved!') } })
– reset() – reset of the form fields
– serialize() – serializes form fields — as keys (names) and the fields values, for example:
// Test 1 // 'username=tester&age=22&hobbies=coding' $('person-example').serialize(); // Test 2 // {username: 'tester', age: '22', hobbies: ['coding', 'JS']} $('person-example').serialize(true);
– serializeElements() – serializes elements, for example:
new Ajax.Request('/some_url', { parameters: $('id_of_form_element').serialize(true) });
Form.element
Now we will take care about operations on the form fields, including getting their values.