Bootstrap the cascading pull-down menu _javascript skills every day

Source: Internet
Author: User

This article will introduce the custom bootstrap cascading pull-down menu, the main application situation has the provincial and municipal correlation menu and so on, then takes this example first, certainly other scene's correlation menu also applies. To be honest, it takes a lot of energy and time to encapsulate a generic component, and the so-called universal nature should be considerate and sigh! This collation of the bootstrap related select, which also involves a lot of jquery, Ajax, SPRINGMVC and so on knowledge points, is all-encompassing!

First, let me make a little introduction on behalf of this custom component.

"Hi, hello, my name is Yunm.combox.js, the owner gave me the name, in fact, very vulgar." I mainly by adding two custom attributes for the Select component to complete the corresponding data loading, the data request uses AJAX, the back-end data processing uses the SPRINGMVC (other way also can, only needs to return the corresponding JSON data), uses it, is very very simple! ”

First, the interface effect

Of course, from the interface completely can not see a component package is good or bad, but at least, you feel very simple and beautiful, so good, with this impression, you are interested in continuing to watch? I think the answer is yes.

Ii. Methods of Use

①, procity.jsp

First of all, load yunm.combox.js on the page (later, as for the other bootstrap CSS and JS, not in the scope of this chapter, skip), at the same time, create two select, the specific format see as follows:

 <script type= "Text/javascript" src= "${ctx}/components/yunm/yunm.combox.js" > </script> <div class= "Form-group" > <div class= "Row" > <div class= "col-md-6" > <select name= "P Rovince_code "class=" Form-control combox "ref=" City_select "refurl=" ${ctx}/procity?pro_code={value}&city_code= hsly "> </select> </div> <div class=" col-md-6 "> <select name=" city_code "id=" City_select "class = "Form-control" > </select> </div> </div> </div> <script type= "Text/javascript" > <
 !--$ (function () {if ($.fn.combox) {$ ("Select.combox", $p). Combox ();
}
 }); --> </script> 

• Two select components, one for Province_code and one for City_code.
• Two additional attributes are added to the provincial menu.
REF specifies that the associated menu is a city-level menu City_select
REFURL Specifies the URL of the menu to get the data
Pro_code as a key factor in obtaining city-level data
{Value} , the wildcard character, and then continue with the introduction of the component
city_code=hsly, mainly used to select the designated provinces and cities menu, such as the above (Henan, Luoyang), if not selected, then city_code= is empty
class= "Combox" adds the jquery selector for the provincial dropdown box
• Key methods for executing the Combox component after the page is loaded, described in detail below

②, Yunm.combox.js

Now let's look at the key component content!

(function ($) {var _onchange = function (event) {var $ref = $ ("#" + event.data.ref);

 if ($ref. Size () = 0) return false;
 var refurl = Event.data.refUrl;
 var value = encodeURIComponent (Event.data. $this. Val ());

 Yunm.debug (value);  $.ajax ({type: ' POST ', DataType: "JSON", Url:refUrl.replace ("{value}", value), Cache:false, data: {}, Success

 : function (response) {$ref. empty ();
 Addhtml (response, $ref);
 $ref. Trigger ("Change"). Combox ();

 }, Error:YUNM.ajaxError});

 };
 var addhtml = function (response, $this) {var json = Yunm.jsoneval (response);

 if (!json) return;
 var html = ';

 $.each (JSON, function (i) {if (Json[i]) {html = ' <option value= ' + Json[i].value + ' ";
 if (json[i].selected) {html + = ' selected= ' + json[i].selected;
 html = + ' > ' + json[i].name + ' </option> ';

 }
 });
 $this. HTML (HTML);

 };

 $.extend ($.fn, {combox:function () {return This.each (function (i) {var $this = $ (this); var value = $this. val () | | '';

 var ref = $this. attr ("ref"); var refurl = $this. attr ("Refurl") | |
 "";
 if (refurl) {Refurl = Refurl.replace ("{value}", encodeURIComponent (value));  } if (Refurl) {$.ajax ({type: ' POST ', DataType: "JSON", Url:refurl, Cache:false, data: {}, Success

  : function (response) {addhtml (response, $this); if (ref && $this. attr ("Refurl")) {$this. Unbind (' Change ', _onchange). Bind ("Change", {ref:ref, Refurl:
  $this. attr ("Refurl"), $this: $this,}, _onchange). Trigger ("change");
 }}, Error:YUNM.ajaxError});
 }

 });
}
 });

 }) (JQuery);

• Add a low-level (query jquery Help document) method called Combox to jquery via $.extend ($.fn, {combox:function () {).
• Through (function ($) {_onchange, addhtml}) (jquery), create two methods onchange and addhtml for this component when the page is initially loaded (function ($) {}) (jquery); I think if you do not understand the words, hurriedly Baidu Bar!
• First look at the Combox method
Get ref, Refurl, request the Provincial menu data to Refurl via Ajax, and when successful, bind the JSON-converted option to the provincial menu select with the Addhtml method
Then, for the provincial menu select bind the Change event, passed the parameter is ref (city-level menu), Refurl (city-level data obtained URL), $this (Provincial menu, easy to change events to get the corresponding selected items, such as Henan in the effect map)
The Change event is executed immediately through the trigger method to facilitate the retrieval of the corresponding city-level menu contents.
• Look at the _onchange method, mainly to click on the provincial menu trigger, to get the city-level menu list
Refurl, URL requested to the server
Value, which is used to get the selected item of the Provincial menu, and then to obtain the provincial-level city menu through the value value
$ref. Empty ();Used to clear the City level menu
Continue to get the content of the city menu via Ajax and add it to the City menu via the Addhtml method.
addhtml method
Through the Jsoneval method to the server to pass back the data to eval (eval (' + Data + '), if you do not understand, can be Baidu) method processing, otherwise there will be errors.
$.each (JSON, function (i) {traverses the JSON, creates the option object through jquery, and adds it to the select.)

③, Procitycontroller

The front end of the introduction, we go back to introduce, of course, you can also ignore this section, because not the associated data used by Springmvc this method to get, then preview the code!

Package Com.honzh.spring.controller;
Import java.util.ArrayList;

Import java.util.List;

Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.log4j.Logger;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;

Import Org.springframework.web.bind.annotation.RequestParam;
Import com.honzh.biz.database.entity.City;
Import com.honzh.biz.database.entity.Option;
Import com.honzh.biz.database.entity.Provincial;
Import Com.honzh.common.util.JsonUtil;
Import Com.honzh.spring.service.CityService;

Import Com.honzh.spring.service.ProvincialService; @Controller @RequestMapping (value = "/procity") public class Procitycontroller extends Basecontroller {private static Lo

 Gger logger = Logger.getlogger (Procitycontroller.class); /** * When passing the City_code, it indicates that the dropdown box is to be selected, otherwise uncheck/@RequestMapping ("") public void Index (@RequestParam (value = "City_code", Requir ed = false) String City_code, @RequestParam (value = "Pro_code", required = FALSE) String Pro_code, httpservletresponse response) {try {logger.debug ("Get the region" + City_code + ", province" + pro_code); If Pro_code is "", it indicates that you want to get the city menu, otherwise get the City menu if (!pro_code.equals ("")) {Integer pro_id = Provincialservice.getinstance ().
 Getbyprovincialcode (Pro_code). GetId ();
 List<city> citys = Cityservice.getinstance (). Getcitysbyprovincialid (pro_id);

 list<option> coptions = new arraylist<option> (Citys.size ());
  for (city city:citys) {option coption = new Option ();
  Coption.setid (City.getid ());
  Coption.setname (City.getcname ());

  Coption.setvalue (City.getcode ()); The city menu is selected if (City_code!= null &&!city_code.equals ("")) {if (City.getcode (). Equals (City_code)) {coption
  . setselected ("selected");
 } coptions.add (Coption);
 } renderjson (response, coptions);

 else {list<provincial> provincials = Provincialservice.getinstance (). Getprovincials (); Convert to Standard Option attribute (name,value,selected) list<option> options = new ARRAYLIST&LT;option> (Provincials.size ()); Selected provinces/Cities is the display of the page, the need for the provincial menu and municipal menu settings to select if (City_code!= null &&!city_code.equals ("")) {provincial selecte

  D_provincial = Provincialservice.getinstance (). Getprovincialbycitycode (City_code);
 Pro_code = Selected_provincial.getprocode (); else {pro_code = provincials.get (0) = = null?
 "": Provincials.get (0). Getprocode ();
  for (provincial provincial:provincials) {option option = new option ();
  Option.setid (Provincial.getid ());
  Option.setname (Provincial.getproname ());

  Option.setvalue (Provincial.getprocode ());
  if (!pro_code.equals ("") && Provincial.getprocode (). Equals (Pro_code)) {option.setselected ("selected");
 } options.add (option);
 } renderjson (Response, Jsonutil.tojson (options));
 The catch (Exception e) {logger.error (E.getmessage ());

 Logger.error (E.getmessage (), E);
 Renderjson (response, NULL);



 }
 }

}

@RequestParam (value = "City_code", required = False) String City_code, for requestparam annotation, actually very useful, here is not much to do explanation, just promote, fixed number of parameters , it is easier to maintain code with this annotation.
Provincialservice class, Cityservice class is two single cases, as far as possible put the data in memory, reduce the number of query database, later posted an example.
The option class is a simple encapsulation of the key properties of the front-end option component to facilitate the generalization of the component.
Renderjson (Response, Jsonutil.tojson (options)), JSON-return the data, and later paste the detailed code.

④, Provincialservice.java

Just paste out the code example, do not do a detailed explanation, after all, is not the focus of this chapter.

Package com.honzh.spring.service;
Import java.util.ArrayList;

Import java.util.List;
Import com.honzh.biz.database.entity.City;
Import com.honzh.biz.database.entity.Provincial;
Import Com.honzh.biz.database.mapper.ProvincialMapper;

Import Com.honzh.common.spring.SpringContextHolder;
 public class Provincialservice {private static Object lock = new Object ();

 private static provincialservice config = null;

 Private Provincialservice () {provincials = new arraylist<provincial> ();
 Provincialmapper mapper = Springcontextholder.getbean (Provincialmapper.class);
 Provincials.addall (Mapper.getprovincials ()); public static Provincialservice getinstance () {synchronized (lock) {if (null = = config) {config = new provincial
 Service ();
 } return (config); Provincial Getbyprovincialcode (String Provincial_code) {for (provincial provincial:provincials) {if (Prov
 Incial.getprocode (). Equals (Provincial_code)) {return provincial;
 } return null; } private list<provincial> provincials = null;
 Public list<provincial> getprovincials () {return provincials; Provincial Getprovincialbycitycode (String city_code) {City city = Cityservice.getinstance (). getcitybycode (CIT

 Y_code); for (provincial provincial:provincials) {if (Provincial.getid (). Intvalue () = City.getproid (). Intvalue ()) {return PR
 ovincial;
 } return null; Provincial Getprovincialbycode (String Province_code) {for (provincial provincial:provincials) {if (Provin
 Cial.getprocode (). Equals (Province_code)) {return provincial;
 } return null;

 }

}

⑤, Renderjson method

 /**
 * If an error occurs, the response returns directly to 404
 /protected void Renderjson (httpservletresponse response, Object Responseobject) {
 printwriter out = null;
 try {
 if (Responseobject = = null) {
 response.senderror (404);
 return;
 }
 Converts an entity object to a JSON object conversion
 String responsestr = Jsonutil.tojson (responseobject);
 Response.setcharacterencoding ("UTF-8");
 Response.setcontenttype ("Application/json; Charset=utf-8 ");

 out = Response.getwriter ();
 Out.append (RESPONSESTR);

 Logger.debug ("Return is:" + responsestr);
 } catch (IOException e) {
 logger.error (e.getmessage ());
 Logger.error (E.getmessage (), E);
 } Finally {
 if (out!= null) {
 out.close ();
 }
 }
 }

If you want to further study, you can click on the jquery cascading menu effects Summary, JavaScript cascading menu effects summary to learn.

If you want to further study bootstrap, you can click here to learn, and then attach two wonderful topics: Bootstrap Learning Tutorials Bootstrap actual combat

This series of tutorials is organized into: Bootstrap basic tutorials, welcome to click to learn.

The above is the entire content of this article, I hope to help you learn.

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.