简体   繁体   中英

Select the next select box beside a td and then select an option by its text value

In short, I need to automate selecting a dropdown value from a webform. I've tried using:

$("td:contains(Gender)")
    .closest('td')
    .next()
    .find('select')
    .filter(function () { return $(this).html() == "Female"; })
    .val();

(just do see if I could return anything and it said undefined)

And

    $("td:contains(Gender)")
    .closest('td')
    .next()
    .find('select')
    .find('option:contains(Female)')
    .attr('selected', true)

(but this would require nested find() to work

The HTML Looks like:

<html>
<table>
    <tr>
        <td>Gender:</td>
        <td>
            <select>
                <option>Male</option>
                <option>Female</option>
            </select>
        </td>
    </tr>
</table>
</html>

The short of it is I cannot use ID's or classes due to the "unique" way the webform is built. I also am aware that I probably cannot use contains due to male and female both containing "male". The values in the dropdowns are all numerical so I'd prefer if I could use text instead of mapping the values.

If you're wondering I am an automation engineer so I've no control over the form itself.

Kind Regards,
K

You were almost correct, you just not need to call .closest('td') as $("td:contains(Gender)") will return the jQuery object of td itself.

 $("td:contains(Gender)") .next() .find('select') .find('option:contains(Female)') .attr('selected', true) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <table> <tr> <td>Gender:</td> <td> <select> <option>Male</option> <option>Female</option> </select> </td> </tr> </table> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM