Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .text() shows double text

Have a strange situation happening. I have a <h3> with text in it. When I extract this text with .text() and then put this into a <textarea> the text appears twice.

Here is jsFiddle.

HTML

<h3 class="profileRightAboutMeText">Heya, this is all the text.</h3>     
<textarea class="profileRightAboutMeTextarea"></textarea>

JQUERY

$(document).on('click','h6.editMyProfileSection', function() {
  var originalText = $('h3.profileRightAboutMeText').text();

  $('h3.profileRightAboutMeText').fadeOut('fast', function() {
    $('textarea.profileRightAboutMeTextarea').text(originalText).fadeIn('fast');
  });
  alert(originalText);
});

Both the alert and <textarea> show the text double as follows:

Heya, this is all the text.Heya, this is all the text.

like image 834
Adam Avatar asked Sep 03 '12 11:09

Adam


3 Answers

I would say that you have 2 elements that match $('h3.profileRightAboutMeText') on the page.

You can see here: http://jsfiddle.net/KwcGB/ that the text appears twice because I added an extra h3.profileRightAboutMeText to the html but if the extra line is removed then it only appears once.

Try putting $('h3.profileRightAboutMeText') into the console in firebug and seeing how many elements it matches...

like image 136
Felix Eve Avatar answered Nov 03 '22 08:11

Felix Eve


JQuery has different behavior for text() method in case of duplicates which are addressed by compound path.

For example, let

<div id=b class="a">2</div>
<div id=b class="a">3</div>

Then

var val1 = $("#b").text()
var val2 = $("#b.a").text()

// val1 = 2
// val2 = 23

To avoid this problem use .first() for sure

var val3 = $("#b.a").first().text()

// val3 = 2
like image 31
malex Avatar answered Nov 03 '22 07:11

malex


For form elements you should use val() instead of text():

$("textarea.profileRightAboutMeTextarea").val(originalText)

Additionally, check if you have duplicates of elements with class profileRightAboutMeText.

like image 44
VisioN Avatar answered Nov 03 '22 08:11

VisioN