pemistahl
pemistahl

Reputation: 9584

How to implement my idea of a JavaScript form?

I have worked mostly with Python so far, so I'm a newbie when it comes to JavaScript. Now I need the latter to implement a form. I have some ideas and requirements in mind and would like you to tell me how to start and which frameworks or tools to use.

My requirements are:

  1. The server-side logic will be implemented in Python and Django.
  2. The entire form is located on a single webpage.
  3. The overall design of the webpage should be done with Twitter Bootstrap.
  4. When the page has been loaded, only the first field of the form is displayed.
  5. When this field has been filled and validates correctly, display the second field of the form below the first field
  6. When a new field gets displayed, its webpage should scroll down automatically if necessary, so that the new field gets centered in the browser. The scrolling should occur with some nice animation.
  7. My form also includes some fields of type ChoiceField. Each choice has its own set of additional settings which will be implemented as form fields as well. Once a particular choice has been made, only the respective set of settings should be displayed but not all settings for all choice fields at the same time. (Can I probably do this with a simple if-else structure?)
  8. When all fields have been displayed, filled and validated and the form has been submitted, the server does some computations. The results of these computations should be displayed below the entire form, once they are ready. The webpage should again scroll down automatically to the results. The best would be to scroll down the webpage to an extent where the form is not visible anymore but only the results. So this is probably dependent on the size of the currently opened browser window.

I know that all of this is possible and I've also seen forms like that from time to time but don't have a concrete example at the moment. I also know that all of this is possible with JavaScript. Can I implement all of the above with JQuery or do I need additional tools? It would be great if a JavaScript expert guided me a bit through this mess inside my mind. Thank you in advance!

Upvotes: 0

Views: 173

Answers (2)

AD7six
AD7six

Reputation: 66258

Make it work

Before doing anything with javascript make a normal form that works. I.e. generate a form using whatever server side language you want, and when you submit the form it should do what you want it to do. If you have a form that works without javascript you have the confidence that it'll always work if the js breaks.

Make it work better/ Progressive Enhancement

There look to be 2 or 3 requirements for your js - treat them all individually:

1. The form should show only one input at a time

E.g. with markup like this:

<form id="myForm" method="post">
    <legend>My Awesome Form</legend>
    <div class="question">
        <label for="x">X</label>
        <input name="x" id="x">
    </div>
    <div class="question">
        <label for="y">Y</label>
        <input name="y" id="y">
    </div>
    <div class="question">
        <label for="z">Z</label>
        <input name="z" id="z">
    </div>

    <div class="submit"><input type="submit" value="Submit"></div>
</form>

Use some js like this:

$('.question', '#myForm').not(':first-child').hide();
$('input', '#myForm').change() {
    var div, next;

    div  = $(this).parent();
    next = div.next();

    if ($(this).val() && next.length) {
        parent.hide();
        next.show();
    }
});

Which would show only one of the question divs at a time, and show the next one (if there is a next one) when the input is filled.

2. Validate user input

To validate the user input, create a function that does that for you, returning true/false as appropriate and hook that into your js so that it doesn't continue if the input value is deemed invalid:

validate(field, input) {
    var valid = false;

    // implement your logic here to validate input

    if (valid) {
        return true
    }
    return false;
}

$('input', '#myForm').change() {
    var div, next;

    if (!validate($('this').attr('name'), $(this).val()) {
        return;
    }

    div  = $(this).parent();
    next = div.next();

    if ($(this).val() && next.length) {
        parent.hide();
        next.show();
    }
});

That will prevent the user from moving onto the next input, if the current one has an invalid value.

3. Submitting the form by ajax

Clicking submit should send the form data to the server, in (almost) the same ways as submitting the form normally. the only difference should be that it response with either a json response that you parse, or a snippet of html that you dump at the end of the page:

$('#myForm').submit(function(e) {
    e.preventDefault();

    $.ajax({
        type: "POST",
        url: $(this).attr('action'),
        data: $(this).serialize(),
        success: function(data, textStatus, jqXHR) {
            // handle success response
        },
        error: function(jqXHR, textStatus, errorThrown)) {
            // show the user an error
        }
    });
});

All of the js written here is untested, it should give you some ideas about how to tackle each aspect of what you want to do - of course, for more information of any particular method refer to the docs.

Upvotes: 3

AJak
AJak

Reputation: 3873

All of this can be done with jQuery, you shouldn't need any additional JS tools.

Since you have a lot of functionality to build out, I'm not going to go into details. However, I can provide some insight into how to go about each step of your process.

1.) Thats fine.

2.) Thats fine too, you just need one html page to accomplish this.

3.) I would recommend having all forms created in HTML with a CSS of display none. Then as the user progresses through, you can use .show() to "show" the hidden elements.

4.) Probably going to want to have a "next" button of some kind outside of your form. Use .click() To trigger a function that does whatever form validation you require on the value of the input form field. You can use .next() to cycle through your form inputs.

5.) If you want a browser scroll use scrollTop or the jQuery ScrollTo Plugin. If your just looking to move things on the screen and not truely scroll, use .animate()

6.) You will have to set the value on the fly as a user progresses. So use .change() to do the detection.

7.) Before submitting, run your validator on all the fields again to ensure you have all correct data. You'll want to use .ajax() to make the request to your service and prevent default on the actual form submit. Take the response you get back from the service and format the information accordingly.

That should give you insight on how to accomplish your project. Good Luck!

Upvotes: 2

Related Questions