Jquery move text within a div to a form input field

别等时光非礼了梦想. 提交于 2019-12-25 11:58:19

问题


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/



来源:https://stackoverflow.com/questions/11076556/jquery-move-text-within-a-div-to-a-form-input-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!