Search code examples
javascriptajaxprototypejs

How to update value attribute using periodicalupdater in prototype


How to update value attribute using periodicalupdater in prototype?

new Ajax.PeriodicalUpdater('content', '/content/',
{
    method: 'post',
    frequency: 5,
});

This updates text inside element.. I want to update value attribute.. is that possible?


Solution

  • From looking at the source, it seems Ajax.PeriodicalUpdater passes it's options directly to an Ajax.Updater, which in turn supports an insertion option. The documentation says insertion can be a string but it leaves out a useful detail, it may be a function.

    new Ajax.PeriodicalUpdater('content', '/content/',
    {
        method: 'post',
        frequency: 5,
        insertion: Form.Element.setValue
    });
    

    This isn't tested but I believe the default Element.insert can be replaced with Form.Element.setValue since the arguments are in identical order


    Update: Prototype.js is older than HTML5 so does not support <progress> elements. Form.Element.setValue() works out which method to use by an element's tag name and it has no method for progress, which is why the above fails. Instead we can write our own function to take the place of Form.Element.setValue:

    new Ajax.PeriodicalUpdater('content', '/content/',
    {
        method: 'post',
        frequency: 5,
        insertion: function (progress, value) {
            progress.value = value;
            if (value >= progress.max) throw $break;
        }
    });