5

Lets say I have a web page with an iframe which contains a form. I want to set a value in a hidden field when the form has been submitted. How can I trigger an event in the main page when the form is submitted?

This is a simplified version of what I'm trying to do:

  <!DOCTYPE html>
  <html>
  <head>
    <title>TEST IFRAME UPLOAD</title>
     <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
     <script type="text/javascript">
     // Pseudo code for what I want to do
     // (this of course doesn't work because target is inside iframe:
     jQuery(document).ready(function() {
        $("#file_upload_form").submit(function() {
           $("input[name='fileuploaded']").val(1);
           return true;
        });
     });
     </script>
  </head>

  <body>

     <form id="mainform" action="processform" method="post">
        <input type="hidden" name="fileuploaded" value="">
        <!-- more form fields here -->
     </form>

     <iframe id="upload-iframe">
        <form enctype="multipart/form-data" id="file_upload_form" action="processfileupload" method="post">
           Select an image to upload:<br/>
           <input type="file" name="file">
           <input type="submit" name="submit" class="submit" value="Upload">
        </form>
     </iframe>

  </body>
  </html>
AidanCurran
  • 2,460
  • 5
  • 20
  • 24

1 Answers1

9

Try this,

$('#upload-iframe').load(function() {
  $(this).contents().find('#file_upload_form').submit(function() { 
       $("input[name='fileuploaded']").val("some value"); // updated
      return true; //return false prevents submit
  });
});

Refered from How can i bind an event to an element inside a local iframe?

Can be possible duplicate of Selecting a form which is in an iframe using jQuery

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • That doesnt work for me, input field does not get updated. I've moved the iframe contents into a seperate file the way I've shown it in my example is incorrect, so inside body tags now contains:
    fileuploaded:
    – AidanCurran Jun 21 '13 at 05:08
  • I'm guessing the problem with this solution is that $("input[name='fileuploaded']").val() = "1"; is acting within the context of the iframed document and not the parent document? – AidanCurran Jun 21 '13 at 05:19
  • Your solution works great, Thanks! The problem was the val assignment issue that I introduced in my pseudo code and you updated in your solution. – AidanCurran Jun 21 '13 at 05:44