Fire a javascript function on a field event

  • 2
  • Question
  • Updated 3 years ago
Hi,
I want to execute a javascript function which updates another field in the UI on an event of a field such as onblur="myFunction()" 
.
I have two date fields, and want to set the second date fields' value based on the selection of the first one.

What would be the solution for this? 
Are there any resources that I can refer (tutorials)?

Thanks in advance.
Photo of Hasantha Liyanage

Hasantha Liyanage

  • 1,446 Points 1k badge 2x thumb

Posted 3 years ago

  • 2
Photo of Irvin Waldman

Irvin Waldman, Champion

  • 9,006 Points 5k badge 2x thumb
There is a more declarative option available but it may occur too late in the sequence of events for your use case.  Have you considered Model Actions?  You can leverage the Action Framework both at the model and model-field levels.  Very cool stuff.  See screenshot.

Alternatively, you could wire up an onblur event handler on the desired field with jQuery and inline JavaScript e.g. 

skuid.$( "<my-element>" ).blur(function() { alert( "Handler for blur called." ); });
One note: You may need to use a custom field renderer to attach the event handler since portions of the DOM maybe destroyed and rebuilt when models are refreshed.  

Hope this helps.



Photo of Hasantha Liyanage

Hasantha Liyanage

  • 1,446 Points 1k badge 2x thumb
Hi Irvin Thank you for the replay, much appreciated.

I also found that I could trigger the field change with using a listener, (code mentioned below) so, which option would follow the best practice? 

       var $ = skuid.$,        $M = skuid.model.map();

        var EventModel = $M.Event,
        Event = EventModel.getFirstRow();

        // Register a listener
        var listener = new skuid.ui.Field(Event, EventModel, null, {
            fieldId: 'StartDateTime',
            register: true
        });

        var handleFieldChange = function(newValue) {
            $.each(EventModel.registeredLists, function() {
                $.each(this.renderedItems, function() {
                    $.each(this.fields, function() {

                       //set the value
                        EventModel.updateRow(Event, EndDateTime, newValue);
                        this.render();

                    });
                });
            });
        };

        listener.handleChange = function(newValue) {
            handleFieldChange(newValue);
        };

        // Run the handle change initially 
        handleFieldChange(
            EventModel.getFieldValue(Event, 'StartDateTime', true)
        );
(Edited)
Photo of Irvin Waldman

Irvin Waldman, Champion

  • 9,006 Points 5k badge 2x thumb
I assume this code will run for any change on the model from any place in the application. Is this OK?
Photo of Hasantha Liyanage

Hasantha Liyanage

  • 1,446 Points 1k badge 2x thumb
Yes Irvin, it would be fine with my case.
Thanks