Search code examples
jquerydata-bindingknockout.jstriggers

jQuery trigger select change value in data-bind in a site using Knockout.js - Possible?


I need to activate a select value in a website using Knockout.js using a browser extension.

I am using jQuery but I am a bit lost with the trigger ko methods.

This is the select that I want to change the value:

<select name="subDuration" class="select number_weeks" id="sub_duration"
data-bind="
    options: options.durationOptions, 
    optionsText: 'val', 
    optionsValue: 'key', 
    optionsCaption: 'Select subscription duration', 
    value:options.duration,
    event:{
        change: options.updateDuration,
        blur: options.validateDuration
    },
    attr:{
        'aria-invalid': options.hasDurationError,
        'aria-describedby': options.hasDurationError() ? 'sub_duration_error' : false
    }
" 
data-ctp-cont="Direct Debit Payments">
</select>

$("#sub_duration").focus().trigger("change", options).val(2).blur()

When I use the cde line above it puts the value as 2 but the site validation runs on blur and does not recognise it as valid. If I select something else or then 2 again it does. It feels like the jQuery change is not triggered in the site ko js validations.

Any idea of what I am missing here? Sadly I've never worked with knockout.js...

Any help is appreciated. Thank you!


Solution

  • Thanks to @user3297291 I followed the solution of injecting js in the main site to be able to run the code form the content script of my extension.

    Below is the solution code in my extension content script, in case anyone is facing the same issue:

    function myFunc() {
      //Trigger some Knockout JS functions on the main site scope.
    }
    
    var script = document.createElement('script');
    script.appendChild(document.createTextNode('('+ myFunc +')();'));
    (document.body || document.head || document.documentElement).appendChild(script);
    

    Thanks to anyone that helped!