2

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.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
McKracken
  • 680
  • 8
  • 17

1 Answers1

2

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");
Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • This would be a lot more helpful if it included a simple explanation of what's happening and a reference to some documentation. Especially since this is such a basic question. – FvD Nov 10 '15 at 01:41
  • Even having read some tutorials in the meantime that is very helpful, I'm sure other people googling this will not have used jQuery before either. Thanks :) – FvD Nov 10 '15 at 03:11