3

Using PhantomJs, I'm trying to create a function which takes a select tag id and the String of an option's text content, and returns the value of the associated option. I'm unsure of how to pass the parameters from the outermost function to the function passed to page.evaluate. Below is what I've tried, but the variables come out as undefined inside page.evaluate.

function getOptionValue(selectID, name)
{
    console.log("Select ID: " + selectID);
    console.log("name: " + name);

    return tempPage.evaluate(function(selectID, name) {
        console.log("SELECT ID: " + selectID);
        var elem = document.getElementById(selectID);
        console.log("elem type: " + elem.type);
        for(var i = 0; i < elem.length; i++)
        {
            if(elem.options[i].text.toLowerCase() === name.toLowerCase())
            {
                return elem.options[i].value;
            }
        }

        return "nothing";
    });
}

1 Answers1

2

PhantomJS has good documentation, including page.evaluate function, please be sure to always check it first.

Your function can be fixed this way (removed console.log for brevity):

function getOptionValue(selectID, name)
{
    return tempPage.evaluate(function(selectID, name) {

        var elem = document.getElementById(selectID);
        for(var i = 0; i < elem.length; i++)
        {
            if(elem.options[i].text.toLowerCase() === name.toLowerCase())
            {
                return elem.options[i].value;
            }
        }

        return "nothing";
    }, selectID, name); // <-- parameters are passed to page.evaluate after the function 
}
Vaviloff
  • 16,282
  • 6
  • 48
  • 56