Bootstrap selectpicker not working on multiple fields added by Javascript / JQuery - javascript

Bootstrap select picker not working when loaded with jQuery /javascript dynamic fields.
When i remove selectpicker class from append function,it works but doesn't load style.
$('select').selectpicker();
$('#add_more').click(function() {
$('.testBox').append('<select class="show-tick form-control"><option>Safari</option><option>Firefox</option><option>Chrome</option></select> <br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
Add More
<select class="selectpicker show-tick form-control">
<option>Safari</option>
<option>Chrome</option>
<option>Firefox</option>
</select>
<br /><br />
<div class="testBox"></div>

JS is not reactive in the sense that $('select') will update with all the newly added instances of <select> elements. Since $('select').selectpicker() is executed when additional select elements have not been added to the DOM, it will only apply to those that are available at runtime—which is the one that is present in the DOM at that moment in time.
In order to initialize the plugin for newly added <select> elements, you can simply create a dummy <div> element and append your <select> element to it:
var $select = $('<div />').append('<select class="show-tick form-control"><option>Safari</option><option>Firefox</option><option>Chrome</option></select>');
Now, your to-be-added element will be available as a document fragment. jQuery is able to bind events to elements in the document fragment even before it is injected into the DOM, so you can initialize the plugin right then and there. We simply search the dummy div for your <select> element:
$select.find('select').selectpicker();
When this is done, you append it to your DOM:
$('.testBox').append($select);
See proof-of-concept example below:
$('select').selectpicker();
$('#add_more').click(function() {
// Create dummy div that houses select element
var $select = $('<div />').append('<select class="show-tick form-control"><option>Safari</option><option>Firefox</option><option>Chrome</option></select>');
// Initialize plugin in <select> element found in document fragment
$select.find('select').selectpicker();
// Append document fragment to your DOM
$('.testBox').append($select);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css">
Add More
<select class="selectpicker show-tick form-control">
<option>Safari</option>
<option>Chrome</option>
<option>Firefox</option>
</select>
<br /><br />
<div class="testBox"></div>

Related

How to add code cells to HTML page with Javascript and Ace.JS?

Is it possible to create several text editor cells within a single page? My desired outcome is to have a button that when clicked allows the user to add new cells of code, where the user can write and later run. Similar to Jupyter notebook. The editor itself is imported from the ace.js library.
For that, I think I need some function add_editor(parent_div) that adds a new text editor to a div that is given as a parameter. ( Which I have failed to implement )
My initial thoughts are perhaps to create a shared class for all of the editors and append it to the father div with jQuery, but when I tried using a class instead of an id for the design,the editor won't load.
I'm not so good with handling with the DOM (especially without React), so even if the solution seems obvious to you, it might not to me.
This is last working version of the code that I have so far
<html lang="en">
<head>
<title>ACE in Action</title>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Define the editor's CSS !-->
<style type="text/css" media="screen">
#editor {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div class="row">
<!-- a row of two columns: the first will contain the text editors, the second is irrelevant !-->
<div class="col-9" style="height:200px;">
<div class="container" style="">
<div id="editor">
<!-- the div containing the code, has the id "editor" !-->
def print_something():
print(a)
</div>
</div>
</div>
<div class="col-3">
empty column
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.5/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
function configure_editor(){
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/python");
editor.getSession().setUseWrapMode(true);
editor.setShowPrintMargin(false);
}
configure_editor()
</script>
</body>
</html>
Help will be much appreciated!
Edit: I need to solve this in Javascript or Jquery, without React.
A cleaner method is to assign an editor to each instance using your own structure. With jquery:
<div id="instance0"></div><div id="instance1"></div>
<script>
var instances[];
var $rootElement = $('#instance0');
newInstance($rootElement);
var $rootElement = $('#instance1');
newInstance($rootElememt);
function newInstance($rootElement){
var instance = {};
instance.id = $rootElement.attr('id');
instance.$root = $rootElement;
instance.editor = ace.edit($rootElement[0]);
instance.editor.instance = instance;
instances.push(instance);
}
</script>
This gives you a 1 to 1 instance to editor relationship with backpointers. It will save you much angst in the future. You can just flip in sessions and keep the editors static.
I think I have found somewhat of a solution on my own with jQuery, even though it seems messy.
Each time a new editor will be added with increasing ids, i.e : "editor0", "editor1", "editor2", and so on.
Here is the full code
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>ACE in Action</title>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- Define the editor's CSS !-->
</head>
<body>
<div class="row">
<!-- a row of two columns: the first will contain the text editors, the second is irrelevant !-->
<div class="col-9" style="height:200px;">
<div id="editors_container">
</div>
</div>
<div class="col-3">
<button id="add_editor">Add a new editor</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.5/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
existing_editors = [];
$(document).ready(function(){
$("#add_editor").click(function(){
console.log("reached here!")
let editor_id = "editor"+existing_editors.length;
$newDiv = $("<div id="+editor_id+" style=width:100%;height:100%>"+"</div>");
$("#editors_container").append($newDiv);
let editor = ace.edit(editor_id);
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/python");
editor.getSession().setUseWrapMode(true);
editor.setShowPrintMargin(false);
existing_editors.push(editor);
});
});
</script>
</body>
</html>

Selecting options in selectPicker for sessionStorage

So I created a mock up of my problem. I am using Select Picker to create my multi-select drop-down. On page reload I want to save the options selected via sessionStorage.
My session Storage works successfully. It grabs the value of my options and stores them on my browser, however it won't be displayed visually to the user.
Is there a way to select the options in the drop-down menu using Javascript/jquery?
Also worth mentioning my logic might seem overkill, but I am using $(this) to grab each name attribute because I will be using this on multiple forms.
Thanks!
jsfiddle : https://jsfiddle.net/7Lhwbzs2/3/
<!--Importing CSS stylesheets-->
<link rel="stylesheet" type="text/css"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"/>
<!--Importing Javascript-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"
integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg=="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js"></script>
<div>
<select class="selectpicker" name="Food" data-none-selected-text="Select Option(s)..." multiple>
<option value="Pizza">Pizza</option>
<option value="Wings">Wings</option>
<option value="Veggies">Veggies</option>
<option value="Rice">Rice</option>
<option value="Pasta">Pasta</option>
</select>
</div>
<script>
$('select').selectpicker({
actionsBox: true,
});
$('select').each(function( index ) {
var previousSelection = window.sessionStorage.getItem(`${$(this).attr('name')}`) ? JSON.parse(window.sessionStorage.getItem(`${$(this).attr('name')}`)): [];
console.log(previousSelection)
});
$('select').on("change", function (e){
window.sessionStorage.setItem(`${$(this).attr('name')}`, JSON.stringify($(this).val()) );
});
</script>
You can just use selectpicker like this:
$('.selectpicker').selectpicker('val', previousSelection);
Just replace your javaScript code with this. I tested it and it works just fine:
var previousSelection
$('select').selectpicker({
actionsBox: true,
});
$('select').each(function( index ) {
previousSelection =
window.sessionStorage.getItem(`${$(this).attr('name')}`) ?
JSON.parse(window.sessionStorage.getItem(`${$(this).attr('name')}`)): [];
console.log(previousSelection)
});
$('select').on("change", function (e){
window.sessionStorage.setItem(`${$(this).attr('name')}`,
JSON.stringify($(this).val()) );
});
$('.selectpicker').selectpicker('val', previousSelection);

Cloning bootstrap datepicker with JavaScript

I am trying to duplicate my bootstrap datepicker, but it's not working properly.
The datepicker is inside a div and I duplicate the whole div. It works fine, but the datepicker is only working in the original div, not the cloned ones.
I've seen on stackoverflow that you can put a class instead of an Id, but that is not working either.
$('.calendar').datepicker({
format: 'dd/mm/yyyy',
todayHighlight: true,
autoclose: true,
});
function duplicate() {
var i = document.getElementById('duplicater');
var d = document.createElement('div');
d.id = "new";
d.innerHTML = i.innerHTML;
var p = document.getElementById('dynamicInput');
p.appendChild(d);
}
duplicate();
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" integrity="sha256-I/m6FhcACNYmRoqn1xUnizh6S7jOJsTq+aiJ6BtE2LE=" crossorigin="anonymous" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.js" integrity="sha256-7Ls/OujunW6k7kudzvNDAt82EKc/TPTfyKxIE5YkBzg=" crossorigin="anonymous"></script>
<div id="dynamicInput" class="col-md-12">
<div id="duplicater">
<div class="row">
<div class="field-wrap3 col-sm-12 col-md-4">
<input type="text" placeholder="Event Title" name="event_title[]">
</div>
<div class="field-wrap3 col-sm-12 col-md-4">
<input type="text" placeholder="Background Image (URL)" name="img_url[]">
</div>
<div class="field-wrap3 col-sm-12 col-md-4">
<input name="date" placeholder="Date" type="text" class="calendar" />
</div>
</div>
<div class="row">
<div class="description-create" class="col-md-8">
<input type="text" placeholder="Description" name="description[]">
</div>
</div>
</div>
</div>
I don't get why it's not working. My JavaScript selects all the elements with the class calendar and "gives" it a datepicker, does it not?
If I understand your problem give same class name of your second input field as your original and initialize datepicker with same class name, you don't need to duplicate whole code.
For example if you want to initialize datetimepicker in two textbox just give them same name as in example that follows in snippet.
$( function() {
$( ".calendar" ).datepicker();
} );
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.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>
<input name="date" placeholder="Date" type="text" class="calendar"/>
<input name="date1" placeholder="Date1" type="text" class="calendar"/>
The order of operations that you are using is:
html is on page
you are telling datepicker to enable the existing instances of .calendar
you are copying the div which creates html that the previous call didn't know about, so nothing attaches to it
The copy is making a copy of the html, it is not creating a new instance of datepicker. If at the end of your copy you called $('.calendar').datepicker('destroy'); you could follow that by your existing call to:
$('.calendar').datepicker({
format: 'dd/mm/yyyy',
todayHighlight: true,
autoclose: true,
});
which would have the effect of:
html is on page
datepicker is attached to all existing instances of .calendar
duplicate is called
duplicate copies the html
and removes all instances of .calendar
and then reattaches to make sure it gets the original and the new instances of calendar
alternatively you could scope your call for attaching datepicker so that you attach it only to the newly created html.

MVC rating Bootstrap Jquery unselect stars selected

I am doing an MVC Application with Rating Bootstrap.
<input id="input-21b" type="number" class="rating" data-show-clear="false" data-show-caption="false" min=0 max=5 step=1 data-glyphicon="false" data-size="sm">
I have also define this...in order to know how many start has been clicked.
$(document).ready(function () {
$("#input-21b").on("rating.change", function (event, value, caption) {
$('#hdfRatingValue').val(value);
});
I have a hidden input to keep the starts selected.
It Works fine...
When User clicks "OK" buttom, a Ajax function is called to save the rating.
What I need is to UnSelect the starts selected via Jquery....
I have try
$('#input-21b').rating({
'update': 0,
'showCaption': false,
'showClear': false
});
Ais it says is Bootstrap-star-rating set default stars
But Nothing happend. I also Include
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- required libraries -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-star-rating/4.0.1/css/star-rating.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-star-rating/4.0.1/js/star-rating.min.js"></script>
Still nothing happend.
Is that Posible?
Thanks
I tried But Nothing happend:
$('#input-21b').rating({
'update': 0,
'showCaption': false,
'showClear': false
});
update is a method and you cannot use it at initialization. Moreover, you don't need initialization because you specified all attributes in the HTML.
If you want to use that method you must write:
$('#input-21b').rating('update', 0).trigger('rating.change');
But you can also directly reset the rating to its initial value:
$('#input-21b').rating('reset').trigger('rating.change');
Why do you need to trigger the event rating.change? Because in this way you can execute your related event handler (i.e.: copy the value to your hidden field).
$(document).ready(function () {
$("#input-21b").on("rating.change", function (event, value, caption) {
$('#hdfRatingValue').val(value);
});
$('button').on('click', function(e) {
//$('#input-21b').rating('update', 0).trigger('rating.change');
$('#input-21b').rating('reset').trigger('rating.change');
})
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- required libraries -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-star-rating/4.0.1/css/star-rating.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-star-rating/4.0.1/js/star-rating.min.js"></script>
<div class="container">
<form>
<div class="form-group">
<label for="input-21b">Rating:</label>
<input id="input-21b" type="number" class="rating" data-show-clear="false" data-show-caption="false"
min=0 max=5 step=1 data-glyphicon="false" data-size="sm">
</div>
<div class="form-group">
<label for="input-21b">Rating Value:</label>
<input id="hdfRatingValue" type="text">
</div>
<button type="button" class="btn btn-primary">Reset rating</button>
</form>
</div>

How to change parent container of dropdown list in select2

I have form, which contain a few selects. For the latter I used plugin select2.
In exemple below you can see, that pull-down menu of select situated in the root of document - in the body.
Can I change location of dropdown list and how to do this?
UPD: probably my question is not fairly accurate. I'm asking, how to put dropdown list in commun container with select block?
$(document).ready(function() {
$(".js-example-basic-single").select2({
minimumResultsForSearch: Infinity
})
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<div class="wrapper">
<select class="js-example-basic-single" style="width: 200px;">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
</div>
I don´t know if is available on the select2 version you are using, but you can use this:
$('select').select2({
dropdownParent: $('#my_amazing_modal')
});
Source https://select2.github.io/options.html#dropdownParent
This would work
$("#selectInput").select2({ dropdownParent: "#modal-container" });
Please note that this would work on select2 version 4.0.2. For higher versions see other answers.
Reference: https://github.com/select2/select2-bootstrap-theme/issues/41
The location of your dropdown list is determined by your HTML and CSS layout. It depends on where you put the div in your example and how it is styled. See my example below which shows the dropdown list moved to the right of a yellow box.
$(document).ready(function() {
$(".js-example-basic-single").select2({
minimumResultsForSearch: Infinity
})
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<div style="width:100%;height:100%;position:relative;">
<div style="height:100px;width:100px;background-color:yellow;float:left;"></div>
<div style="float:left;" class="wrapper">
<select class="js-example-basic-single" style="width: 200px;">
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
</div>
</div>

Categories