简体   繁体   中英

PHP: Set second dropdown options based on first dropdown choosen option using kartik Select2

I've an application using yii2 framework. I'm trying to use select option (dropdown select), and I use Kartik Select2 .

This is the view of my select option 在此处输入图片说明

In pics above you can see I've two select option, but I've condition. This is the condition.

My first dropdown option( transaction id ) contain 2 options, there are

  1. Buy
  2. Sell

and if user choose the 1. Buy , the second dropdown option( payment method ) will show

  1. Cash
  2. E-money transaction as options, and will show 1. Cash only as option if user choose 2. Sell .

How do I can do it using Kartik Select2?

Any help will be apreciated.

Thanks.

As per your requirement, you need to update the second dropdown options based on first dropdown. First assign ids for dropdowns, first one id will be first-dropdown and second one id will be second-dropdown. add below code inside in your first dropdown change event.

// get first dropdown value here
var firstDropdownValue = $("#first-dropdown").select2("val");


var $secondDropdown = $('#second-dropdown');

// get all second dropdown options
var options = $secondDropdown.data('select2').options.options;

// delete all options of the native select element
$secondDropdown.html('');

// build new items
var items = [];

items.push({
    "id": 1,  // value of option
    "text": 'Cash' // name of option
});

$secondDropdown.append("<option value=\"1\">Cash</option>");

// check the first dropdown value and add E-money option
if(firstDropdownValue == 1){
    items.push({
        "id": 2,
        "text": 'E-money'
    });

    $secondDropdown.append("<option value=\"2\">E-money</option>");
}

// add new items
options.data = items;
$secondDropdown.select2(options);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM