Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

javascript - Greasemonkey to change value of Radio buttons in a form?

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:

<input type="radio" name="11" value="XXX" class="radio">
<input type="radio" name="11" value="zzzz" class="radio">

So I want to set those buttons that have name of 11 and a value of zzzz to be checked.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...