bootstrap selectpicker and cloning - bootstrap-select

I have been using bootstrap selectpicker where I've added an Add Button for user to replicate the button as much as he wants. Problem is, selectpicker is not working on the second / cloned element and values of dropdown are just showing and not changing on click.
Main Select:
<div id="main_product">
<select name="product[]" class="selectpicker" >
<option value="Tube Lights" >Tube Lights</option>
<option value="Downlights" >Downlights</option>
</select>
</div>
Clone Function:
function clone()
{
var $orginal = $('#main_product');
var $cloned = $orginal.clone();
$cloned.appendTo('#new_products');
// $cloned.find('.bootstrap-select').remove();
// $cloned.find('select').selectpicker();
}
Note that I tried to reassign the selectpicker to the cloned object which is in comments atm, because it dint work also.
Any help would be really appreciated.

I came across this problem but if using the latest version now the select is placed inside the .bootstrap-select element for html5 error handling purposes. The remove() also removes the select, a work around is:
Instead of:
$cloned.find('.bootstrap-select').remove();
Use:
$cloned.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
This will replace the .bootstrap-select element with the select element that it contains inside.

function clone()
{
//you can use :
var $orginal = $('#main_product');
var $cloned = $orginal.clone();
//Or
var $cloned = $('#main_product').clone();
//then use this to solve duplication problem
$cloned.find('.bootstrap-select').replaceWith(function() { return $('select', this); })
$cloned .find('.selectpicker').selectpicker('render');
//Then Append
$cloned.appendTo('#new_products');
}

if we replace the bootstrap-select with the select then the problem is in HTML structure.
so, original element is actual bootstrap-select and cloned are normal select.
take look at following for more clarification.
instead of this
$cloned.find('.bootstrap-select').replaceWith(function() { return $('select', this); });
use
$cloned.selectpicker('refresh');
$cloned.find('.bootstrap-select:odd').remove();

You can please change clone function
function clone() {
var $orginal = $('#main_product');
var $cloned = $orginal.clone();
var $selectPicker = $cloned.find('select');
$cloned
.find('.bootstrap-select').remove().end()
.append($selectPicker).end();
$cloned.find('select').selectpicker();
$cloned.appendTo('#new_products');
}

When using in Form Sets along with other form fields you need to replace and render all the selectpicker mentioned by #cm_mehdi. First find the new form html element and apply the below code:
//Clone new form
let newForm = purchaseForm[0].cloneNode(true);
// Replace and render the cloned html selectpicker
$(newForm).find('.bootstrap-select').replaceWith(function() { return $('select', this); })
$(newForm).find('.selectpicker').selectpicker('render');
// Re-Initialize search in dropdown
$(`#id_form_formfield-${formNum}`).selectpicker({liveSearch: true});

Related

Convert Quill Delta to HTML

How do I convert Deltas to pure HTML? I'm using Quill as a rich text editor, but I'm not sure how I would display the existing Deltas in a HTML context. Creating multiple Quill instances wouldn't be reasonable, but I couldn't come up with anything better yet.
I did my research, and I didn't find any way to do this.
Not very elegant, but this is how I had to do it.
function quillGetHTML(inputDelta) {
var tempCont = document.createElement("div");
(new Quill(tempCont)).setContents(inputDelta);
return tempCont.getElementsByClassName("ql-editor")[0].innerHTML;
}
Obviously this needs quill.js.
I guess you want the HTML inside it. Its fairly simple.
quill.root.innerHTML
If I've understood you correctly, there's a quill thread of discussion here, with the key information you're after.
I've quoted what should be of most value to you below:
Quill has always used Deltas as a more consistent and easier to use (no parsing)
data structure. There's no reason for Quill to reimplement DOM APIs in
addition to this. quill.root.innerHTML or document.querySelector(".ql-editor").innerHTML works just fine (quill.container.firstChild.innerHTML is a bit more brittle as it depends on child ordering) and the previous getHTML implementation did little more than this.
Simple, solution is here:
https://www.scalablepath.com/blog/using-quill-js-build-wysiwyg-editor-website/
The main code is:
console.log(quill.root.innerHTML);
This is a very common confusion when it comes to Quilljs. The thing is you should NOT retrieve your html just to display it. You should render and display your Quill container just the same way you do when it is an editor. This is one of the major advantages to Quilljs and the ONLY thing you need to do is:
$conf.readOnly = true;
This will remove the toolbar and make the content not editable.
I have accomplished it in the backend using php.
My input is json encoded delta and my output is the html string.
here is the code , if it is of any help to you.This function is still to handle lists though and some other formats but you can always extend those in operate function.
function formatAnswer($answer){
$formattedAnswer = '';
$answer = json_decode($answer,true);
foreach($answer['ops'] as $key=>$element){
if(empty($element['insert']['image'])){
$result = $element['insert'];
if(!empty($element['attributes'])){
foreach($element['attributes'] as $key=>$attribute){
$result = operate($result,$key,$attribute);
}
}
}else{
$image = $element['insert']['image'];
// if you are getting the image as url
if(strpos($image,'http://') !== false || strpos($image,'https://') !== false){
$result = "<img src='".$image."' />";
}else{
//if the image is uploaded
//saving the image somewhere and replacing it with its url
$imageUrl = getImageUrl($image);
$result = "<img src='".$imageUrl."' />";
}
}
$formattedAnswer = $formattedAnswer.$result;
}
return nl2br($formattedAnswer);
}
function operate($text,$ops,$attribute){
$operatedText = null;
switch($ops){
case 'bold':
$operatedText = '<strong>'.$text.'</strong>';
break;
case 'italic':
$operatedText = '<i>'.$text.'</i>';
break;
case 'strike':
$operatedText = '<s>'.$text.'</s>';
break;
case 'underline':
$operatedText = '<u>'.$text.'</u>';
break;
case 'link':
$operatedText = ''.$text.'';
break;
default:
$operatedText = $text;
}
return $operatedText;
}
Here's a full function using quill.root.innerHTML, as the others didn't quite cover the complete usage of it:
function quillGetHTML(inputDelta) {
var tempQuill=new Quill(document.createElement("div"));
tempQuill.setContents(inputDelta);
return tempQuill.root.innerHTML;
}
This is just a slight different variation of km6 's answer.
For Quill version 1.3.6, just use:
quill.root.innerHTML;
Try it online: https://jsfiddle.net/Imabot/86dtuhap/
Detailed explaination on my blog
This link if you have to post the Quill HTML content in a form
quill.root.innerHTML on the quill object works perfectly.
$scope.setTerm = function (form) {
var contents = JSON.stringify(quill.root.innerHTML)
$("#note").val(contents)
$scope.main.submitFrm(form)
}
I put together a node package to convert html or plain text to and from a Quill Delta.
My team used it to update our data model to include both Quill's Delta and HTML. This allows us to render on the client without an instance of Quill.
See node-quill-converter.
It features the following functions:
- convertTextToDelta
- convertHtmlToDelta
- convertDeltaToHtml
Behind the scenes it uses an instance of JSDOM. This may make it best suited for migration scripts as performance has not been tested in a typical app request lifecycle.
Try
console.log ( $('.ql-editor').html() );
Here is how I did it, for you Express folks. It seems to have worked very well in conjunction with express-sanitizer.
app.js
import expressSanitizer from 'express-sanitizer'
app.use(expressSanitizer())
app.post('/route', async (req, res) => {
const title = req.body.article.title
const content = req.sanitize(req.body.article.content)
// Do stuff with content
})
new.ejs
<head>
<link href="https://cdn.quilljs.com/1.3.2/quill.snow.css" rel="stylesheet">
</head>
...
<form action="/route" method="POST">
<input type="text" name="article[title]" placeholder="Enter Title">
<div id="editor"></div>
<input type="submit" onclick="return quillContents()" />
</form>
...
<script src="https://cdn.quilljs.com/1.3.2/quill.js"></script>
<script>
const quill = new Quill('#editor', {
theme: 'snow'
})
const quillContents = () => {
const form = document.forms[0]
const editor = document.createElement('input')
editor.type = 'hidden'
editor.name = 'article[content]'
editor.value = document.querySelector('.ql-editor').innerHTML
form.appendChild(editor)
return form.submit()
}
</script>
express-sanitizer (https://www.npmjs.com/package/express-sanitizer)
document.forms (https://developer.mozilla.org/en-US/docs/Web/API/Document/forms)
My view only has one form, so I used document.forms[0], but if you have multiple or may extend your view in the future to have multiple forms, check out the MDN reference.
What we are doing here is creating a hidden form input that we assign the contents of the Quill Div, and then we bootleg the form submit and pass it through our function to finish it off.
Now, to test it, make a post with <script>alert()</script> in it, and you won't have to worry about injection exploits.
That's all there is to it.
Here is a proper way to do it.
var QuillDeltaToHtmlConverter = require('quill-delta-to-html').QuillDeltaToHtmlConverter;
// TypeScript / ES6:
// import { QuillDeltaToHtmlConverter } from 'quill-delta-to-html';
var deltaOps = [
{insert: "Hello\n"},
{insert: "This is colorful", attributes: {color: '#f00'}}
];
var cfg = {};
var converter = new QuillDeltaToHtmlConverter(deltaOps, cfg);
var html = converter.convert();
Refer https://github.com/nozer/quill-delta-to-html
For a jQuery-style solution that allows getting and setting the Quill value I am doing the following:
Quill.prototype.val = function(newVal) {
if (newVal) {
this.container.querySelector('.ql-editor').innerHTML = newVal;
} else {
return this.container.querySelector('.ql-editor').innerHTML;
}
};
let editor = new Quill( ... );
//set the value
editor.val('<h3>My new editor value</h3>');
//get the value
let theValue = editor.val();
quill-render looks like it's what you want. From the docs:
var render = require('quill-render');
render([
{
"attributes": {
"bold": true
},
"insert": "Hi mom"
}
]);
// => '<b>Hi mom</b>'
If you want to render quill using nodejs, there is a package quite simple based on jsdom, usefull to render backside (only one file & last update 18 days from now) render quill delta to html string on server
Just use this clean library to convert from delta from/to text/html
node-quill-converter
example:
const { convertDeltaToHtml } = require('node-quill-converter');
let html = convertDeltaToHtml(delta);
console.log(html) ; // '<p>hello, <strong>world</strong></p>'

How to get the value of selected row directly in HTML using ag-grid

i try to get the the value of number row selected, and print it in HTML using Angularjs, but no issue,
i have the count only when i clic in the grid column header.
The value of " selectedRowsCounter " is 0 in html, when i dosn't clic in the grid header
my code is like
var activeButtons = function() {
var countRowsSelected = $scope.gridOptions.api.getSelectedRows().length;
$scope.selectedRowsCounter = countRowsSelected;
console.log($scope.selectedRowsCounter);
$rootScope.count.selectedRows = countRowsSelected;
};
$scope.gridOptions = {
rowData: null,
angularCompileRows: true,
onSelectionChanged: activeButtons,
}
there is a screenshot
i have open the same subject here
https://github.com/ceolter/ag-grid/issues/1023
i have added this line to activeButtons function and it work fine
$scope.gridOptions.api.refreshView();
i dont knew if there is a good solution, but that work for now
The problem seems to be with Angular being unaware of the $scope property change because ag-grid does not tell Angular that it has modified something in the $scope. Although it is difficult to tell if you don't show your view.
You can use onSelectionChanged the way you are using it to know how many rows have been selected, but you need to tell Angular that something has changed in its $scope by applying it.
Something like this:
var activeButtons = function() {
var countRowsSelected = $scope.gridOptions.api.getSelectedRows().length;
$scope.selectedRowsCounter = countRowsSelected;
console.log($scope.selectedRowsCounter);
$rootScope.count.selectedRows = countRowsSelected;
window.setTimeout(function() {
this.$scope.$apply();
});
};
That way you can apply the $scope and the html view will reflect the changes.

Null model in select in Angular template

I have a databound <select> element in an angular app. To bind it I am using:
<select id="AllKeyValuePairsInput" size="4" style="width:500px; height: 175px;" ng-options='item.key as (item.key + ": " + item.value) for item in data.availableOptions' ng-model="selected">
</select>
In my controller I have the following code, that according to the Angular documentation should remove that initial dirty model:
$scope.selected = $scope.data.availableOptions[0];
But I still see an empty entry appearing first in the select. I have it up and running in JSFiddle at https://jsfiddle.net/alchiggs/d12tdapv/
I'd be most grateful if anyone could point me in the right direction. One last point, it's the first bit of Angular I've ever written, so please don't hate me!!!! ;-)
This is how loadInitialData should look, note the change in the default value:
$scope.loadInitialData = function() {
var initialData = [{"key":"Maximum length","value":"200mm"},{"key":"Maximum width","value":"5000mm"}]
angular.forEach(initialData, function(object, index) {
$scope.keyValuePairs.push({ key: object.key, value: object.value});
});
$scope.selected = $scope.keyValuePairs[0].key; // THIS IS THE CHANGE I MADE
}
I've set the default value using the key property and not the element itself because your ngOptions define that the value of each option is item.key

How make related selects in Angular?

I have two select list HTML.
How I can make easy them related? I mean when I select option from first select, some options from second select are shown to hidden?
Selects lists HTML created by PHP.
There are a few ways using angular. One way is to use the ng-change:
<select ng-model="selectedItem1" ng-options="item in items1" ng-change="update(selectedItem1)"></select>
and then have the update(selectedItem1) function update your items2 list. And vice versa for your items2 drop down.
$scope.update = function(selectedItem1) {
$scope.items2 = // logic to filter items 2 based on selectedItem1
}
<select ng-model="selectedItem2" ng-options="item in items2" ng-change="updateSet1(selectedItem2)"></select>
Alternatively, you could use a $watch function, to watch selectedItem1 and update items2 list in this function.
If you need to use a custom filter, see here:
https://docs.angularjs.org/tutorial/step_09
angular.module('myModule', []).filter('items2', function() {
return function(selectedItem1, items2) {
for (var i = 0; i < items2.length; i++) {
// return items you want
}
};
});
Then in your controller, include this filter as dependency items2Filter by appending Filter and you can update $scope.items2 like so:
$scope.items2 = items2Filter($scope.selectedItem1, $scope.items2);

Angular JS UI-Grid Delete Row

I'm new to ui-grid and I'm trying to implement a table in AngularJS as shown in the picture below. I'm trying to select a row and delete it using a delete button on that particular row. The ui-grid documentation requires us to use the gridApi but I can't find sufficient documentation for the same.
Please see a working example of how to delete a row here.
http://plnkr.co/edit/6TiFC6plEMJMD4U6QmyS?p=preview
The key is to use indexOf(row.entity) and not relying on row.index as it doesn't dynamically get updated.
$scope.deleteRow = function(row) {
var index = $scope.gridOptions.data.indexOf(row.entity);
$scope.gridOptions.data.splice(index, 1);
};
Generic approach
function deleteRow(row,grid) {
var i = grid.options.data.indexOf(row.entity);
grid.options.data.splice(i, 1);
}
You can use #Blousie solution as far as you adapt it to the newer API: https://github.com/angular-ui/ng-grid/blob/master/3.0_UPGRADE.md
Now "grid.appScope.edit(row.entity)" gives you access to your scope's "edit" function.
Something like this:
var removeTemplate = '<button class="btn btn-danger" ng-click="grid.appScope.removeRow(row)"><i class="glyphicon glyphicon-remove"></i></button>';
$scope.removeRow = function(row) {
var index = $scope.<yourDataModelProperty>.indexOf(row.entity);
if (index !== -1) {
$scope.<yourDataModelProperty>.splice(index, 1);
}
};
We need to use the $scope.grid.appScope. It is available in all templates. Besides that, you need to send the row object from the template, so that you can delete the row from the grid data.
jsfiddle: http://jsfiddle.net/3ryLqa9e/4/
cellTemplate:'<button class="btn primary" ng-click="grid.appScope.Delete(row)">Delete Me</button>'
$scope.Delete = function(row) {
var index = $scope.gridOptions.data.indexOf(row.entity);
$scope.gridOptions.data.splice(index, 1);
};
The other solutions provided here didn't worked for me(May be because of my latest different version of ui-grid). So removing element from the scope array worked for me. This should even work with other versions of ui-grid because grid must be updated when the data changes. (Thanks to Angular!!!)
I am using lodash to remove element from array and here is sample code:
$scope.deleteRow = function(row){
_.remove($scope.gridData, {
id: row.id
});
};
Just remove the row you want to delete from ui-grids data source model using splice.
For example
$scope.myGridOptions.data.splice(<YOUR ROW INDEX HERE>, 1);

Resources