Chosen dropdown search is not working for dynamically populated options - javascript

I am using Chosen dropdown and populating the option dynamically. search in the dropdown is not working even i cant enter the text but it is working fine when dropdown options are static. Please help.
<select id="test" class="chosen-select">
<option>Select1</option>
</select>
var div2=[];
div2.push("<option value='1'>ALL1</option>");
div2.push("<option value='2'>ALL2</option>");
div2.push("<option value='3'>ALL3</option>");
div2.push("<option value='4'>ALL4</option>");
div2.push("<option value='5'>ALL5</option>");
$("#test").html(div2.join(''));
$("#test").trigger("chosen:updated");

Make sure to call .chosen() after you've dynamically populated the dropdown.
Here is a fiddle https://jsfiddle.net/npzs2bt7/
EDIT 1 :
Probably you didn't call chosen() on the dropdown before you could call trigger("chosen:updated").
Updated fiddle https://jsfiddle.net/npzs2bt7/1/
EDIT 2 :
Using Jquery 1.9.0, Chosen.Jquery 1.1.0
Copy this into an html file (chosentest.html) and try it.
<html>
<head>
<title>chosen demo</title>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
<style type="text/css">
#test
{
width:100px;
}
</style>
</head>
<body>
<select id="test" class="chosen-select">
<option>Select1</option>
</select>
<button class="btn">Click to see selected value</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//first call chosen()
$("#test").chosen();
var div2=[];
div2.push("<option value='1'>ALL1</option>");
div2.push("<option value='2'>ALL2</option>");
div2.push("<option value='3'>ALL3</option>");
div2.push("<option value='4'>ALL4</option>");
div2.push("<option value='5'>ALL5</option>");
$("#test").html(div2.join(''));
//this will bind the updates
$("#test").trigger("chosen:updated");
//text button to alert selected value from dropdown
$(".btn").click(function(){
alert($("#test").val());
});
});
</script>
</body>
</html>

Related

Materialize CSS breaks event listener for changing selected value in dropdown list

The goal is to reset the value of a dropdown list by pressing a button. Using vanilla javascript and html the following code works fine:
HTML/JS:
button = document.getElementById('button')
button.addEventListener('click', e => {
console.log('executed')
document.getElementById('sel').value = 'bike'
})
<select id="sel">
<option value="car">1</option>
<option value="bike">2</option>
<option value="cycle">3</option>
</select>
<button id="button">Test</button>
As expected, when the button is pressed, the value "2" is listed in the dropdown list. However, as soon as I add materialize CSS to my HTML, the value in the dropdown list is unchanged when I click the button. I know the event listener is triggered because "executed" is displayed in the console whenever I press the button. However, the value in the dropdown menu does not change like it did before in the vanilla javascript/html. How could this happen and what can I do to troubleshoot this to find the source?
HTML/JS with materialize CSS:
$(document).ready(function() {
// Initialize materialize data picker
$('.datepicker').datepicker({
'format': 'yyyy-mm-dd'
});
$('select').formSelect();
});
button = document.getElementById('button')
button.addEventListener('click', e => {
console.log('executed')
document.getElementById('sel').value = 'bike'
})
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.1/css/materialize.min.css" integrity="sha256-qj3p6P1fJIV+Ndv7RW1ovZI2UhOuboj9GcODzcNFIN8=" crossorigin="anonymous" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.1/js/materialize.min.js" integrity="sha256-SrBfGi+Zp2LhAvy9M1bWOCXztRU9Ztztxmu5BcYPcPE=" crossorigin="anonymous"></script>
</head>
<body>
<select id="sel">
<option value="car">1</option>
<option value="bike">2</option>
<option value="cycle">3</option>
</select>
<button id="button" type="button" class="bold waves-effect waves light btn-large teal lighten-2">Test</button>
</body>
</html>
Thank you to whoever provided the edit to make this executable. After playing with this a little more I noticed that after pressing the button, if you click on the dropdown menu again the value automatically changes to "2" before you even select another option.
You could reinitialize the plugin in your eventListener after the update of the select element.
In addition to my code, you should outsource the initialization to a function in order to stay DRY.
$(document).ready(function() {
// Initialize materialize data picker
$('.datepicker').datepicker({
'format': 'yyyy-mm-dd'
});
$('select').formSelect();
});
button = document.getElementById('button')
button.addEventListener('click', e => {
console.log('executed')
document.getElementById('sel').value = 'bike'
$('.datepicker').datepicker({
'format': 'yyyy-mm-dd'
});
$('select').formSelect();
})
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.1/css/materialize.min.css" integrity="sha256-qj3p6P1fJIV+Ndv7RW1ovZI2UhOuboj9GcODzcNFIN8=" crossorigin="anonymous" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.1/js/materialize.min.js" integrity="sha256-SrBfGi+Zp2LhAvy9M1bWOCXztRU9Ztztxmu5BcYPcPE=" crossorigin="anonymous"></script>
</head>
<body>
<select id="sel">
<option value="car">1</option>
<option value="bike">2</option>
<option value="cycle">3</option>
</select>
<button id="button" type="button" class="bold waves-effect waves light btn-large teal lighten-2">Test</button>
</body>
</html>

How dynamically duplicate a select tag that is converted to select2.js?

I am trying to use select2 in my project.
In the following screenshot, I want to duplicate the social media section (include select2, input and remove btn) dynamically after a user clicks on the ADD More button:
To avoid conflict, I am calling destroy event for all select2 at the beginning of the click event. Then, I will duplicate the elements. Then, I will re-initialize select2. But, it will always just convert one select to select2.
In the following screenshot, you can see duplicated selects are not converted to select2:
The following snippet code shows the problem:
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
</head>
<body>
<button onclick="duplicate_select();">duplicate</button>
<br/><br/>
<select class="selection" name="state">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
<script>
$(document).ready(function() {
$('.selection').select2();
});
function duplicate_select ()
{
//Destroy all active select2
$(".selection").each(function (index, value) {
var temp_selecte2 = $(value).select2();
temp_selecte2.select2('destroy');
});
//Get First Select Node that I want to duplicate
var first_node = $('.selection').first().prop('outerHTML');
//Add new node to the body
$('body').append(first_node);
//Re-initialize all select2
$(".selection").each(function (index, value) {
var temp = $(value).select2();
//temp.select2();
});
//Following codes is not working too
//$(".selection").select2();
}
</script>
</body>
</html>
Can you please guide me how I can solve this problem and Re-initialize all duplicated select elements?
The issue occurs because Select2 requires the select tag to be unique, the select2() method identifies this by using an attribute called data-select2-id, the only thing you need to do is modify that attribute.
Your problem can be fixed by either removing the attribute or setting a unique one. To set unique one just add the line temp.attr('data-select2-id', new Date().getTime()), but the recommended way is to remove it temp.removeAttr('data-select2-id')
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
</head>
<body>
<button onclick="duplicate_select();">duplicate</button>
<br/><br/>
<select class="selection" name="state">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
<script>
$(document).ready(function() {
$('.selection').select2();
});
function duplicate_select ()
{
//Destroy all active select2
$(".selection").each(function (index, value) {
var temp_selecte2 = $(value).select2();
temp_selecte2.select2('destroy');
});
//Get First Select Node that I want to duplicate
var first_node = $('.selection').first().prop('outerHTML');
//Add new node to the body
$('body').append(first_node);
//Re-initialize all select2
$(".selection").each(function (index, value) {
var temp = $(value);
temp.removeAttr('data-select2-id');
// temp.attr('data-select2-id', new Date().getTime()); // <-- this works too
temp.select2();
});
}
</script>
</body>
</html>

Replace another dropdown while the value in one drop down selected

I have 2 select boxes with ids dd1,dd2. While selecting a value from select box 1 the value in seelct box 2 should be replaced in jquery. The following is not worked. What mistake I am doing here?
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
<script src="jquery-1.12.0.min.js"></script>
<head>
<script>
function change(){
alert("Hi");
$('dd2').children().remove().end().append('<option selected value="5">5</option>') ;
}
</script>
</head>
<body>
<select id="dd1" onchange=change()>
<option>1<option>
<option>2<option>
<option>3<option>
<option>4<option>
</select>
<select id="dd2">
<option>A<option>
<option>B<option>
<option>C<option>
<option>D<option>
</select>
</body>
</html>
You need to add # in your Jquery selector for an ID: $('#dd2')...
Here is a working fiddle: https://jsfiddle.net/p5g3p0t5/

trying to add an option to a dropdown list and have it displayed in the dropdown

As the title says, I'm trying to add an option to a dropdown and have it displayed in the list.
Here's a sample example (I maybe old but this is my first stab at the world of web)
When you press the add button a new option should appear in the list "Pasta", but it is not being displayed. If you "select all" and press the "Products" button the alert displays "Pasta".
I've spent over a week looking for a solution and I am here out of desperation!
<!DOCTYPE html>
<html>
<head>
<title>Simple List Example</title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#productsList").multiselect({
includeSelectAllOption: true
});
$("#selectedButton").click (function() {
var selected = $("#productsList option:selected");
var message = "Products:\n";
selected.each(function () {
message += " " + $(this).text() + " " + $(this).val() + "\n";
});
alert(message);
});
$('#addButton').click(function(){
$("#productsList").append(new Option("Pasta", "6"));
});
});
</script>
</head>
<body>
<select id="productsList" multiple="multiple">
<option value="1">Cereal</option>
<option value="2">Soft Drinks</option>
<option value="3">Staples</option>
<option value="4">Salad Dressing</option>
<option value="5">Ice Cream</option>
</select>
<input type="button" id="selectedButton" value="Products"/>
<input type="button" id="addButton" value="Add"/>
</body>
</html>
Please feel free to reduce the problem (but not too much) and please don't get too esoteric.
Thanks in advance
Since you're using bootstrap multi-select , everytime you add a new option element you need to "rebuild" the element. You can check that method on the documentation right here: http://davidstutz.github.io/bootstrap-multiselect/#methods
So the code would be something like this:
$('#addButton').click(function(){
$("#productsList").append(new Option("Pasta", "6"));
$('#productsList').multiselect('rebuild');
});
The problem is that when you initialise your multiselect, it appends a hidden DOM element class="multiselect-container dropdown-menu" to your productlist.
This new element is responsible for displaying items in your list.
You need to rebuild your multiselect after adding the new option.
$('#addButton').click(function(){
$("#productsList").append(new Option("Pasta", "6")).multiselect("rebuild");
});
I would highly recommend using Firebug or Chrome's dev tools to view your DOM.

Change selected value of DDSlick dropdown using JavaScript

In my website, I am using the DDSlick plugin for styling my select dropdown. It is nice. But I can't change the selected value using javascript.
For example, if the current selected value is "INDIA", then I want to change "INDIA" to "USA" by using javascript, without refreshing the page. Is there any way to do this?
Thanks in advance.
If you want force a specific selected items on click on buttons you culd use this code.
<!DOCTYPE HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.ddslick.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#dropdown').ddslick({
width: 300,
selectText: "Select an item",
onSelected: function (data) {
console.log(data)
}
});
$('#button').on('click', function () {
$('#dropdown').ddslick('select', {index: 2 });
});
})
</script>
</head>
<body>
<select id="dropdown">
<option>select</option>
<option id="a" value="">INDIA</option>
<option id="b" value="">USA</option>
<option id="c" value="">AFRICA</option>
</select>
<input name="" type="button" value="change" id="button">
</body>
</html>
with similar code you can create a button to browse through all the options in the list
fiddle
If this solution does not suit your needs, i apologize for making you lose time.

Categories

Resources