Javascript multiple select2 doesn't work on click event - javascript

I want to click button to create an multiple selectbox(select2).
Each button click will create a select box with select2 function libraries.
My code will appear only a simple selectbox.
$('.main_select2').select2({
placeholder: 'Selection Box',
allowClear: true
});
$('#add_select').on('click', function() {
$('.for_select').append(
'<div class="c-input c-input--select c-input--icon">'
+ '<select class="select2 main_select2">'
+ '<option>Choose 1</option>'
+ '<option>Choose 2</option>'
+ '<option>Choose 3</option>'
+ '</select>'
+ '</div>');
})
.main_select2{
width:200px;
margin-top:10px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.0.0/select2.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/2.1.0/select2.min.js"></script>
<button type="button" id="add_select">Add Select2</button>
<div class="for_select">
<div class="c-input c-input--select c-input--icon">
<select class="select2 main_select2">
<option>Choose 1</option>
<option>Choose 2</option>
<option>Choose 3</option>
</select>
</div>
</div>
Is there any possible ways to do this with multiple class in select2.
Thanks

You need to initialise your select as a Select2, just as you would for one that exists on page load. Your code appends a new select, but it doesn't initialise it as a Select2.
Here's a working snippet. I've added a hidden CSS class to your first, base select, since you probably don't want that visible.
let count = 0; // Track how many copies we have
let $template = $('.c-input--select'); // The HTML you want to copy each time
let $container = $('.for_select'); // Where the copies should be added
$('#add_select').on('click', function() {
// Increment our counter
count++;
// Create a copy of your base HTML/select
let $copy = $template.clone();
// Find the select in the div, and give it an id so we can find it
$copy.find('select').attr('id', count);
// Append it
$container.append($copy);
// Initialise it as a select2, using the id we just gave it to find it
$('#' + count).select2();
});
.hidden {
display: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.0.0/select2.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/2.1.0/select2.min.js"></script>
<button type="button" id="add_select">Add Select2</button>
<div class="for_select">
<div class="c-input c-input--select c-input--icon">
<!-- add hidden class so the template is not visible -->
<select class="select2 main_select2 hidden">
<option>Choose 1</option>
<option>Choose 2</option>
<option>Choose 3</option>
</select>
</div>
</div>

Related

Bootstrap Multiselect showing 0 selected even if i select multiple values

When I select multiple values it is showing 0 selected in the label. I think there is something wrong with the Javascript. Take a look at this image: https://photos.app.goo.gl/5Dxwt5gvuE277Uyw9
I also want to store all the values in my database. Should I store all the values in an array and then pass it to PHP?
$(document).ready(function() {
$("#multifield1 option:selected").each(function() {
console.log(this.text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
<div class="col-lg-6">
<div class="form-group">
<strong>Area of Interest:</strong>
<select id="multifield1" class="multiselect-ui form-control" multiple="multiple">
<option value="X">X</option>
<option value="Y">Y</option>
<option value="Z">Z</option>
</select>
</div>
</div>
You need to use onChange event handler:
$('#multifield1').multiselect({
onChange: function(option, checked) {
var selectedItems = $("#multifield1 option:selected").length;
console.log('selected items: ' + selectedItems);
}
});
$('button.btn.btn-info').on('click', function(e) {
var selectedItems = $("#multifield1 option:selected").length;
console.log('Info btn: selected items: ' + selectedItems);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
<button type="button" class="btn btn-info">Info</button>
<div class="col-lg-6">
<div class="form-group">
<strong>Area of Interest:</strong>
<select id="multifield1" class="multiselect-ui form-control" multiple="multiple">
<option value="X">X</option>
<option value="Y">Y</option>
<option value="Z">Z</option>
</select>
</div>
</div>
This code is placed in your $(document).ready event handler, meaning it will only execute when the page is first loaded. And I assume that initially on page load, nothing is selected yet.
You could listen for the select's onchange event and use your code inside the handler, so that the code runs every time the select values are changed.
$(document).ready(function() {
$("#multifield1").on("change", function() {
$(this).find("option:selected").each(function() {
console.log(this.text);
});
})
});
To send values in an array to PHP you should set "name" attribute of your select tag like this:
<select name="test[]" id="multifield1" class="multiselect-ui form-control" multiple="multiple">
Also, don't forget to make your form in a tag and add a submit button.

How to display value of the already selected database value from the multiple dropdown

I have a multiple dropdown as below
<select class="select2_multiple form-control" multiple="multiple" id="users'.$id.'" name="users" style="width: 100%;left: 10px;">
<option id="none" value="">Select Users</option>';
... further options generated as per database values (php) ......
</select>
<div id="wrapper" style="top: 105px;"></div>
Now I have a javascript to display the user selected values. this will wrap in another div
<script type=text/javascript>
$('select[name="users"]').change(function() {
$('#wrapper').html('');
$('option:selected', $(this)).each(function() {
$('#wrapper').append(
$('<ul class="user-list"><li>').html($('<span class="avatar"><img src="images/'+$(this).data('useravatar')+'" alt=""> </span><div class="user-info-body"><div class="user-name">'+$(this).data('usertitle')+'</div><span class="country">'+$(this).data('country')+'</span></div></div></li></ul>'))
);
});
});
</script>
This function is working perfectly fine.
The only problem is it will display the selected values only if the dropdown changes or if the users change the dropdown options.
What I want is, I need to display the existing selected values without making any change in the dropdown.
.trigger():
A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user
You can first set the value then trigger the change event:
$('select[name="users"]').val('').trigger('change');
Demo:
$('select[name="users"]').change(function() {
$('#wrapper').html('');
$('option:selected', $(this)).each(function() {
$('#wrapper').append(
$('<ul class="user-list"><li>').html($('<span class="avatar"><img src="images/avatar" alt=""> </span><div class="user-info-body"><div class="user-name">title</div><span class="country">country</span></div></div></li></ul>'))
);
});
});
$('select[name="users"]').val('').trigger('change');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="select2_multiple form-control" multiple="multiple" id="users'.$id.'" name="users" style="width: 100%;left: 10px;">
<option id="none" value="">Select Users</option>
<option id="none1" value="1">1111111</option>
<option id="none2" value="2">2222222</option>
<option id="none3" value="3">3333333</option>
</select>
<div id="wrapper" style="top: 105px;"></div>
Update: You can use localStorage() to trigger the event using the latest selected value.
Inside the change event handler function set the currently selected value using localStorage.setItem()
$('select[name="users"]').change(function() {
localStorage.setItem('latestValue', this.value);
.....
.....
});
Then use that using localStorage.getItem():
var last = localStorage.getItem('latestValue');
if(!last) last = ""; // set to empty if null
$('select[name="users"]').val(last).trigger('change');

How to trigger an Event using an ID in a Select list

I have a select list that triggers DIV tag visibility, which works great, but once I added a new select list it started conflicting with the first list. I need to be able to use the first list to trigger the toggle event independently of any other lists in the code.
I'm to use the select list using a specific ID to properly toggle the DIV visibility but I can't seem to get it right.
$(document).ready(function () {
$("select").change(function () {
$(this).find("option:selected").each(function () {
var optionValue = $(this).attr("value");
if (optionValue) {
$(".divToggle").not("." + optionValue).hide();
$("." + optionValue).show();
} else {
$(".divToggle").hide();
}
});
}).change();
});
This is the select options:
<select id="transferOptions" class="form-control" name="transferoptions" aria-label="Transfer Options" tabindex="">
<option value="fundTransferOption" selected>Select an Option</option>
<option value="achTransfer">ACH Transfer</option>
<option value="flashFundsTransfer">Flash Transfer</option>
</select>
<select id="ConflictingSelectOptionsAlsoCausingDIVToggling">
<option>Choose</option>
<option>Blah</option>
<option>Blah 2</option>
</select>
<div class="achTransfer divToggle">On select show Thing 1</div>
<div class="flashFundsTransfer divToggle">On select show Thing 2</div>
I want to use the Javascript above to specifically work the select list that use the "id="transferOptions", so as I add other select lists to the code it won't conflict with the transferOptionselect list, thus triggering the DIV's in the page.
Use the select ID with its CSS selector #transferOptions. Also changed some logic for you to check out:
$(document).ready(function() {
$("#transferOptions").change(function() {
var optionValue = $(this).val(); // or use javascript: this.value
$(".divToggle").hide(); // hide all .divToggle elements
if (optionValue) { // in your example this is always true
$("." + optionValue).show(); // show the matching element
}
}).change(); // trigger change after document is ready
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="transferOptions" class="form-control" name="transferoptions" aria-label="Transfer Options" tabindex="">
<option value="fundTransferOption" selected>Select an Option</option>
<option value="achTransfer">ACH Transfer</option>
<option value="flashFundsTransfer">Flash Transfer</option>
</select>
<select id="ConflictingSelectOptionsAlsoCausingDIVToggling">
<option>Choose</option>
<option>Blah</option>
<option>Blah 2</option>
</select>
<div class="achTransfer divToggle">On select show Thing 1</div>
<div class="flashFundsTransfer divToggle">On select show Thing 2</div>
You can get the element that event is referring to using event.target instead of using this which in your case refers to the callback function, see example below:
$('select').change(event => {
console.log(event.target.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select1">
<option>foo</option>
<option>bar</option>
<option>baz</option>
</select>
<select id="select2">
<option>quux</option>
<option>xyzzy</option>
</select>

Add a custom event at select2 input search element

I am trying to target a select2 element from the DOM and attach to its input field a keyup event. Because the element its hidden and created after the selection is pressed I cannot set any id or class name to the input. I made it work with event delegation using this code:
$('body').on('keyup', '.select2-search__field', function() {
//TODO: do some work here
});
This works fine, however it works for all the select2 elements I have on the page. I want to target a specific select2 element. I tried also to get the parent of the input so I can check which select2 element is currently used but it is not possible since select2 creates the elements directly at the body and not at the selection element. So all the select2 elements have parents with same classes and cannot be differentiated.
I am using the 4.0.4 version of the select2 and as I read so far the documentation there is no option to attach a custom event to the input.
You can use index() and .select2-container--open class to find the item.
$(document).ready(function(){
$('select').select2();
})
$('body').on('keyup', '.select2-search__field', function() {
var selectItem = $('.select2-container--open').prev();
var index = selectItem.index();
var id = selectItem.attr('id');
alert('index of the item =' + index +' and the id = '+ id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<select id="first">
<option value="a">aaaaaaaaaaaaaaa</option>
<option value="b">bbbbbbbbbbbbbbb</option>
<option value="c">ccccccccccccccc</option>
</select>
<select id="second">
<option value="1">111111111111</option>
<option value="2">222222222222</option>
<option value="3">333333333333</option>
</select>
<select id="third">
<option value="q">qqqqqqqqqq</option>
<option value="w">wwwwwwwwww</option>
<option value="e">eeeeeeeeee</option>
</select>
You can find the select that is being clicked by $(".select2-container--open").prev(); and check if it has specific data-attribute you added to determine whether to do the stuff or not.
$(document).ready(function() {
$('.my-select').select2();
});
$('body').on('keyup', '.select2-search__field', function() {
let $select = $(".select2-container--open").prev();
if($select.data("show")) {
// TODO: do some work here
console.log(this.value)
}
});
select {
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<div>
<select class="my-select">
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
</div>
<div>
<select class="my-select" data-show="true">
<option value="3">Option3</option>
<option value="4">Option4</option>
</select>
</div>
You could use :eq in the selector; https://api.jquery.com/eq-selector/
eq(1) because you want the second, index starts at 0
$('body').on('keyup', '.select2-search__field:eq(1)', function() {
//TODO: do some work here
});
Do run the snippet and change the value of the select fields;
$(document).on("change", ".select2-search__field:eq(1)", function() {
alert("Hello World!");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select2-search__field">
<option>A1</option>
<option>A2</option>
<option>A3</option>
</select>
<select class="select2-search__field">
<option>B1</option>
<option>B2</option>
<option>B3</option>
</select>
<select class="select2-search__field">
<option>C1</option>
<option>C2</option>
<option>C3</option>
</select>

How to apply on change event on a select box inside a dialog

I wrote some HTML as follows:
<div id = "dialog-1" title = "Dialog Title goes here...">
<select id= "lang" name= "lang">
<option value="1"> TEXT </option>
<option value="2"> HTML </option>
</select>
</div>
I want to open a dialog box and apply onChange() event for select box to perform operations on selected value.
I am opening the dialog as follows :
$("#dialog-1").dialog({width: 600,height:500});
Now I want to perform On change() event on select box. I have tried as bellow but it doesn't work :
$("#dialog-1").dialog({
var lang = $("#lang").val();
alert("lang :: "+lang);
});
Nothing really changes for your jQuery. You will need to assign a .change() callback on the <select> element. You can choose to be more specific if you wish.
$(function() {
$("#dialog-1").dialog({
width: 600,
height: 500
});
$("#dialog-1 #lang").change(function(e) {
var lang = $(this).find("option:selected").val();
console.log("lang :: " + lang);
$(this).parent().dialog("close");
});
$("a[rel='dialog']").button().click(function(e) {
e.preventDefault();
$($(this).attr("href")).dialog("open");
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Open Language Selection
<div id="dialog-1" title="Select Language">
<select id="lang" name="lang">
<option value="1"> TEXT </option>
<option value="2"> HTML </option>
</select>
</div>
As you can see, it's all about using the proper selector and proper callback function.
If the element is dynamically created, you can then use the .on() function.
$("#dialog-1").on("change", "select", function(){});
Hope that helps.

Categories