0

Is it possible to add text boxes into an iframe of the same domain. So i have created a button for the user to click.

<button id="text" onclick="addTextBox()">Text</button>

As the user clicks on the button, I need a text box added within the iframe.

<iframe id="iframeDiv" class="section"></iframe>

I have tried this

JS:

function addTextBox() {

    var text = '<div><textarea name="textbox" id="textbox" cols="10" rows="1"></textarea></div>';

    var iframe = document.getElementById('iframeDiv'),
        iframe.innerHTML += parent.text;

    $('div').draggable({
        cancel: "textbox",
        start: function () {
            $('#textbox').focus();
        },
        stop: function () {
            $('#textbox').focus();
        }
    });

}

window.onload = function () {
    addTextBox();

    return;
}

I have done a fiddle too: JSFiddle

I also want to understand how the text tag can be appended to the DOM structure

4
  • Use document.createElement(nodename) Commented Jan 23, 2014 at 12:19
  • why you add textbox in iframe instead of a div Commented Jan 23, 2014 at 12:19
  • See this: stackoverflow.com/questions/1390319/… Commented Jan 23, 2014 at 12:20
  • Your fiddle is broken... Commented Jan 23, 2014 at 12:37

2 Answers 2

1

You can use document.createElement for creating element or use jQuery to create element in a easier way. And use iframe.contentWindow.document.body.appendChild to have multiple elements

     function addTextBox() {    
        var text = document.createElement('textarea'),
        iframe = document.getElementById('iframeDiv');
        text.setAttribute('id', 'textbox');

        iframe.contentWindow.document.body.appendChild(text);    
     }

Or you can also do this:

    function addTextBox() {    
        var text = '<div><textarea name="textbox" id="textbox" cols="10" rows="1"> </textarea></div>',
        iframe = document.getElementById('iframeDiv');
        iframe.contentWindow.document.body.innerHTML = text;    
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I prefer the first suggestion as I can add multiple textboxes. Though I'm trying to make the textbox draggable too. Where can I add the draggable function. or something similar to this $('textarea').draggable({ cancel: "textbox", start: function () { $('#textbox').focus(); }, stop: function () { $('#textbox').focus(); } });
0

try this

 var text = '<div><textarea name="textbox" id="textbox" cols="10" rows="1"></textarea></div>';
    var iframe = document.getElementById('iframeDiv');
iframe .src = "data:text/html;charset=utf-8," + escape(text);

see Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.