-2

I'm currently trying to figure out a way to select the first checkbox (I'm not exactly sure if it's technically a radio button) that has the following HTML on a page (http://www.swagbucks.com/polls):

<td class="pollCheckbox"></td>

I have been using the following code in an attempt to select the first checkbox of the 4 that are on the page:

// ==UserScript==
// @name         SBPollSelectv2
// @version      1.0
// @description  Demonstration script to change form values
// @include      *
// @grant        none
// ==/UserScript==

var tds = document.getElementsByTagName("td");
for (var i = 0; i<tds.length; i++) {

  // If it currently has the pollCheckbox class
  if (tds[i].className == "pollCheckbox") {
    // Select first button
    document.getElementsByClassName("pollCheckbox")[0].checked = true;
  }
}

I believe that the final line of code is where the flaw lies. I can select all the TD elements by tag, and then try to sort by class. I then need to select the first checkbox with the given class. Unfortunately, my code doesn't work. I need to figure out how to select the first item with the class name and then select that checkbox. Any and all help would be awesome.

Jonas
  • 121,568
  • 97
  • 310
  • 388
theCrabNebula
  • 731
  • 2
  • 13
  • 29
  • 2
    a `` isn't a checkbox. It's a table cell. – Tyr Jan 26 '19 at 10:18
  • 1
    Without the relevant ("*[mcve]*") HTML you're working with we can offer nothing but guesses based upon your - potentially flawed - assumptions and interpretations. Please: post the relevant HTML in order that we can try to help. And no, posting a link to the relevant page isn't a substitute for posting the (relevant) code *in your question.* – David Thomas Jan 26 '19 at 10:45

2 Answers2

1

They're not actually checkboxes or radio buttons - they're <td>s styled to look like radio buttons, so assigning to .checked won't work. Instead, call click() on the td you want, and the site's JS will make it look checked:

document.querySelector('td.pollCheckbox').click();

A userscript containing that single line of code will make the first td appear selected.

Because you only want to select the first td radio-button lookalike, there's no need for loops, you can just use querySelector to return the first element that matches the selector string.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

The element td is just a table cell. The checked circle appears by adding class "pollAnswerSelected" to element td with class "indivAnswerWrap". You can use the below code to check the first box. To uncheck it, just remove the class "pollAnswerSelected".

document.getElementsByClassName("indivAnswerWrap ")[0].classList.add("pollAnswerSelected")
Divvya Mehta
  • 384
  • 1
  • 8