开发者

How can I implement a JS observer which will observe multiple fields

开发者 https://www.devze.com 2022-12-22 07:04 出处:网络
I would开发者_如何学Go 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.

I would开发者_如何学Go 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.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消