Creating tags using jquery -
first see example http://jsfiddle.net/es5qs/ in example keeping space delimiter creating tags, wanted when type on textbox1 should reflect tags in textbox2 hear code, how can this.
<!doctype html> <html> <head> <script src="jquery.min.js"></script> <script src="jquery-ui.js"></script> <script> $(document).ready(function() { $("#textbox").keyup(function() { $("#message").val(this.value); }); }); $(document).ready(function() { //the demo tag array var availabletags = [ {value: 1, label: 'tag1'}, {value: 2, label: 'tag2'}, {value: 3, label: 'tag3'}]; //the text input var input = $("input#text"); //the tagit list var instance = $("<ul class=\"tags\"></ul>"); //store current tags //note: tags here can split of trigger keys // tagit split on trigger keys passed var currenttags = input.val(); //hide input , append tagit dom input.hide().after(instance); //initialize tagit instance.tagit({ tagsource:availabletags, tagschanged:function () { //get tags var tags = instance.tagit('tags'); var tagstring = []; //pull out value (var in tags){ tagstring.push(tags[i].value); } //put tags input, joint ',' input.val(tagstring.join(',')); } }); //add pre-loaded tags tagit instance.tagit('add', currenttags); }); </script> </head> <body> <div> textbox 1 : <input type="textbox" id="textbox"></input> textbox 2 : <input type="text" id="message" name="tags"/></input> </div> </body> </html>
demo in jsfiddle. main idea @ whole string each time , re-create elements. saves duplication checks , whatnot. long don’t want process huge amounts of text, doesn’t matter performance wise.
i exchanged keypress
keydown
capture backspace well. further, executes on every key, instead of on space. inside keydown listener:
tags = this.value.split(/\s+/); $(".target").html(""); //clear $.each(tags, function (ind, tag) { $(".target").append("<a href='#' class='tag'>" + tag + "</a>"); });
first, input in first textbox split on spaces. regular expression matches successive spaces well. way human being
still creates 2 tags. next, target cleared of previous tags. lastly, iterate on available tags , create link elements them.
note: didn’t change way create these tags. recommend switch $(".target").append($("<a href='#' class='tag'>").text(tag));
. escapes input, users can’t break site including html tags. example, try happens if input <b>
jsfiddle demo.
Comments
Post a Comment