Lewis Smith
Lewis Smith

Reputation: 1345

Move an input into a form using Javascript

I am trying to move an element inside a form and then change the display to block. I am getting the display to change but can't seem to move it, this is the code I am using

<form action="testsubmit.php">
    <div id="placehere">
    </div>
    <input type="submit" value="submit">
</form>

<div id="input1" style="display:none">
<input type="text" name="test" id="input1">
</div>

<button onclick="test()">Click me</button>


<script>
function test(){
    document.getElementById('input1').appendChild(document.getElementById('placehere'));
    document.getElementById('input1').style.display = 'block';
}
</script>

Upvotes: 0

Views: 220

Answers (3)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

the insertion has to be done in the other way round

document.getElementById('placehere').appendChild(
     document.getElementById('input1')
);

The DOM insertion via appendChild() is in fact <parentNode>.appendChild(<node>)

Then, to show the element javascript is not necessary. just hide the input by default via CSS, and show it when it is inside the form element

#input1 { display: none }
#placehere #input1 { display: block }

Upvotes: 4

user3062282
user3062282

Reputation:

Try this code

<form action="testsubmit.php">
    <div id="placehere"></div>
    <input type="submit" value="submit">
</form>

<div style="display:none">
<input type="text" name="test" id="input_text">
</div>

<button onclick="test()">Click me</button>


<script>
function test(){
    document.getElementById('placehere').appendChild(document.getElementById('input_text'));
    document.getElementById('input_div').style.display = 'block';
}
</script>

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65806

Have you tried:

     document.getElementById('placehere').appendChild(document.getElementById('input1'));

Upvotes: 2

Related Questions