Home >Web Front-end >JS Tutorial >Three-level linkage of provinces and municipalities implemented by jquery_jquery

Three-level linkage of provinces and municipalities implemented by jquery_jquery

WBOY
WBOYOriginal
2016-05-16 16:06:241150browse

Provincial and municipal level linkage, with usage examples and data table data

Some data are accurate to the township level! ! !

Git address: http://git.oschina.net/upliu/province-city-district

Demo code:

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title>省市区三级联动</title>
</head>
<body>
<form method="post" action="post.php">
  <div id="area"></div>
  <input type="submit" style="margin-top: 10px;">
</form>
<script src="jquery-2.1.3.min.js"></script>
<script src="area.js"></script>
<script>
  $(function(){
 
    add_select(0);
 
    $('body').on('change', '#area select', function() {
      var $me = $(this);
      var $next = $me.next();
      /**
       * 如果下一级已经是当前所选地区的子地区,则不进行处理
       */
      if ($me.val() == $next.data('pid')) {
        return;
      }
      $me.nextAll().remove();
      add_select($me.val());
    });
 
    function add_select(pid) {
      var area_names = area['name'+pid];
      if (!area_names) {
        return false;
      }
      var area_codes = area['code'+pid];
      var $select = $('<select>');
      $select.attr('name', 'area[]');
      $select.data('pid', pid);
      if (area_codes[0] != -1) {
        area_names.unshift('请选择');
        area_codes.unshift(-1);
      }
      for (var idx in area_codes) {
        var $option = $('<option>');
        $option.attr('value', area_codes[idx]);
        $option.text(area_names[idx]);
        $select.append($option);
      }
      $('#area').append($select);
    };
  });
</script>
</body>
</html>

The above is all the content shared with you in this article. I hope you will like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn