I´m trying to use a dinamic select with the Materialize framework, but I can´t get the the expected result.
After the page loads, if you change the first select (the fixed one) we can not the all options on the dinamic select. I made a simple example to ilustrate the issue:
Without Materialize
//ready function -------------------------
$( document ).ready(function() {
startDinamicSelect();
});
// Creating the function to add on listener
function startDinamicSelect() {
// Numbers array
var numbersList = {
1 : ['1','3','5','7'],
2 : ['2','4','6','8'],
3 : ['1','2','3','4','5','6','7','8'],
}
// Adding function to onChange event
document.querySelector('#fixedSelect').addEventListener("change", function(){
// Get values of the object
var items = numbersList[this.value];
// Cleaning select
var selectDinamico = document.querySelector('#dinamicSelect');
selectDinamico.innerHTML = '';
// Addinng the items as selected on the first select
items.forEach(function(item){
var option = document.createElement("option");
option.value = item;
option.text = item;
selectDinamico.appendChild(option);
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body style="margin-left: 20px;margin-right: 20px;margin-top: 10px;">
<html>
Type:
<select name="fixedSelect" id="fixedSelect">
<option value="" selected></option>
<option value="1" >Odd numbers</option>
<option value="2" >Pair numbers</option>
<option value="3" >Both</option>
</select>
<hr>
Number:
<select name="dinamicSelect" id="dinamicSelect"></select>
</html>
</body>
After add the Materialize framework, the dinamic select does not work correctly. Just show the first option and wh can not change the selection
With Materialize
//ready function -------------------------
$( document ).ready(function() {
startDinamicSelect();
$('select').formSelect();
});
// Creating the function to add on listener
function startDinamicSelect() {
// Numbers array
var numbersList = {
1 : ['1','3','5','7'],
2 : ['2','4','6','8'],
3 : ['1','2','3','4','5','6','7','8'],
}
// Adding function to onChange event
document.querySelector('#fixedSelect').addEventListener("change", function(){
// Get values of the object
var items = numbersList[this.value];
// Cleaning select
var selectDinamico = document.querySelector('#dinamicSelect');
selectDinamico.innerHTML = '';
// Addinng the items as selected on the first select
items.forEach(function(item){
var option = document.createElement("option");
option.value = item;
option.text = item;
selectDinamico.appendChild(option);
});
$('select').formSelect('destroy');
});
}
<!-- Compiled and minified CSS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<body style="margin-left: 20px;margin-right: 20px;margin-top: 10px;">
<html>
Type:
<select name="fixedSelect" id="fixedSelect">
<option value="" selected></option>
<option value="1" >Odd numbers</option>
<option value="2" >Pair numbers</option>
<option value="3" >Both</option>
</select>
<hr>
Number:
<select name="dinamicSelect" id="dinamicSelect"></select>
</html>
</body>
I´ve tried to use with no results
$('select').material_select('destroy');
$('select').formSelect('destroy');
Some one could tell what´s wrong? Where is the problem the code does not work properly?
I´ve solved this trouble adding a trigger to listen the contendChanged
//ready function -------------------------
$( document ).ready(function() {
startDinamicSelect();
$('select').formSelect();
});
// Creating the function to add on listener
function startDinamicSelect() {
// Numbers array
var numbersList = {
1 : ['1','3','5','7'],
2 : ['2','4','6','8'],
3 : ['1','2','3','4','5','6','7','8'],
}
// Adding function to onChange event
document.querySelector('#fixedSelect').addEventListener("change", function(){
// Get values of the object
var items = numbersList[this.value];
// Cleaning select
var selectDinamico = document.querySelector('#dinamicSelect');
selectDinamico.innerHTML = '';
// Addinng the items as selected on the first select
items.forEach(function(item){
var option = document.createElement("option");
option.value = item;
option.text = item;
selectDinamico.appendChild(option);
});
//NEW CODE ADDED -----------------------
$("#dinamicSelect").trigger('contentChanged');
});
// NEW CODE ADDED
$('#dinamicSelect').on('contentChanged', function() {
$(this).formSelect();
});
}
<!-- Compiled and minified CSS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<body style="margin-left: 20px;margin-right: 20px;margin-top: 10px;">
<html>
Type:
<select name="fixedSelect" id="fixedSelect">
<option value="" selected></option>
<option value="1" >Odd numbers</option>
<option value="2" >Pair numbers</option>
<option value="3" >Both</option>
</select>
<hr>
Number:
<select name="dinamicSelect" id="dinamicSelect"></select>
</html>
</body>
Related
I have two dropdowns that I need their values inside a URL. I am using selectize for the two dropdowns. But I mostly used jquery for the functions.
Expected output is a URL that changes with value of the two dropdowns after the user clicks on the button.
when I checked the value of the URL after the click event it doesn't show both on the URL instead it occurs differently I believe as it should but is there a way to make these values appear on the url together at once?
$(document).ready(function($) {
$(".dropdown_menu").selectize({
sortField: "text",
placeholder: "Select a value...",
});
$("#dad").on("click", function() {
$(".dropdown_menu").map(function() {
let marketValues = "";
let msmValues = "";
if ($(this).is("#dropdown1")) {
//using join "&" to capture multiple values
marketValues += $(this).val().join("&");
}
if ($(this).is("#dropdown2")) {
msmValues += $(this).val().join("&");
}
//expecting the url change with values of the dropdown after the click event
let url = `localhost:5000/${marketValues}/${msmValues}`;
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.14.0/js/selectize.min.js"></script>
<!-- food Drop down menu -->
<div style="max-width: 200px">
<select id="dropdown1" class="dropdown_menu" multiple="multiple">
<option value="rice">rice</option>
<option value="beans">beans</option>
</select>
</div>
<!-- name dropdown -->
<div style="max-width: 200px">
<select id="dropdown2" class="dropdown_menu" multiple="multiple">
<option value="bob">bob</option>
<option value="max">max</option>
</select>
</div>
<button id="dad">send</button>
There is no need to loop since you already have unique IDs
$(document).ready(function($) {
$(".dropdown_menu").selectize({
sortField: "text",
placeholder: "Select a value...",
});
$("#dad").on("click", function() {
let marketValues = $("#dropdown1").val().join("&"),
msmValues = $("#dropdown2").val().join("&");
//expecting the url change with values of the dropdown after the click event
let url = `localhost:5000/${marketValues}/${msmValues}`;
// do something with the URL here
console.log(url)
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.14.0/css/selectize.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.14.0/js/selectize.min.js"></script>
<!-- food Drop down menu -->
<div style="max-width: 200px">
<select id="dropdown1" class="dropdown_menu" multiple="multiple">
<option value="rice">rice</option>
<option value="beans">beans</option>
</select>
</div>
<!-- name dropdown -->
<div style="max-width: 200px">
<select id="dropdown2" class="dropdown_menu" multiple="multiple">
<option value="bob">bob</option>
<option value="max">max</option>
</select>
</div>
<button id="dad">send</button>
Outside of the map loop declare your variables url, marketValues and msmValues. Then After the loop, generate the URL with the variables. Right now, the URL gets replaced during each loop as well as the other two variables. Also, use an else if not two separate if statements.
Using each is the better option as map is used to apply functions to the content of the array. Where as each simply loops through them
$(document).ready(function($) {
$(".dropdown_menu").selectize({
sortField: "text",
placeholder: "Select a value...",
});
$("#dad").on("click", function() {
let marketValues = "";
let msmValues = "";
$(".dropdown_menu").each(function() {
if ($(this).is("#dropdown1")) {
//using join "&" to capture multiple values
marketValues += $(this).val().join("&");
}
else if ($(this).is("#dropdown2")) {
msmValues += $(this).val().join("&");
}
});
let url = `//localhost:5000/${marketValues}/${msmValues}`;
console.log(url);
});
});
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>
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>
I have 2 comboboxes, first for Province and second for city/town.
I just wanna get the value of my second combobox (city/town) after first combobox changed and second combobox will change with ajax after user chose first the combobox.
Here is my code, but the problem is that the alert shows up twice!
jQuery('#billing_state').on('change', function() {
jQuery('#billing_city').on('change', function() {
var state = jQuery(this).val();
alert(state);
});
});
Why you made an imbrication of event ? just use change on the first combo .
Here is an example :
state = {"1":["Rome","Milan","Parma"],"2":["Paris","Lile","Nice"],"3":["Algiers","Jijel","Bejaia"],"4":["London","Manchester"]}
$(document).ready(function(){
//this if you want that changing province this alert country value
$("#billing_state").on("change",function(e){
$("#billing_town").children().remove();
var city =state[$(this).val()];
if(!city) return;
$("#billing_town").append('<option value="">- Select -</option>')
for(i=0; i< city.length;i++) {
//console.log(city[i]);
$("#billing_town").append('<option value="'+city[i]+'">'+city[i]+'</option>');
}
});
// when changing country this alert country value itself
$("#billing_town").on("change",function(e){
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Province :
<select id="billing_state">
<option value="">- select -</option>
<option value="1">Italy</option>
<option value="2">France</option>
<option value="3">Algeria</option>
<option value="4">UK</option>
</select>
<br><br>
Country :
<select id="billing_town">
</select>
is this what you want. try with demo below
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
<label>Province</label>
<select id="province">
<option>california</option>
<option>austin</option>
<option>texas</option>
<option>colombo</option>
</select>
<hr>
<label>city</label>
<select id="city">
<option>colombo</option>
<option>canberra</option>
<option>silicon valley</option>
<option>ottawa</option>
</select>
</body>
<script type="text/javascript">
$("#province").on('change',function(){// in this line identify if there is any changes to first select box
var thevalue = $("#city").val(); // if there is any changes to first selection box, then at that time get the value of second selection box.
alert(thevalue); // to check the value of secod check box at the time chage put an alert.
});
</script>
</html>
or else if your want to show values according to user selection of first select box value, you can do it like this.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
<label>Province</label>
<select id="province">
<option>california</option>
<option>austin</option>
<option>ottawa</option>
<option>western</option>
</select>
<hr>
<label>City</label>
<select id="city">
<option>--select--</option>
</select>
</body>
<script type="text/javascript">
$("#province").on('change',function(){// in this line identify if there is any changes to first select box
var thevalue = $(this).val(); // if there is any changes to first selection box, then at that time get the
$("#city").text("");
//display values according to the first value
if (thevalue == "california")
{
var cities = ["sillicon valley","st pauls","new york"];
for(var i=0;i<cities.length;i++)
{
var createoption = $('<option>'+cities[i]+'</option>');
$("#city").append(createoption);
}
}
else if(thevalue="austin")
{
var cities = ["mirage","manhatten","las vegas"];
for(var i=0;i<cities.length;i++)
{
var createoption = $('<option>'+cities[i]+'</option>');
$("#city").append(createoption);
}
}
else
{
//like above you can add relevent values.
}
});
</script>
</html>
I have a jQuery autocomplete attached to an textbox input element which works fine.
I have a special requirement in which I would need to have two dropdowns appear with different data. So the user would type in the input textbox and as he is typing it would show two dropdowns side by side and filter both at the same time depending on what he is typing.
Anyone know how I could achieve this ?
Why not use Select2? I've provided an example of a keyup check using jQuery, and then a simple Select2 call on another select so you can see the difference.
$(document).ready(function() {
$('input').on('keyup', function () {
var value = $(this).val();
var $options = $('#test').find('option');
var selected = false;
$options.each(function() {
var $option = $(this);
var text = $option.text()
if( !selected && text.indexOf(value) > -1) {
$option.prop('selected', true);
selected = true;
}
});
});
$('#test2').select2();
});
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<input type="text" />
<br />
<select id="test">
<option></option>
<option val="1">Testing</option>
<option val="2">Why Not?</option>
<option val="3">Use</option>
<option val="4">Select2?</option>
</select>
<br />
<br />
<select id="test2">
<option></option>
<option val="1">See</option>
<option val="2">It's</option>
<option val="3">Much</option>
<option val="4">Better</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>