Greasemonkey to change value of Radio buttons in a form?

前端 未结 1 1126
悲&欢浪女
悲&欢浪女 2020-12-04 03:22

I am writing a Greasemonkey/Tampermonkey script and I need to turn on radio buttons depending on the name and value of the radio control.

This is how it looks:

相关标签:
1条回答
  • 2020-12-04 03:52

    This is super easy when you use jQuery. Here's a complete script:

    // ==UserScript==
    // @name     _Radio button check
    // @include  http://YOUR_SITE/YOUR_PATH/*
    // @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @grant    GM_addStyle
    // ==/UserScript==
    /*- The @grant directive is needed to work around a design change
        introduced in GM 1.0.   It restores the sandbox.
    */
    $("input[name='11'][value='zzzz']").prop ('checked', true);
    

    The input[name='11'][value='zzzz'] jQuery selector gets all <input>s that have the initial value zzzz, but only if they are in the group of radio buttons with name="11".

    Reference:

    • jQuery
    • jQuery selector documentation
    • jQuery .prop()

    Important:   The above works on most pages but, on AJAX-driven pages, you often need to use AJAX-aware techniques. This is because the Greasemonkey script will run before the checkbox you care about is loaded.

    One way to deal with this is with the waitForKeyElements utility. Like so:

    // ==UserScript==
    // @name     _Radio button check
    // @include  http://YOUR_SITE/YOUR_PATH/*
    // @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
    // @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
    // @grant    GM_addStyle
    // ==/UserScript==
    /*- The @grant directive is needed to work around a design change
        introduced in GM 1.0.   It restores the sandbox.
    */
    waitForKeyElements ("input[name='11'][value='zzzz']", selectRadioButton, true);
    
    function selectRadioButton (jNode) {
        jNode.prop ('checked', true);
    }
    



    Old answer that was "state of the art" :) back when the question was asked:

    // ==UserScript==
    // @name            _Radio button check
    // @include         http://YOUR_SITE/YOUR_PATH/*
    // @require         http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
    // ==/UserScript==
    
    $("input[name='11'][value='zzzz']").attr ("checked", "checked");
    
    0 讨论(0)
提交回复
热议问题