views:

293

answers:

3

I would like to observe changes in multiple form fields and make a call back to the server with the combined values. The fields I want to observe are select boxs.

Do I do this by firing the "onchange" event of the parent element?

I'm using Prototype 1.6.

+1  A: 

it is only idea. subcribe to any event the container of all controls and catch them.

controls will generate events and your handler on container will process them (it is bubbling process)

it works in jquery, i hope will work in prototype

igor
+1  A: 

Using onchange doesn't always satisfy as it doesn't catch changes well in my experience. Use the timed observer pattern here http://prototypejs.org/api/timedObserver/form-element-observer

Christian
+1  A: 

I agree that it is best to delegate the listening to a containing element in this case. Since it is checkboxes you're looking at, either "change" or "click" would work. I go for the "click" event in the example.

Something like this can be used to make an ajax call with the state of a form's checkboxes whenever one of them is clicked:

<body>

    <form action="/myAction.do" id="theForm">
        <h4>Checkbox submission</h4>
        <input type="checkbox" name="cb0" id="cb0" /> cb0<br />
        <input type="checkbox" name="cb1" id="cb1" /> cb1<br />
        <input type="checkbox" name="cb2" id="cb2" /> cb2
    </form>

    <script type="text/javascript">
    (function setupCheckboxSubmitter(form_) {
        form = $(form_);
        if (!form) {throw new Error('#setupCheckboxSubmitter could not find form:'+form_);}
        // collect the checkboxes we are interested in
        var boxes = form.select('input[type=checkbox]');
        form.observe('click', checkboxSubmitter);
        function checkboxSubmitter(event) {
            var element = event.findElement();
            // bail if it is not one of the elements of interest
            if (!(boxes.include(element))) {return;}
            var params = form.serialize(true);
            new Ajax.Request(form.action, {parameters: params});
        }
    })('theForm');// passing in a form id (or form element) here
    </script>

</body>

Edit the checkboxSubmitter function to your liking, of course. Or maybe make it a callback, passed in after the form id? Glad to hear you're using prototype.js! I'm a fan of it.

npup
var element = event.element() will be a little shorter.
Alsciende
event.element() is deprecated. See http://api.prototypejs.org/dom/event.html#element-class_method
npup
Wooooh. Distinct from findElement in 1.6.0, deprecated in favor of findElement in 1.6.1. http://prototypejs.org/api/event/element
Alsciende
form.request() will serialize and create an Ajax request for you, saving a line or so.
arbales