Jquery move text within a div to a form input fiel

2019-08-17 01:17发布

问题:

could somebody please take a look at this

http://jsfiddle.net/bloodygeese/EzkFR/1/

My aim is to on clicking the "click me" get the text contained in the "area" divs to move into the text area below - one in each space.

I have removed my failed jquery attempt at the code as I don't really know what I am doing.

If I can get this to work the next step would be to try and achieve the same thing when the "display area's are on a different page?? not sure if thats possible, I hope it is?

回答1:

Not exactly sure if you want original text left behind or not

DEmo: http://jsfiddle.net/EzkFR/6/

$('#submit').click(function(){
   $('#displayarea').val(  $('#area').text() ); 
   $('#displayarea2').val(  $('#area2').text() );   
})

Note there is no input type="textarea". It is either input type="text" or <textarea></textarea>

If you want the original text containers gone, use remove()



回答2:

Try this code:

​$("#submit").click
    (
        function()
        {
            $("#displayarea").val($("#area").text());
            $("#displayarea2").val($("#area2").text());
            $("#area").html("");            
            $("#area2").html("");
        }
        );​​​​​​​

Edit: using .text instead of .html because we want not any tag inside an INPUT field.



回答3:

var $texts = $('textarea');
var $divs = $('div');

$('#submit').click(function() {
    $divs.each(function(index) {
        $texts.get(index).value = this.innerHTML;
        $(this).remove();
    });
});​

Fixed DEMO

Notes:

  • textarea, isn't a type of <input> as you wrote, it is a tag: <textarea>
  • I cached the elements so I don't need to query the DOM multiple times.


回答4:

Assuming you want an extensible way to do this...

<div id="area" class="movable">I wish I could go down there</div>
<div id="area2" class="movable">Me too please!!</div>
</br>
<input type="textarea" id="displayarea" class="inputtable" value="" />
<input type="textarea" id="displayarea2" class="inputtable" value="" />
</br>
<div id="submit">click me</div>
</br>​

$('div#submit').click(function(e) {
    $('input.inputtable').each(function() {
        var input = $(this);
        $('div.movable').each(function() {
            var self = $(this);
            if (!self.hasClass('moved') && !input.hasClass('inputted')) {
                input.val(self.text()).addClass('inputted');
                self.addClass('moved');
            }
        });
        $('div.movable.moved').detach(); //safe to remove now that we're not looping through them.
    });
    e.preventDefault();
    return false;
});​

Working fiddle: http://jsfiddle.net/EzkFR/10/