Stewart
Stewart

Reputation: 1899

What's wrong with this jQuery code to access elements inside an iframe?

I'm trying to use jQuery to fill in a form in an iFrame. Do you see anything wrong with this code? It should be selecting the inputs and filling them in with the values TESTuser and TESTpassword.

Here is the HTML from the iFrame :

<td align="right"><label for="rcmloginuser">CSID</label></td>
<td><input name="_user" id="rcmloginuser" type="text"></td>
</tr>
<tr>
<td align="right"><label for="rcmloginpwd">Password</label></td>
<td><input name="_pass" id="rcmloginpwd" type="password"></td

And here is the jQuery/parent part.

<script type='text/javascript'> 
$().ready(function () {
    $('#emailframe').ready(function () {

        $('#emailframe').contents().find('#rcmloginuser').val('TESTuser');
        $('#emailframe').contents().find('#rcmloginpwd').val('TESTpassword');

    });
};


</script>

<iframe id="emailframe" src ="<?php global $base_url; echo $base_url; ?>/mail.php" width="100%" height="700"></iframe>

Upvotes: 1

Views: 672

Answers (4)

Nick Craver
Nick Craver

Reputation: 630349

There are a few script errors, first the <iframe> doesn't have a ready event (calling $("anything").ready() is really calling .ready() for the current document).

Instead you want the <iframe>'s .load() event, like this:

$(function () {
  $('#emailframe').load(function () {
    $('#emailframe').contents().find('#rcmloginuser').val('TESTuser');
    $('#emailframe').contents().find('#rcmloginpwd').val('TESTpassword');
  });
});

Also notice the end is });, you were missing a parenthesis there.

Upvotes: 3

Keith
Keith

Reputation: 155602

I'd break this up and place debug break points (in Chrome or Firebug) to see where it fails:

var iFrameContent = $('#emailframe').contents();
var loginUser = iFrameContent.find('#rcmloginuser');
loginUser.val('username');

This would let you know whether it's failing to find the frame, the input or failing to set the value.

Upvotes: 0

sorpigal
sorpigal

Reputation: 26086

Try

$().ready(function () {
    $('#emailframe').ready(function () {
        alert('iframe length: ' + $('#emailframe').length);    
        alert('contents length: ' + $('#rcmloginpwd').contents().length);
        alert('rcmloginuser length: ' + $('#emailframe').contents().find('#rcmloginuser').length); 
        alert('rcmloginuser length: ' + $('#emailframe').contents().find('#rcmloginpwd').length);    
    });
};

Do all of these alerts alert with non-zero? I expect the first one will succeed, but the others I am not so certain.

inb4 poor man's debugger: it's true! Firebug would be better, but this is easier to describe.

Upvotes: 0

Snekse
Snekse

Reputation: 15789

Are they on the same domain and same scheme (http vs. https)? Might be a cross-site scripting issue.

Upvotes: 0

Related Questions