get the values of two dropdowns into a url - javascript

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);
});
});

Related

Javascript multiple select2 doesn't work on click event

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>

How to load a select option using Materialize

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>

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');

Adding values from dropdown to table javascript

Whenever the user clicks on a value in the drop down, I want to create a table with the values in it. When you unchecked the checkbox, it should dissapper from the table. The problem that I have is that, it keeps appending the selection like this:
This is how it should look like:
This is my asp code. I also would like to target a specific table by it's ID. because I'll have about 20 dropdown in this page.
<asp:ListBox ID="ddlRolePosition" AutoPostBack="false" runat="server"
SelectionMode="Multiple" class="selectpicker show-tick form-control show-tick"
multiple data-validation-event="change" style="display: none;">
</asp:ListBox>
<table>
<tbody>
</tbody>
</table>
$("[id$=ddlRolePosition]").change(function() {
if (!$("[id$=ddlRolePosition]").val()) {
}
else {
var markup = "<tr><td>" + $("[id$=ddlRolePosition]").val() + "</td></tr>";
$("table tbody").append(markup);
}
});
You can:
Wrap the select and table elements so you can access many on a single page
Grab the selected options via select.selectedOptions
Added an empty() method that mimics jQuery.fn.empty
Added a triggerEvent() method that mimics jQuery.fn.trigger
// Add event listeners
Array.from(document.querySelectorAll('.preview-combo select')).forEach(combo => {
combo.addEventListener('change', onComboChange);
});
// Pre-select some options...
let combo = document.querySelectorAll('.preview-combo select');
combo[0].options[0].selected = true; // First combo, first option
combo[0].options[1].selected = true; // First combo, second option
combo[1].options[1].selected = true; // Second combo, second option
combo[1].options[2].selected = true; // Second combo, third option
// Fire change events (for initial loading only)
Array.from(combo).forEach(combo => triggerEvent(combo, 'change'))
function onComboChange(e) {
let select = e.target, table = select.parentElement.querySelector('table'),
values = Array.from(select.selectedOptions).map(opt => opt.value);
appendRows(table, values);
}
function appendRows(table, values) {
let tbody = empty(table.querySelector('tbody'));
values.forEach((value) => {
let tr = document.createElement('tr'), td = document.createElement('td');
td.textContent = value; tr.appendChild(td); tbody.appendChild(tr);
});
return table;
}
function triggerEvent(el, eventName) {
var event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, false);
el.dispatchEvent(event);
return el;
}
function empty(el) {
var range = document.createRange();
range.selectNodeContents(el);
range.deleteContents();
return el;
}
.preview-combo {
display: inline-block;
}
.preview-combo select {
width: 100px;
}
<div class="preview-combo">
<select multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table class="selected-values">
<tbody><tr><td><em>Results</em></td></tr></tbody>
</table>
</div>
<div class="preview-combo">
<select multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table class="selected-values">
<tbody><tr><td><em>Results</em></td></tr></tbody>
</table>
</div>
jQuery + Bootstrap
Here is an example with jQuery.
(($) => {
$.fn.selectedValues = function() {
return this.find('option:selected').map((i, opt) => opt.value).get();
};
})(jQuery);
$('select').selectpicker(); // Convert to a picker.
// Add event listeners
$('.preview-combo select').on('change', onComboChange);
// Pre-select some options...
let $combo = $('.preview-combo select');
$combo.get(0).options[0].selected = true; // First combo, first option
$combo.get(0).options[1].selected = true; // First combo, second option
$combo.get(1).options[1].selected = true; // Second combo, second option
$combo.get(1).options[2].selected = true; // Second combo, third option
// Fire change events (for initial loading only)
$('.preview-combo select').trigger('change');
function onComboChange(e) {
let $sel = $(e.target);
populateTable($sel.closest('.preview-combo').find('table'), $sel.selectedValues());
}
function populateTable($table, values) {
return $table.find('tbody').empty().append(values.map(value => {
return $('<tr>').append($('<td>').text(value));
}));
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
<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.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm">
<div class="preview-combo">
<select multiple class="form-control">
<option value="1">Audit Assistant</option>
<option value="2">Audit Expert</option>
<option value="3">Auditor</option>
</select>
<table class="selected-values">
<tbody><tr><td><em>Results</em></td></tr></tbody>
</table>
</div>
</div>
<div class="col-sm">
<div class="preview-combo">
<select multiple class="form-control">
<option value="1">Audit Assistant</option>
<option value="2">Audit Expert</option>
<option value="3">Auditor</option>
</select>
<table class="selected-values">
<tbody><tr><td><em>Results</em></td></tr></tbody>
</table>
</div>
</div>
</div>
</div>
I'd approach this differently and rather keep an array of selected items and then pass those to a function that should generate the rows of the table.
See example below that can be applied:
let target = document.querySelector('#target');
function generateRows(items) {
// clear the rows
target.innerHTML = '';
let rows = '';
for(let i = 0; i <items.length; i++) {
rows += `<tr><td>${items[i]}</td></tr>`;
}
// append once
target.innerHTML = rows;
}
document.querySelector('.select').onchange = function (e) {
let items = [];
for (var i= 0; i < e.currentTarget.options.length; i++) {
let opt = e.currentTarget.options[i];
if (opt.selected) {
items.push(opt.value);
}
}
// pass the selected items to function to generate the rows
generateRows(items);
};
<select class="select" multiple style="width: 100px;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table>
<tbody id="target">
<tr><td>rows here</td></tr>
</tbody>
</table>

Can't get values from SemanticUI multi dropdown

I'm trying to get the user selections from a multi-select dropdown but I don't seem to be able to get them. Here is the HTML:
<div id="content_dropdown" class="ui multiple search normal selection dropdown" style="border-radius: 0px;width: 100%;">
<i class="dropdown icon"></i>
<div class="default text">Dashboard widget, Improved reporting</div>
<div id="content_dropdown_menu" class="menu">
{% for content_tag in content_tags %}
<div class="item" data-value="{{content_tag}}">{{content_tag}}</div>
{% endfor %}
</div>
</div>
And here is the javascript I have tried:
var selectedValues = $('#content_dropdown').val();
var selectedValues = $('#content_dropdown').dropdown('get value');
Both of these return nothing even though the dropdown is populated.
I should also note that I had this working in a separate page, but I have been moving content onto 1 page, where I put this form into a modal. I'm not sure why this would affect it, just thought I'd point it out.
Thanks.
.dropdown('get value') won't work for multiple. You'll have to find a way to observe changes to dropdown. Here's how to do it in Aurelia:
form.html:
<select id="thickness" name="thick" multiple="" class="ui multiple dropdown selection" value.bind="thickness_selected">
<option value="">Выбрать</option>
<option value="100">100 mm</option>
<option value="150">150 mm</option>
</select>
form.ts:
export class form {
thickness_selected: number[] = [];
submit() {
const self = this;
for (let id of self.thickness_selected) {
console.log(id);
}
}
}
Try this:
var selectedValues;
$('#content_dropdown')
.dropdown({
action: function(text, value) {
selectedValues = value;
}
})
;

Categories