¶ Edit

X Delete

3110 views

8 years ago

Forms

When a user submits an HTML form to your app, the data is available from the request.params object, which has a property for each form parameter. The property value is a string, or an array if the property value occurs more than once.

Here's a form with a single text box. When the user presses "enter" in the text box, the form submits back to the app. The app always shows the form, but if it detects form data, it shows that below the form.

printp("What is your favorite word?");

print(FORM({action:"/", method:"post"},
        INPUT({text:"text",name:"theWord"})));

if (request.params.theWord) {
    printp("Your favorite word is: ",B(request.params.theWord));
}

Note that the action is the URL to submit the form to, and method:"post" tells the form how to send the data. (The alternative is "get", which would also work here, but would encode the form data into the URL.)

Here's a similar app that uses the "dispatch" library. Submitting the form takes the user to a different page, from which they can click a link to return.

function get_main() {
    printp("What is your favorite word?");
    print(FORM({action:"/favword", method:"post"},
              INPUT({text:"text",name:"theWord"})));
}

function post_favword() {
    printp("Your favorite word is: ",B(request.params.theWord));
    printp(link("/","Back"));
}

dispatch();

Here's a more complicated app that implements Elmer Fudd's speech impediment. It uses our "quickforms" library, an experimental library that makes it a little easier to format forms.

import("quickforms");

var form = new QuickForm({action: "/", method: "post"});

form.addHeading("h", "Tell Elmer Fudd what to say!");
form.addInputTextArea("theText", {label: "Enter (or paste) text",
  value:"I have a dream.  Let freedom ring."});
form.addSubmit("submit","Say it");

print(form);

var text = request.params.theText;
if (text) {
    text = text.toLowerCase().replace(/l|r/g,'w').replace(/th/g,'d');
    printp("Elmer Fudd says: ",SPAN({style:"color:green"},text));
}

The steps to using a QuickForm are creating it, adding fields, and printing it. Each field has an "id" (the first argument), which is mainly used to give each input field a parameter name so you can refer to it through request.params.

Powered by AppJet on JGate
source
rendered in 0.143s