Jquery-based intelligent personnel selection input box

Source: Internet
Author: User

Update: fixed the display issue in Firefox. Copy CSS again.

After writing this name, I suddenly felt a bit suspicious about the title party, but I don't know what kind of name is suitable. So let's just do it now.

Today we will talk about something relatively simple. Another jquery control is used, which is used by a person to select an input box. So what is it?
Well, let's take a look at the final effect and have a direct understanding.

 

Is it similar to the popular SNS website's staff selection controls? In comparison, haha is, in fact, the purpose is similar.

In fact, there are many such applications, such as the automatic completion of the sender in the mail system during input. It is a function similar to AutoComplete, but there are more plug-ins than autocomplete.

Based on this situation, I wrote this control based on an AutoComplete control, it is jquery. AutoComplete, its official site is: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/

You can access the following to obtain the usage method. The materials and demos are more detailed. I will not repeat them here. So we started the expansion part directly.

First, determine the html

From the html analysis of the AutoComplete and selection controls, the query is

1: External container 2: The small block of the selected person

We can use the DIV for the container, and the small square is also relatively simple. Let's take a look, the outermost layer is the DIV package, and then a nested a tag (to facilitate future hover effects ), in tag a, a span is used to place text,

Input [type = hidden] to prevent data on this node. IMG seems to delete the carrier of the button. What is the carrier of the control? In fact, it can be an input in design, but I prefer Div. when instantiating, I dynamically add an input to the DIV to attach the autocomplete attribute, if, in turn, the container is wrapped outside the input, the problem will be located in some special circumstances.

Now that HTML has been defined and CSS is followed, this CSS is actually very simple, that is, the container's border and the way items look. Let's take a look at it.Code

. Bbit-usbox {border: solid 1px #3c7fb1; margin: 20px; padding: 2px; display: block; Background-color: # f3fefe ;}. bbit-usbox. bbit-usbox-item {width: auto; margin-left: 4px; margin-top: 2px; Background-color: # e0e5ee; Border: solid 1px # ccd5e4; float: left; white-space: nowrap ;}. bbit-usbox. bbit-usbox-item A {color: #000; text-Decoration: none; padding-left: 2px ;}. bbit-usbox. bbit-usbox-item a span {}. bbit-usbox. bbit-usbox-del {Background: URL ("images/usbox/del.gif") No-repeat 50% 80%; width: 10px; Height: 5px; cursor: pointer; Border: none; vertical-align: middle; margin-left: 2px ;}. bbit-usbox-boxc {margin-left: 4px; clear: Left ;}. bbit-usbox-box {}. bbit-usbox-boxc input {background-color: # f3fefe; width: 100%; Height: 17px; display: block; Border: none ;}

In this example, only one image is used.

The second step is to write JavaScript.

it's still the old rule. Let's start with the complete code, which is very simple and only contains less than 70 lines of code.

; (Function ($) {If (! $. Autocompleter) {alert ("Please reference jquery first. autoComplete. JS "); return;} $. FN. usbox = function (o) {var def = {urlordata: "responseautocomplete. ashx ", width:" 90% ", // width additem: false, removeitem: false, clickitem: function () {}, completeop :{}; $. extend (def, O); var CO = $. extend ({scroll: false, formatitem: function (row, I, max) {return row [0] + "[" + row [1] + "]" ;}}, def. completeop); var temp = "<Div class = 'bbit-usbox-item'> <a href = 'javascript: void (0 ); '> <span >$ {text} </span> <input type = 'den den' value = '$ {value}'/>  </a> </div> "; return this. each (function (e) {var me = $ (this); var id = me. ATTR ("ID"); If (ID = NULL | id = "") {id = "usbox _" + new date (). gettime () ;}var Inc =$ ("<Div class = 'bbit-usbox-boxc'/> "); vaR input = $ ("<input type = 'text' id = '" + ID + "_ inbox' class = 'bbit-usbox-box'/> "). appendto (INC); me. addclass ("bbit-usbox "). width (def. width ). append (INC); input. autoComplete (def. urlordata, Co ). result (function (event, Data, formatted) {$ (this ). val (""); additem (this, data) ;}); me. BIND ("addboxitem", function (E, data) {additem (input, data) ;}); function additem (Inc, data) {var TP =$ (temp. replace (/\ $ \ {([\ W] +) \}/g, function (S1, S2) {If (s2 = "text ") {return data [0];} else if (s2 = "value") {return data. join ("|");} else {return S1 ;}}); TP. click (def. clickitem ). find ("IMG. bbit-usbox-del "). click (removeitem); $ (INC ). parent (). before (TP); If (def. additem) {def. additem (data) ;}} function removeitem () {var P =$ (this ). prev () var v = P. val (); var arr = v. split ("|"); If (def. removeitem) {def. removeitem (ARR);} $ (this ). parent (). parent (). remove () ;}return me ;};}; $. FN. addboxitem = function (OP) {$ (this ). trigger ("addboxitem", [op]) ;};} (jquery)

Next, let's take a step-by-step analysis of my implementation and start to write the "template" of the jquery control. For more information about the reason, see this description.

 
; (Function ($) {If (! $. Autocompleter) {alert ("Please reference jquery. autocomplete. js"); Return ;}$. FN. usbox = function (o) {}}) (jquery)

This time I added a judgment, because our control relies on autocomplete. If you read the first two articles, you must know that the next step is to compile the default parameters.

 
VaR def = {urlordata: false, // required! The URL of the request data or the data directly. For details about the format, see AutoComplete description width: "90%", // width additem: false, // The removeitem: false function triggered when a person is selected from the drop-down list. // The clickitem: function () function triggered when a person is deleted from the selected person () {}, // The completeop: {}// AutoComplete parameter triggered when a person clicks a small square. For the format, refer to its own description };

Parameters are also relatively simple, and the two functions to be added and removed are quite important. In the demo, we will talk about AutoComplete parameters. Because there are too many parameters, you can only refer to the official instructions. By default, they do not matter, because I will give it to you by default.

$. Extend (def, O); // This is the default complete parameter var CO = $. extend ({scroll: false, formatitem: function (row, I, max) {return row [0] + "[" + row [1] + "]" ;}}, def. completeop); // defines the template of a small cube. s.gif is an empty image, and the position can be adjusted according to the actual situation. var temp ="$ {Text}";

The formatitem function is the format displayed in the drop-down list, followed by generating HTML and registering events. The detailed steps are as follows:

Return this. each (function (e) {var me = $ (this); var id = me. ATTR ("ID"); // obtain the unique ID if (ID = NULL | id = "") {id = "usbox _" + new date (). gettime () ;}// input container var Inc =$ ("<Div class = 'bbit-usbox-boxc'/> "); // generate an input for appending the autocomplete control var input =$ ("<input type = 'text' id = '" + ID + "_ inbox' class = 'bbit-usbox- box '/> "). appendto (INC); // set the style and add the input to the object. addclass ("bbit-usbox "). width (def. widt H ). append (INC); // registers AutoComplete for input and sets the callback function input. autoComplete (def. urlordata, Co ). result (function (event, Data, formatted) {$ (this ). val (""); // If the selected person is selected, the input box will be cleared by additem (this, data); // generate a small square}); // register a custom event, event name addboxitem me. BIND ("addboxitem", function (E, data) {additem (input, data) ;}); function additem (Inc, data) {// Replace the small square template with the correct value var TP = $ (temp. replace (/\ $ \ {([\ W] +) \}/g, function (S1, S2) {If (S2 = "Text") {return data [0]; // the first value returned is displayname} else if (s2 = "value") {return data. join ("|"); // put all the others in input [type = hidden]} else {return S1 ;}}); // trigger the click event of small release, in addition, find the delete button internally and register and click the event. jquery's chain is TP. click (def. clickitem ). find ("IMG. bbit-usbox-del "). click (removeitem); // put the small square before the input! $ (INC ). parent (). before (TP); If (def. additem) {// If additem exists, Def is triggered. additem (data) ;}/// function removeitem () {var P =$ (this ). prev () // obtain input [type = hidden], this points to delete IMG var v = P. val (); var arr = v. split ("|"); // concatenate an array if (def. removeitem) {// trigger the removal function def. removeitem (ARR);} // small square to remove itself $ (this ). parent (). parent (). remove (); //} return me ;});

The last step is to publish a function to facilitate the external call of additem. If I have a pop-up interface, I can select n people to return at a time, then I can call this function.

 
$. FN. addboxitem = function (OP) {$ (this ). trigger ("addboxitem", [op]); // do you think of the Custom Event I registered earlier? };

So far, our control has been analyzed completely, but in order to make everyone better understand this control, I also write the corresponding server-side code, because the demo is ASP. net MVC, so take Asp.net MVC as an example. Let's take a look at the demo call code. urlordata is an action, additem and removeitem respectively add or delete selected persons to or from the specified hidden fields for form submission.

$ (Document ). ready (function () {$ ("# usbox "). usbox ({width: 430, urlordata: "<% = URL. action ("querycomplete") %> ", additem: function (data) {var T = $ (" # hdtext "). val (); var v = $ ("# hdvalue "). val (); var T1 = T! = ""? T. Split (","): []; var V1 = V! = ""? V. split (","): []; t1.push (data [0]); v1.push (data [2]); $ ("# hdtext "). val (t1.join (","); $ ("# hdvalue "). val (v1.join (",") ;}, removeitem: function (data) {var t =$ ("# hdtext "). val (); var v = $ ("# hdvalue "). val (); var T1 = T. split (","); var V1 = v. split (","); var Index =-1; for (VAR I = v1.length-1; I> = 0; I --) {If (data [2] = V1 [I]) {Index = I; break;} If (index>-1) {t1.splice (index, 1 ); v1.splice (index, 1); $ ("# hdtext "). val (t1.join (","); $ ("# hdvalue "). val (v1.join (",") ;}}); var tempdata = ["fake brother", "xuanye", "001"]; $ ("# usbox "). addboxitem (tempdata );});

HTML code

 
<Div id = "usbox" class = "bbit-usbox"> </div> <input id = "hdtext" type = "text"/> <input id = "hdvalue" type = "text"/> the input box may be a hidden field in the actual project, by default, I added a fake brother.

Let's take a look at the action code. Two parameters are accepted by default. One is Q, that is, the input box in input, and the other is the limit number (the default value is 10, which can be changed by modifying the complete parameter)

Public contentresult querycomplete (string Q, int limit) {string ret = ""; if (Q! = "" & Limit> 0) {// search for a database or cache based on the keyword. This is relatively simple and does not go deep into the list <person> List = _ respository. querycompleteperson (Q, limit); If (list! = NULL) {stringbuilder sb = new stringbuilder (); foreach (person in list) {// use | split data format, which can be multiple. Here there are three. Of course, you can also use ID as a special SB. appendline (person. fullname + "|" + person. PY + "|" + person. ID);} ret = sb. tostring () ;}} return content (RET );}

The address in this example is: http://jscs.cloudapp.net/ControlsSample/usbox

Another complaint: deploying Windows Azure is a little troublesome .. Several times

Your support is my motivation to continue writing!

 

Address: http://www.cnblogs.com/xuanye/archive/2009/10/28/1591733.html

Reprinted, please keep it!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.