Issue creating a select menu dynamically using object data and materialize - javascript

I am trying to place a select menu into a modal and have a strange issue in that the select menu is loaded with display:none so it is hidden is that normal behaviour with materialize?
The name field above the select only shows the first entry from the select unless I remove the display:none in the inspector which then allows me to choose any value from my select with it repeating that value above.
What am I doing wrong?
this is the div I am adding the select into
<div class="input-field col s12">
<select class="custName">
</select>
<label>Select Customer</label>
</div>
I am calling this at the end of my html page
<script>$(document).ready(function(){
$('select').formSelect();
});</script>
creating my selects options here
const custData = (data) => {
if (data.length) {
let html = '';
data.forEach(doc => {
const cust = doc.data();
//console.log(cust);
const select = `
<select>
<option value=${cust.customerId}>${cust.name}, ${cust.address.postCode}</option>
</select>
`;
html += select;
});
customerList.innerHTML = html;
} else {
customerList.innerHTML = '<ul class="center-align">no data</ul>'
}
};
Please put me out of my misery

The issue is that, your $('select').formSelect(); is being executed before you are populating your option tags.
The Solution:
Make the intialization call after your option tag population code.
Note: don't enclose every option tag with a select tag in your custData() function
For example, this one executes initialization statement before population :
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>
<body>
<div class="input-field col s12">
<select id="s_1" class="custName">
</select>
<label>Select Customer</label>
</div>
<script type="text/javascript">
var select = document.getElementById("s_1");
var options = "<select><option value = 1>1</option></select><select><option value = 2>2</option></select><select><option value = 3>3</option></select>";
setTimeout(function(){ select.innerHTML = options; }, 1000);
$(document).ready(function() {
$('select').formSelect();
});
</script>
</body>
</html>
This one Executes initialization after population:
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>
<body>
<div class="input-field col s12">
<select id="s_1" class="custName">
</select>
<label>Select Customer</label>
</div>
<script type="text/javascript">
var select = document.getElementById("s_1");
var options = "<select><option value = 1>1</option></select><select><option value = 2>2</option></select><select><option value = 3>3</option></select>";
setTimeout(function(){ select.innerHTML = options; $('select').formSelect();}, 3000);
$(document).ready(function() {
$('select').formSelect();
});
</script>
</body>
</html>

You have to intialize formSelect() on select after your modal is open so it will work. Replace modal_id with your modal id attribute.
$('#modal_id').on('shown.bs.modal', function (e) {
$('select').formSelect();
});

Related

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>

Jquery MultiSelect Dropdown is not working correctly with data from Ajax call

I am using a multiselect dropdown to have a checkbox and Search functionality.
I have added all the required libraries. But the dropdown is not showing correctly. The data is displayed as radio buttons instead of check box. And Selecting any value is not shown. Please find my code below:
<head>
<link rel="stylesheet"
href="https://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/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">
<script type="text/javascript" src="/resources/js/app.js"></script>
<script src="http://igniteui.com/js/modernizr.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#fileList').change(function() {
var end = this.value;
alert("Value:" + end);
$.ajax({
type: "POST",
url: 'getColumns',
data : {
end
},
dataType: 'json',
success: function (response) {
alert('something'+response+"="+response.length);
alert('res'+response[0]);
for(var i = 0; i<response.length; i++){
var id = response[i];
$("#columnList").append("<option value=''>"+id+"</option>");
}
$('#columnList').multiselect({
includeSelectAllOption: true,
buttonWidth: 500,
enableFiltering: true
});
},
error: function() {
alert('fail');
}
});
});
});
</script>
HTML code for Select Element
<div class="row">
<div class="col-sm-12 form-group wow fadeInDown"
data-wow-delay="700ms" data-wow-duration="1000ms">
<div class="input-group">
<span class="input-group-addon"><span
class="glyphicon glyphicon-file"></span></span> <select
class="form-control" name="columnList" id="columnList">
<option value="" hidden>Select Segment Name</option>
</select>
</div>
</div>
</div>
I am Expecting Output like this.
I hope you have to change your option value code in your jquery. try modifying your code like below:
$("#columnList").append("<option value="+id+">"+value+"</option>");
Also, try to check the class for showing checkbox

Need a two dropdown in html to show different json values

I want to display two different values from json in two different dropdowns in html but its not displaying. I am currently using the following code :
How to separate Name in one dropdown and Age in the other dropdown in js.
Here is my json data :
{
"action": [
{"name":"Ankit","age":"23"},
{"name":"Ankit2","age":"23"}
]
}
$(document).ready( function(){
$.getJSON("jsondata.json",function(data){
$.each(data.action,function(){
$("select").append("<option>Name: "+this['name']+"</option><option>Age: "+this['age']+"</option><br/>");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<title>
</title>
</head>
<body>
<select>
</select>
<select>
</select>
<script type="text/javascript" src="script/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="script/myscript.js"></script>
</body>
</html>
Added id attribute to both selects to be able to select with jQuery easily.
I also added your sample json data to http://jsbin.com/pegabe/1.json.
$.each(data.action, function() {
nameDropdown.append($("<option></option>")
.text('Name:' + this['name']));
ageDropdown.append($("<option></option>")
.text('Age:' + this['age']));
});
nameDropdown is the reference to <select id="name"></select>
$('<option></option>') - creates a <option></option>
.text('Name:' + this['name']) - appends text to the option like this <option>Name: + this['name']</option>
finally this option is appended to nameDropdown.
Hope this helps.
$(document).ready(function() {
$.getJSON("http://jsbin.com/pegabe/1.json", function(data) {
var nameDropdown = $("#name"); // dropdown for name
var ageDropdown = $("#age"); // dropdown for age
$.each(data.action, function() {
nameDropdown.append($("<option></option>")
.text('Name:' + this['name']));
ageDropdown.append($("<option></option>")
.text('Age:' + this['age']));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<title>
</title>
</head>
<body>
<select id="name">
</select>
<select id="age">
</select>
<script type="text/javascript" src="script/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="script/myscript.js"></script>
</body>
</html>
Change your HTML slightly, Add ID to select element
<select id="name">
</select>
<select id="age">
</select>
Script
$.getJSON("jsondata.json", function(data) {
$.each(data.action, function(index, elem) {
//Append option to name
$("#name").append($("<option />", {
value: elem.name,
text: "Name: " + elem.name
}));
//Append age
$("#age").append($("<option />", {
value: elem.age,
text: "Age: " + elem.age
}));
});
});
Note: Also use only single version of jQuery.

Dropdown form Javascript create a range of numbers

I'm trying to create a range of numbers in a dropdown form using JavaScript.
However, it looks like
…and it does not show any options and clicking on the arrow does not pop up more options. I already checked that my path is correct.
I tried it in JSFiddle and it works but not when I put it in my HTML.
I'm going crazy on why this is not working.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../stylesheets/main.css">
<script type="text/javascript" src="../assets/main.js"></script>
</head>
<body id="gradient">
<div id="down" class="center">
<p >Word Size</p>
<select id="length">
</select>
</div>
</body>
</html>
main.js
var select = document.getElementById('length');
for (var i = 0; i<= 24; i++){
var option = document.createElement('option');
option.value = i;
option.innerHTML = i;
select.options.add(option);
}
The problem is that when main.js script is parsed and executed, there is no element with id length yet in DOM. The simplest solution is to move your script to the very end of body tag:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="../stylesheets/main.css">
</head>
<body id="gradient">
<div id="down" class="center">
<p >Word Size</p>
<select id="length"></select>
</div>
<script type="text/javascript" src="../assets/main.js"></script>
</body>
</html>
The reason why it works in jsFiddle, is because it's configured so that script section is executed on window.onload event (in the right side-panel, dropdown "onLoad"). Of course, you could do the same, e.g. in main.js:
window.onload = function() { /* previous main.js code */};
In this case you would not need to move script anywhere.

Get the selected value of a dropdown list

I have the follwing code. I want to get the value of the selected value of the dropdownlist once the user changes it or to have the default value to be displayed by alert(). I need to use alert() from within the < body > of the html. Is that possible?
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="phonegap-1.4.1.js">
</script> <script type="text/javascript" src="JS/Util.js"></script>
<script type="text/javascript" src="JS/Language.js"></script>
<script type="text/javascript">
function dropdown(){
var drp = document.getElementById("numberlist");
var optn = document.createElement("OPTION");
optn.text="3";
optn.value="3";
drp.add(optn);
}
</script>
</head>
<body onload="dropdown();"> <div id="main3"></div> <form><select id = "numberlist"><option>12</option><option>24</option><option>36</option></select>
Use the code:
selectElement.options[ selectElement.options.selectedIndex ];
to find the index that is selected.
So where you say var drp = document.getElementById("numberlist"); you can now find the value of the index by doing:
var value = drp.options[ drp.options.selectedIndex ].value;
Add the code into an onchange event so that whenever you change the selectedIndex of the element, you will be able to obtain it's value:
Here is a DEMO
Try this Following...Mark it as answer if it helps you
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="phonegap-1.4.1.js"> </script> <script type="text/javascript" src="JS/Util.js"></script>
<script type="text/javascript" src="JS/Language.js"></script>
<script type="text/javascript">
function dropdown()
{
var drp = document.getElementById("numberlist");
var optn = document.createElement("OPTION");
optn.text="3";
optn.value="3";
drp.add(optn);
}
</script>
</head>
<body onload="dropdown();">
<div id="main3">
</div>
<form>
<select id="numberlist" onchange="show()">
<option>12</option>
<option>24</option>
<option>36</option>
</select>
<script type="text/javascript">
function show() {
var e = document.getElementById('numberlist');
var txt = e.options[e.selectedIndex].text;
alert(txt);
}
</script>
</form>
</body>
</html>
add this function within script tag.
function pickvalue(id){
var drp = document.getElementById(id);
alert(drp.value);
}
and add function call like this.
<select id = "numberlist" onchange="pickvalue(this.id)">
Here is a JQuery method:
$value = $("#numberlist option:selected").text();
alert($value);

Categories

Resources