Using javascript to select a radio button inside an iframe

Viewed 709

It works fine when I'm using document.querySelector("input[value='female']").click() in test2.php and selects the radio button with the value of female, but it doesn't work in test1.php, when test2.php is inside of an iframe. Is there any work around I can use to fix this?

test1.php

<iframe src="http://chatwithibot.com/test2.php"></iframe>

test2.php

<form action="/testx.php" method = "POST">
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
<input type="submit" value="Submit">
</form> 

Edit: the duplicate solution link seems to only answer question about how to select things from inside an iframe, but not how to change them.

2 Answers

Let's give an id to your iframe to make sure we can find it without difficulties:

<iframe id="testpage" src="http://chatwithibot.com/test2.php"></iframe>

then:

document.getElementById("testpage").contentWindow.document.querySelector("input[value='female']").click()

Explanation:

  • we find the iframe
  • we use its contentWindow.document
  • from there on we can call querySelector as you did

Is necessary access to the iframe for select radio button inside of him. The next code access to all iframes in the actual document and run a call-back function for each.

document.querySelectorAll('iframe').forEach( item =>
   item.contentWindow.document.body.querySelector("input[value='female']").click()
)

if only need access to one iframe try this :

document.getElementById("frame_id").contentWindow.document.querySelector("input[value='female']").click()

Related