开发者

jQuery delicious alike tags input

开发者 https://www.devze.com 2023-01-28 04:21 出处:网络
I am trying to build a tags input which act like delicious tags , i managed to send the value of a text to the text input field , but can\'t append more than one tags . How i can make it submit more t

I am trying to build a tags input which act like delicious tags , i managed to send the value of a text to the text input field , but can't append more than one tags . How i can make it submit more than one tag with separator " , " ..

        <label for="tags">Tags</label>
    <input type="text" name="tags" id="tags"  />


    <p>
        <a class="but">tag 1</a>
        <a class="but">tag 2</a>
        <a class="but">tag 3</a>
        <a class="but">tag 4</a>
        <a class="but">tag 5</a>
       开发者_JAVA百科 <a class="but">tag 6</a>
        <a class="but">tag 7</a>
        <a class="but">tag 8</a>
    </p>
   <script>
    $(".but").click(function () {
      var text = $(this).text();
      $("#tags").val(text);
    });
   </script>


Here's how I did it using jQueryUI

function split(val) {
    return val.split(/,\s*/);
}

function extractLast(term) {
    return split(term).pop();
}

    $("input[name='categoriesAsText']").autocomplete({
        source: function(request, response) {
            $.getJSON(URLS.search_admin_categories, {
                term: extractLast(request.term)

            }, response);
        },
        select: function(event, ui) {
            var terms = split(this.value);
            terms.pop();
            terms.push(ui.item.value);
            terms.push("");
            this.value = terms.join(", ");
            return false;
        },
        focus: function() {
            return false;
        },
        search: function() {
            var term = extractLast(this.value);
            if (term.length < 2) {
                return false;
            }
        }
    });

Here is the server side code for doing the search. It's in Grails, but you should be able to craft it to your server side language of choice:

def search = {
    withFormat {
      json {
        def categories = Category.createCriteria().list() {
          ilike('name', "${params.term}%")
        }

        categories = categories.collect {
          [id: it.id, label: it.name, value: it.name]
        }

        render categories as JSON
      }
    }
  }


This will keep the current value of the #tags input (if there is one) and append the new tag separating each tag with ,

$(".but").click(function () {
    var text = $(this).text();
    var input = $("#tags");
    var curtext = input.val();
    input.val( (curtext ? curtext + ", " : "") + text);
    $(this).hide(); // Hide the tag link
});

Example: http://jsfiddle.net/petersendidit/ZFYC5/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号