David19801
David19801

Reputation: 11448

Create working form inside div using JUST code

I have a div:

<div id="test">Text to be removed</div>

How can I add this complete form into the div, using JUST code (starting from nothing, meaning the form element does not exist anywhere in the page):

<form name="input" action="html_form_action.asp" method="get">
Edit: <input type="text" name="tex" value="Some text here to edit"/>
<input type="submit" value="Submit" />
</form> 

Upvotes: 0

Views: 2703

Answers (1)

user1106925
user1106925

Reputation:

Well how about...

$('#test').html('<form name="input" action="html_form_action.asp" method="get">' +
                    'Edit: <input type="text" name="tex" value="Some text here to edit"/>' +
                    '<input type="submit" value="Submit" />' +
                 '</form>');

or...

$('<form>',{name:'input',action:"html_form_action.asp",method:'get'})
    .append('Edit: ')
    .append($('<input>',{type:'text',name:'tex',value:'Some text here to edit'}))
    .append($('<input>',{type:'submit',value:'Submit'}))
    .appendTo($('#test').empty());

Or with the native API...

var test_div = document.getElementById('test');

test_div.innerHTML = '';

var form = test_div.appendChild(document.createElement('form'));

form.name = 'input';
form.action = 'html_form_action.asp';
form.method = 'get';

form.appendChild(document.createTextNode('Edit: '));

var input = form.appendChild(document.createElement('input'));
input.type = 'text';
input.name = 'tex';
input.value = 'Some text here to edit';


input = form.appendChild(document.createElement('input'));
input.type = 'submit';
input.value = 'Submit';

Or with the native API, and a helper function...

function createAndInsert(parent, tag, props, clear_first) {
   var el;

    if(typeof parent === 'string')
        parent = document.getElementById(parent);

    if(clear_first)
        parent.innerHTML = '';

    if(tag === ':text')
        el = parent.appendChild(document.createTextNode(props));
    else {
        el = parent.appendChild(document.createElement(tag));

        for(var n in props)
            el[n] = props[n];
    }
    return el;
}

Then...

var form = createAndInsert('test', 'form', {
   name: 'input',
   action: 'html_form_action.asp',
   method: 'get'
}, true);

createAndInsert(form, ':text', 'Edit: ');

createAndInsert(form, 'input', {type:'text',name:'tex',value:'Some text here to edit'});

createAndInsert(form, 'input', {type:'submit',value:'Submit'});

Upvotes: 3

Related Questions