Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery/javascript: Capture submit event from form in iframe?

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>
like image 854
AidanCurran Avatar asked Jan 14 '23 02:01

AidanCurran


1 Answers

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

like image 164
Rohan Kumar Avatar answered Jan 30 '23 17:01

Rohan Kumar