views:

241

answers:

2

I'm working on a tagging system and I want users to be able to add and remove tags on the page. for each one thats added I am displaying a small div with the tag and an x to remove the tag. I have the adding functionality working, but I'm not sure how to go about making it so I can remove them. I also have a hidden input which should hold all the values so that when the information is submitted I can use it.

Heres my attempt that doesn't work:

function tagsremove(tag) {
 $('#hiddentags').val().replace('/'+tag+'\,\s/', '');
 $("#tagdiv-"+tag.replace(" ","_")).fadeOut('normal', function(){
  $(this).remove();
 });

}
$(document).ready(function(){
 $('#tagbutton').click(function(){
  var tags = $('#tagsbox').val().split(", ");
  for (var i in tags) {
     $('#hiddentags').val($('#hiddentags').val() + tags[i] +", ");
   $('#curtags').append("<div class='tag'>" + tags[i] + " <a href='#' id='#tagdiv-"+tags[i].replace(" ", "_")+"' onclick='tagsremove(\""+tags[i]+"\");' >x</a></div>");
  }
  $('#tagsbox').val('');
 });
});

heres the html to go with it:

<div class='statbox'>
    <form method='post' action='post.php' id='writeform'>
     <p class='subtitle'>Title</p>
     <input type='text' name='title' id='titlebox' /><br />
     <p class='subtitle'>Body</p>
     <textarea id='postbox' name='body' rows='10'></textarea><br />
     <p class='subtitle'>Tags</p>
     <input type='text' id='tagsbox' /><input type='button' id='tagbutton' value='Add' />
     <p class='subsubtitle'>Seperate by commas (eg. "programming, work, job")</p>
     <div class='subsubtitle' id='curtags'>Current Tags:</div>
     <input type='hidden' value='' name='tags' id='hiddentags' />
    </form>
</div>
A: 

Instead of using .val('') you should be using .html('');

http://docs.jquery.com/Manipulation

Ruggs
i'm using val because i'm changing the value of a hidden input value in one case and a textbox in the other.
The.Anti.9
+1  A: 

Make each of your tag divs have a relevant ID. For, say, the "play pen balls" tag, your ID could be "tagdiv-play_pen_balls". Now you can just do

function removeTag(tag) {
    $("#tagdiv-"+tag.replace(" ","_")).remove();
}

to remove the visible div.

(I'm not sure if that's what you were asking for, though...)

AKX