niranjan kumar
niranjan kumar

Reputation: 21

copy text from one div to other div using javascript

<div id="noty">Hello</div>
<div id="noty">World</div>
<div id="noty">Nation</div>

<div id="textArea"></div>

$("#noty").click(function() {
    $("#textArea").html($("#noty").html());
});

I'm using this to copy text from one div to other by onclick function. But this is not working. It's only working on the first div. Is there any way to accomplish this ?

Upvotes: 1

Views: 276

Answers (4)

Jinyoung Kim
Jinyoung Kim

Reputation: 1965

At first, you must not use multiple id attribute. And another problem is sizzle providing jQuery as a selector engine returns result to use getElementById. It means even if you've declared multiple ids, you'll get just only one id element. When consider those problems, you can get over this problem to follow this way:

<div class="noty">Hello</div>
<div class="noty">World</div>
<div class="noty">Nation</div>

<div id="textArea"></div>
<script>
var $noty = $('.noty');
var $textarea = $('#textArea');
$noty.click(function () {
  var text = Array.prototype.map.call($noty, function (el) {
    return $(el).html();
  }).join(' ');

  $textarea.html(text);
});
</script>

Upvotes: 1

Steve Harris
Steve Harris

Reputation: 5119

Yes. var s = ''; $('.noty').each(function () {s += $(this).html();}); $('#textarea').html(s); but change your divs to use class="noty" instead of id. The id should be unique.

Upvotes: 1

Gene R
Gene R

Reputation: 3744

Use something like this:

<div class="noty">Hello</div>
<div class="noty">World</div>
<div class="noty">Nation</div>

<div id="textArea"></div>

<script>
$(".noty").click(function() {
    $("#textArea").html($(this).html());
});
</script>

https://jsbin.com/giqilicesa/edit?html,js,output

Upvotes: 2

Asons
Asons

Reputation: 87313

Like this.

$(".noty").click(function(e) {
    $("#textArea").html(e.target.innerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="noty">Hello</div>
<div class="noty">World</div>
<div class="noty">Nation</div>

<div id="textArea"></div>

Upvotes: 2

Related Questions