Silsand
Silsand

Reputation: 9

Move input between divs

Trying to move user input from one div to another via a move button, back and forth. Even if there is multiple inputs one can move selected input from one to the other. So far it moves all inputs in "field1" to "field2". Im trying to move only a single line back and forth.

Tried various stuff, still learning this. Any pointers on what i need to look at in order to achieve this?` Any help appreciated.

var number = [];

function myNotes() {
  var x = document.getElementById("field1");
  number.push(document.getElementById("input").value);
  x.innerHTML = number.join('<input type="button" value="move" onclick="move();"/><br/>');
}

function move() {
  $('#field1').appendTo('#field2')
}
form {
  display: inline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="input" type=text>
</form>
<input type=submit onclick="myNotes();" value="Send">

<br>
<span id='displaytitle'></span>
<h2>Field 1</h2>
<div id="field1"></div>
<h2>Field 2</h2>
<div id="field2"></div>

JSFIDDLE

Upvotes: 0

Views: 690

Answers (1)

Sean Kendle
Sean Kendle

Reputation: 3609

You've got a mixture of javascript and jQuery going that's kind of hard to understand. I've whipped up an example of this using jQuery, since you seem to have it in your project anyway:

https://jsfiddle.net/j5mvq6L5/7/

HTML:

<form>
  <input id="input" type=text>
</form>
<input type=submit id="btnSend" value="Send">

<br>
<span id='displaytitle'></span>
<h2>Field 1</h2>
<div id="field1" class="field"></div>
<h2>Field 2</h2>
<div id="field2" class="field"></div>

JS:

//listen for document ready
$(document).ready(function() { 
    //button click listener:
    $("#btnSend").on("click", function(e) {

        var $field1 = $("#field1");  //works like getElementById

        //create a containing div for later
        var $entry = $("<div></div>").addClass("entry");

        //create a new button
        var $btnMove = $("<input/>").attr("type", "button").attr("value", "move").addClass("btnMove");

        //click listener for the new button
        $btnMove.click(function(){              
          //find "sibling" field (I added a class to both), append this button's parent div
          $(this).parents(".field").siblings(".field").append($(this).parent());
        });

        //append entry parts
        $entry.append($("#input").val())
              .append($btnMove);

        //append entry to #field1
        $field1.append($entry);          
    });
 });

CSS:

form {
  display: inline;
}

.btnMove {
  margin-left: .5em;
}

Upvotes: 2

Related Questions