Widget HTML #1

Cara Membuat Comobox Tingkat atau Berantai

Hai selamat datang di blog saya kali ini saya akan membagikan cara bagaimana sih cara buat comobox bertingkat dan saling berkaitan ( Insert Dynamic Multi Select Box Data ) itu menggunakan Php, Database, Jquery dan Ajax ? Nah kali ini saya aka membahas tentang hal itu so ikutin tutorial dibawah ya.

Tutorial yang saya bagikan ini pun bisa mengatasi permasalahan kalian yang ingin menyimpan hasil comobox bersifat huruf atau nama yang dipilih bukan malah id nya yang diambil ( berdasarkan pengalaman pribadi hehe ).

Dibawah ini adalah contoh hasil tutorial saya.



Penasaran cara membuat nya ? Oke ikutin tutorial saya dibawah ya cekidot.

Pertama 

Kamu buatlah terlebih dahulu database nya dengan nama "testing" tanpa tanda peti atau bebas namun saya sarankan mengikuti dulu agar kalian tidak bingung. 

Cara Membuat Comobox Tingkat atau Berantai

Lalu kamu buat tabel dengan nama country_state_city dengan struktur dan isi tabel sebagai berikut.

Cara Membuat Comobox Tingkat atau Berantai

Cara Membuat Comobox Tingkat atau Berantai


Dan buat satu lagi tabel untuk menyimpan hasil inputan dengan nama country_state_city_form_data dengan struktur tabel sebagai berikut.

Cara Membuat Comobox Tingkat atau Berantai


Kedua

Selanjutnya kamu buka notepad atau sejenisnya lalu ketikan koding berikut dan save dengan nama database_connection.php

<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
?>

Ketiga

Kamu buat file baru lagi di notepad atau sejenisnya ketikan koding berikut dan save dengan  nama index.php

<?php
//index.php

include('database_connection.php');

$country = '';

$query = "
SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC
";
$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

foreach($result as $row)
{
$country .= '<option value="'.$row["country"].'">'.$row["country"].'</option>';
}

?>
<!DOCTYPE html>
<html>
<head>
<title>Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="jquery.lwMultiSelect.js"></script>
<link rel="stylesheet" href="jquery.lwMultiSelect.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</h2><br /><br />
<form method="post" id="insert_data">
<select name="country" id="country" class="form-control action">
<option value="">Select Country</option>
<?php echo $country; ?>
</select>
<br />
<select name="state" id="state" class="form-control action">
<option value="">Select State</option>
</select>
<br />
<select name="city" id="city"  class="form-control">
<option value="">Select City</option>
</select>
<br />

<input type="submit" name="insert" id="action" class="btn btn-info" value="Insert" />
</form>
</div>
</body>
</html>

<script>
$(document).ready(function(){



$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == 'country')
{
result = 'state';
}
else
{
result = 'city';
}
$.ajax({
url:'fetch.php',
method:"POST",
data:{action:action, query:query},
success:function(data)
{
$('#'+result).html(data);

}
})
}
});

$('#insert_data').on('submit', function(event){
event.preventDefault();
if($('#country').val() == '')
{
alert("Please Select Country");
return false;
}
else if($('#state').val() == '')
{
alert("Please Select State");
return false;
}
else if($('#city').val() == '')
{
alert("Please Select City");
return false;
}
else
{

var form_data = $(this).serialize();
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#action').attr("disabled", "disabled");
if(data == 'done')
{

$('#insert_data')[0].reset();
alert('Data Inserted');
}
}
});
}
});

});
</script>

Keempat

Masih buat file di notepad ketikan koding berikut dan save dengan nama fetch.php

<?php
//fetch.php

if(isset($_POST['action']))
{
include('database_connection.php');

$output = '';

if($_POST["action"] == 'country')
{
$query = "
SELECT state FROM country_state_city
WHERE country = :country
GROUP BY state
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':country' => $_POST["query"]
)
);
$result = $statement->fetchAll();
$output .= '<option value="">Select State</option>';
foreach($result as $row)
{
$output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
}
}
if($_POST["action"] == 'state')
{
$query = "
SELECT city FROM country_state_city
WHERE state = :state
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':state' => $_POST["query"]
)
);
$result = $statement->fetchAll();
$output .= '<option value="">Select City</option>';
foreach($result as $row)
{
$output .= '<option value="'.$row["city"].'">'.$row["city"].'</option>';
}


}
echo $output;
}

?>

Kelima

Kamu buat koding insert di notepad untuk menyimpan data comobox ke database. ketikan koding berikut dan simpan sebagai insert.php

<?php
//insert.php

if(isset($_POST['country']))
{
include('database_connection.php');
$query = "
INSERT INTO country_state_city_form_data (country, state, city)
VALUES(:country, :state, :city)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':country' => $_POST['country'],
':state' => $_POST['state'],
':city' => $_POST['city']
)
);
$result = $statement->fetchAll();

if(isset($result))
{
echo 'done';
}

}

?>

Keenam

Buatlah koding css agar tampilan terlihat menarik dengan cara ketikan koding berikut dan simpan sebagai jquery.lwMultiSelect.css

/* multi select */
.lwms-main
{
font-family: Arial,Helvetica,sans-serif;
background: url('doublearrow.png') no-repeat 204px 110px;
/*width:435px;*/
width:100%;
}

.lwms-main .lwms-left, .lwms-main .lwms-right
{
/*width: 200px; */
width:45%;
color: #555;
float: left;
}

@media only screen and (max-width: 480px) {
    .lwms-main .lwms-left, .lwms-main .lwms-right
{
/*width: 200px; */
width:100%;
float: none;
}
}

.lwms-main .lwms-list{
  -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  border: 1px solid #ccc;
}

.lwms-selected{display:none;}

.lwms-main .lwms-left{margin-right: 35px;}

.lwms-main ul{margin: 0; list-style-type: none;}

.lwms-main ul.lwms-list{
  height: 150px;
  padding: 0px 0px;
  overflow-y: auto;
  background:#fff;
}

.lwms-main .lwms-left li.lwms-selectli,
.lwms-main .lwms-right li.lwms-selectli{
  padding: 4px 10px;
  color: #555;
  font-size: 12px;
  line-height:16px;
  border-bottom:1px solid #D4D4D4;
}

.lwms-filterhead {
  color: #4A4A4A;
  font-size: 12px;
  font-weight: bold;
  height: 25px;
  line-height: 25px;
  margin-top: 5px;
  vertical-align: middle;
}

.lwms-filterhead a {
  color: #4A4A4A;
  text-decoration: none;
}

.lwms-filcount {
  color: #078697;
  font-size: 14px;
}

.lwms-filterhead a:hover { text-decoration: underline; }

.lwms-main li.lwms-selectli:hover,
.lwms-main .lwms-right li:hover{
  cursor: pointer;
  text-decoration: none;
  color:#fff;
  background-color: #1a849b;
}

/* clear fix */
.lwms-cf:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; }
.lwms-cf { display: inline-block;}
html[xmlns] .lwms-cf {display: block;}
* html .lwms-cf { height: 1%;}


Ketujuh

Terakhir kamu buat JQuery nya dengan cara ketikan coding berikut dan simpan sebagai jquery.lwMultiSelect.js


/*
 *  Project: jQuery Light Weight MultiSelect
 *  Version: 1.1.0
 *  Date: 7/11/2013
 *  Requires: jQuery 1.7+
 *  Description: A light weight plugin that transforms a multi select drop menu into two panels for easy selections.
 *  Demo: http://bennylin.net/jquery-plugin-light-weight-multiselect/
 *  Author: Benny Lin - http://bennylin.net
 *  Designer: Monique Aviles
 *  License: MIT License
 *  jQuery Boilerplate: http://jqueryboilerplate.com/
 */

;(function ($, window, document, undefined) { 
  var pluginName = "lwMultiSelect";
  var defaults = { 
    addAllText: "Select All",
    removeAllText: "Remove All",
    selectedLabel: "Values accepted",
    maxSelect: 0, //0 = no restrictions
    maxText: '',
    onChange: ''
  };

  // The actual plugin constructor
  function Plugin(element, options) {
    this.$element = $(element);
    if (options) {
      options.maxSelect = parseInt(options.maxSelect) || defaults.maxSelect;
    }
    this.options = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.totalItem = 0; //cache total count
    this.$mainContainer = "";
    this.$leftDiv = "";
    this.$rightDiv = "";
    this.$leftHead = "";
    this.$rightHead = "";
    this.$availList = "";
    this.$selectedList = "";
    this.$counter = ""; 
    this.init();
  }

  Plugin.prototype = {
    init: function () {
      var tmphtml = "";
      this.$element.hide();
      this.$mainContainer = $('<div class="lwms-main lwms-cf"></div>').insertAfter(this.$element);
      this.$leftDiv = $('<div class="lwms-left"></div>').appendTo(this.$mainContainer);
      this.$rightDiv = $('<div class="lwms-right"></div>').appendTo(this.$mainContainer);

      if (this.options.maxSelect != 0) {
        tmphtml = '<div class="lwms-filterhead"><div class="lwms-maxtext">'+ this.options.maxText +'</div></div>';
      } else {
        tmphtml = '<div class="lwms-filterhead"><a href="#" class="lwms-addall">' + this.options.addAllText + '</a>&nbsp; | &nbsp;<a href="#" class="lwms-removeall">' + this.options.removeAllText + '</a></div>';
      }
      this.$leftHead = $(tmphtml).appendTo(this.$leftDiv);
      this.$rightHead = $('<div class="lwms-filterhead"><span class="lwms-filcount"></span> '+this.options.selectedLabel+'</div>').appendTo(this.$rightDiv);   
      this.$availList = $('<ul class="lwms-list lwms-available"></ul>').appendTo(this.$leftDiv);
      this.$selectedList = $('<ul class="lwms-list"></ul>').appendTo(this.$rightDiv);
      this.$counter = this.$mainContainer.find('.lwms-filcount');
   
      this.updateList();
      this.initEvents();
    },

    //return if current selected is not more than max select
    isBelowMax: function () {   
      return (this.$selectedList.children().length < this.options.maxSelect);
    },

    /* event: clicking on left container li */
    selectItem: function (that) {   
      if (this.options.maxSelect == 0 || this.isBelowMax()) { //allow selection if there's no max or selection is below max
        var $self = $(that);
        $self.clone().appendTo(this.$selectedList); //clone the element and append to selected, this is required due to search visibility
        $self.addClass('lwms-selected'); //lwms-selected is to preserved visibility state of search filters
        this.$element.find('option[value="' + $self.data('value') + '"]').attr('selected', 'selected'); //mark selected on the source, used attr vs prop because clone doesn't carry over selected attr   
        this.updateCount(); //refresh counts
        this.triggerChange(); //trigger change callback 
      }
    },
 
    /* event: clicking on right container li */
    removeItem: function(that) {
      var $self = $(that);
      this.$availList.find('li[data-value="' + $self.data('value') + '"]').removeClass('lwms-selected'); //remove lwms-selected from available list
      this.$element.find('option[value="' + $self.data('value') + '"]').removeAttr('selected'); //remove selected on the source
      $self.remove(); //remove the current element from selected
      this.updateCount(); //refresh counts
      this.triggerChange(); //trigger change callback
    },
 
    /* event: selecting all visible */
    selectAll: function () {
      if (this.options.maxSelect == 0) { //only allow this if no max specified
        var tmpArrId, $tempAddList = this.$availList.find('li:visible'); //cache list of visible items only (search filters and items not already selected)

        this.$selectedList.append($tempAddList.clone()); //clone the list and append to selected

        tmpArrId = $tempAddList.map(function () {
          return $(this).data('value').toString(); //convert this to string, data values are typed
        }).get(); //get an array of selected values     

        //update the source select
        this.$element.find('option').filter(function (index) {
          return ($.inArray(this.value, tmpArrId) > -1); //inArray checks with ===, we need tmpArrId to be a array of strings
        }).attr('selected', 'selected'); //used attr vs prop because clone doesn't carry over selected attr

        $tempAddList.addClass('lwms-selected'); //mark them with lwms-selected

        this.updateCount();
        this.triggerChange();
      }
    },
 
    /* event: remove all */
    removeAll: function() {
      this.$availList.find('li').removeClass('lwms-selected'); //remove all lwms-selected from available
      this.$selectedList.empty(); //clear selected list
      this.$element.children().removeAttr('selected'); //remove all selected from source, used attr vs prop because clone doesn't carry over selected attr

      this.updateCount();
      this.triggerChange();   
    },
 
    //initial all event handlers
    initEvents: function() {
      var that = this;
      //event delegations
   
      /* clicking items on left container */
      this.$availList.off('click.lwmultiselect','li');
      this.$availList.on('click.lwmultiselect', 'li', function (e) {     
        e.preventDefault();
        that.selectItem(this);
      });

      /* remove clicks */
      this.$selectedList.off('click.lwmultiselect','li');
      this.$selectedList.on('click.lwmultiselect', 'li', function (e) {     
        e.preventDefault();
        that.removeItem(this);
      });
         
      //select all
      this.$mainContainer.off('click.lwmultiselect','.lwms-addall');
      this.$mainContainer.on('click.lwmultiselect','.lwms-addall',function(e) {     
        e.preventDefault();
        that.selectAll();
      });

      //remove all
      this.$mainContainer.off('click.lwmultiselect','.lwms-removeall');
      this.$mainContainer.on('click.lwmultiselect','.lwms-removeall',function(e) {
        e.preventDefault();
        that.removeAll();     
      });
    },
 
    //refresh the containers with the elements from the original source
    updateList : function() {   
      var that = this,
        tmpSelectHtml = '',
        tmpAvailHtml = '',
        $tmpThis,
        tmpVal,
        tmpText,
        selectClass = '';
     
      this.$selectedList.empty(); //clear available and selected list
      this.$availList.empty();   
      this.totalItem = this.$element.children().length; //cache the total per update
   
      //loop through the source and rebuild the list
      this.$element.children().each(function () {
        selectClass = '';
        $tmpThis = $(this);
        tmpVal = $tmpThis.prop('value');
        tmpText = $tmpThis.text();

        //if option is preselected then append to selected and add lwms-selected to the available side     
        if ($tmpThis.is(':selected')) {
          tmpSelectHtml += '<li class="lwms-selectli" data-value="' + tmpVal + '">' + tmpText + '</li>';
          selectClass = ' lwms-selected';
        }
        tmpAvailHtml += '<li class="lwms-selectli' + selectClass + '" data-value="' + tmpVal + '">' + tmpText + '</li>';
      });

      this.$selectedList.html(tmpSelectHtml);
      this.$availList.html(tmpAvailHtml);
      this.updateCount(); 
    },
 
    /* call back function if defined */
    triggerChange: function() {
      if (this.options.onChange != '') {
        this.options.onChange();
      }
    },
 
    /* refresh count */
    updateCount: function () {
      this.$counter.text(this.$selectedList.children().length + '/' + ((this.options.maxSelect == 0 ) ? this.totalItem : this.options.maxSelect));
    }
  };

  // A really lightweight plugin wrapper around the constructor,
  // preventing against multiple instantiations
  $.fn[pluginName] = function (options) {
    return this.each(function () {
      if (!$.data(this, "plugin_" + pluginName)) {
          $.data(this, "plugin_" + pluginName, new Plugin(this, options));
      }
    });
  };
})(jQuery, window, document);



Nah sekarang kamu coba jalankan file nya di htdocs dan kamu cek hasil inputan nya masuk atau engga di database nya. Jika sudah berhasil selamat kamu sukses mengikuti tutorial diatas. namun jika masih gagal bisa di tanyakan di komentar ya..

Oke See u Next Time Guys...
Dzikri Muhammad Sopyana
Dzikri Muhammad Sopyana Silih Asih, Silih Asuh, Silih Asah. Hatur nuhun.

Posting Komentar untuk "Cara Membuat Comobox Tingkat atau Berantai"