Bradley Mc Kinnon Bradley Mc Kinnon - 1 year ago 43
Javascript Question

Selecting a value from a drop down menu via Javascript [Google accounts creation page]

Below is snippets of code I have put together to randomly automate a selection of a birth month via the google accounts creation page.

The months are generated via a drop down list and have appropiate id's i.e 1=January 2=February etc.

I have tried changing my values in myArray to actual months (January,February etc) with no luck aswell.

Where have I gone wrong? Or is this not how it's done?

Any help will be greatly appreciated.

//Get select object
var objSelect = document.getElementById("BirthMonth");
var myArray = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

//Set selected
setSelectedValue(objSelect, "myArray");

function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;

Answer Source
 var objSelect = document.getElementById("BirthMonth");

The objSelect DOM element has no options array to access like you are using.

var myArray = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];

The month elements actually have Ids with values :1 - :9 and then :a - :c.

The hidden field that contains the selected month value is HiddenBirthMonth. The caption element for the month field has an Id of :0, and that needs to be set to the corresponding month caption. We can get that from the textContent property of the month element.

The annoying bit is the fact that the individual month elements aren't rendered until you click the drop-down list. To get around this, I created a function to trigger the mousedown and mouseup events quickly, before continuing.

Working Solution:

function setRandomBirthMonth() {
    var hiddenMonthField = document.getElementById("HiddenBirthMonth");
    var selectedMonthCaption = document.getElementById(":0");
    var monthIds = [':1', ':2', ':3', ':4', ':5', ':6', ':7', ':8', ':9', ':a', ':b', ':c'];
    var randomMonth = monthIds[Math.floor(Math.random() * monthIds.length)];

    // month options don't render until a 'mousedown' event, so let's simulate it
    if (document.getElementById(randomMonth) == null) forceRenderOfMonths();
    var selectedMonth = document.getElementById(randomMonth);

    hiddenMonthField.value = randomMonth;
    selectedMonthCaption.setAttribute("aria-posinset", randomMonth);
    selectedMonthCaption.textContent = selectedMonth.textContent;

    function forceRenderOfMonths() {
        var select = document.getElementsByClassName("jfk-select")[0];
        var clickEvent = document.createEvent('MouseEvents');

        clickEvent.initEvent("mousedown", true, true);
        clickEvent.initEvent("mouseup", true, true);