Ad

Fill Input Field Inside An Iframe When Link Outside Of Iframe Is Clicked

- 1 answer

I have been trying to get this to work for 2 weeks now but I am stumped on this which is probably very simple. I am new to js.

I have multiple links on a page along with a form embedded in an iframe. Same domain, same page, both using https. The form is from a form script and is embedded in the page using:

<div id="my_placeholder" 
data-formurl="https://www.example.com/forms/embed.php?id=7777" 
data-formheight="1268"  
data-paddingbottom="10">
</div>
<script src="https://www.example.com/forms/js/jquery.min.js"></script>
<script src="https://www.example.com/forms/js/jquery.postmessage.min.js"></script>
<script src="https://www.example.com/forms/js/form_loader.js"></script>

Using that code it automatically puts the form in an iframe. The input field ID within the form i'd like to fill is #element_11

So far, I have the following code which works exactly as I'd like but the generic form code is not in an iframe

<a target="_blank" rel="nofollow noreferrer" href="#" onclick="reply_click(this)" data-filled-value="Text from clicking on link 1">Link1</a>
<br />
<a target="_blank" rel="nofollow noreferrer" href="#" onclick="reply_click(this)" data-filled-value="Text from clicking on link 2">Link2</a>
<br />
<a target="_blank" rel="nofollow noreferrer" href="#" onclick="reply_click(this)" data-filled-value="Text from clicking on link 3">Link3</a>

<form>

<input type="text" id="element_11" />

</form>

<script type="text/javascript">

function reply_click(element)
{
document.getElementById('element_11').value = element.getAttribute('data-filled-value');
}    

</script>

How can I accomplish this? I have searched and searched but every post I've come across wants to target the iframe and "submit" the form or "close" the iframe or "fill in one form and have it go to another form in an iframe".

Ad

Answer

Use .contents() to access the contents of an iframe.

function reply_click(element)
{
    $("#iframeID").contents().find("#element_11").val(element.dataset.filledValue);
}

Replace iframeID with the actual ID of the iframe.

Ad
source: stackoverflow.com
Ad