Reputation: 33
I have a page (index.htm) that contains iframe (iframe.htm) from the same domain.
Inside the iframe there is a textarea element that handles its 'change' event.
There is a jquery code at the main page that changes textarea content using val(). Then I'm trying to fire the 'change' event calling to change() function.
However, this doesn't work. Value changes, but 'change' event doesn't work. This works as expected if textarea is not inside the iframe.
QUESTION: how to force event triggering on an element inside the iframe?
iframe.htm:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("textarea").bind("change", function () {
alert("changed"); });
});
</script>
</head>
<body>
<textarea id="txt"></textarea>
</body>
</html>
index.htm:
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("#btn").bind("click", function () {
var frame = document.getElementById("frame");
var txt = frame.contentDocument.getElementById("txt");
$(txt).val("hello").change();
});
});
</script>
</head>
<body>
<iframe id="frame" src="iframe.htm"></iframe>
<button id="btn">Fire change</button>
</body>
</html>
Upvotes: 1
Views: 4410
Reputation: 33
I've solved this. Problem is that using iframe we have different instance of jQuery inside. To fire the event, one should refer to that iframe-nested jQuery instance instead of the parent one.
So instead of
$(txt).val("hello").change();
simply use
frame.contentWindow.$(txt).val("hello").change();
Hope this will help to someone. I've spent few hours looking for the reason of this bug:)
Upvotes: 2
Reputation: 452
try this:
$iframe = $('#iframe').contents().find('#txt');
$iframe.on('change',function(){
var val = $(this).val();
console.log(val);
});
$('#btn').click(function(){
$iframe.trigger('change');
});
Upvotes: 1