content from divs into textarea

I'd like to transfer text from all div's with specific class to the textarea on the same page.

How can I do that?

for example:

< div class="test1" > Example1 < /div >
< div class="test2" > Example2 < /div >
< div class="test1" > Example3 < /div >
< div class="test3" > Example4 < /div >

I would like to transfer the content of div class test1 and in the textarea should show "Example1" and "Example3".

Any help, please! javascript or php

john


This would be done pretty easily with jQuery:

var newTextVal = "";
$('.text1').each(
    function()
    {
       newTextVal += $(this).text();
    }
);
 $('textarea').val( newTextVal );

This above will loop through each element with class "text1" and append it's text node value to the text within the textarea.


如果你正在寻找纯粹的JavaScript,这将工作 - 虽然这样的事情很容易在像jQuery这样的框架中处理:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <script type="text/javascript">

        function CopyDivsToTextArea()
        {
            var divs = document.getElementsByTagName("div");
            var textToTransfer = "";
            var pattern = new RegExp("test1");

           for(var i=0;i<divs.length;i++)
            {
            if(pattern.test(divs[i].className))
                {
                   textToTransfer += (divs[i].innerText || divs[i].textContent);
                }
             }
         document.getElementById("ta").value = textToTransfer;
        }

    </script>
</head>
<body>
<div class="test1" > Example1 </div >
<div class="test2" > Example2 </div >
<div class="test1" > Example3 </div >
<div class="test3" > Example4 </div >
<br />
<textarea id="ta" cols="50" rows="20"></textarea>
<br />
<input type="button" id="btn" value="Button" onclick="CopyDivsToTextArea();" />
</body>
</html>

I'd suggest using the "id" attribute for the divs instead of class. Basically, you would need to write a JavaScript function that uses GetElementById() or GetElementByObject().

Then define a button that calls that function passing it the id of the div and the id of the textarea. Finally, set the textarea object's value to the div object's value.

EDIT: Here's the function.

<script type="text/javascript">
function copyValues(idFrom, idTo) {
    var objFrom = document.getElementById(idFrom);
    var objTo = document.getElementById(idTo);

    objTo.value = objFrom.value
}
</script>

On the event you want it triggered:

copyValues("div1", "textarea1");
copyValues("div2", "textarea2");
copyValues("div3", "textarea3");
链接地址: http://www.djcxy.com/p/10178.html

上一篇: 在PHP中从空值创建默认对象?

下一篇: 内容从divs到textarea