String logic issue

Hi there,

I’ve got this code to add bbcode into a wysiwyg rich text editor. Everything’s working fine except when I want to add an image. The first time the script is run everything is ok, but the second time i get two image inserts, third time I get three and so on.

Here’s the code:


$('#uploads tr').click(function(){
  var filename = $(this).text();
  var insert = '[img="'+filename+'"]';
  [B]textarea.value = textarea.value+insert;[/B]
  $('#images').hide();
  textarea.focus();
});

So first time I click on ‘#uploads tr’, I get [img=“filename”], then if I type some more stuff and then add another image, I get [img=“filename”] ‘Some more stuff’ [img=“filename2”][img=“filename2”], then i’ll get three image tags, then four and so on.

I can see that it’s something to do with the line I’ve highlighted, but I can’t see why, or how to change it.

Any help greatly appreciated,
Mike

What happens if you just use

textarea.value = insert;

What happens if you just use


textarea.value = insert;

Anything that is currently in the textbox is replaced with ‘[img=“filename”]’

In my original post I only included a snippet of the code. With my WYSIWYG form, I have a number of buttons. The image button uses the toggle() jQuery function to display a table of images. I’ve noticed that every click on this button (‘#image’) will result in an extra tag being inserted when I click on the uploads table row (‘#uploads tr’) further on down the code. I’ve highlighted them just to be über clear.

Here’s a more expansive snippet of my code:


[B]$('input').click(function(){[/B]
  var textarea = document.getElementById('wysiwyg');
  var length = textarea.value.length;
  var start = textarea.selectionStart;
  var end = textarea.selectionEnd;
  var selection = textarea.value.substring(start, end);
  [B]if ($(this).attr('id') == 'image'){[/B]
    $('#images').toggle('slow');
    [B]$('#uploads tr').click(function(){[/B]
      var filename = $(this).text();
      var insert = '[img="'+filename+'"]';
      textarea.value = textarea.value+insert;
      $('#images').hide();
    });
  }
  ... more if clauses ...

Don’t really understand why this is happening. I would have thought that textarea.value = textarea.value+insert would give textarea.value a string, like ‘some text blah blah [img=“filename”]’, then if I wanted to add another image, textarea.value + insert would be ‘some text blah blah [img=“filename”]’ + ‘[img=“filename”]’

Could it be because I am declaring the variables within the function?