Add a button to Select2 Dropdown list - jquery-select2

I am using the lastest version of Select2. Want to add an Insert New button at the end of the dropdown list. I tried these two solutions I found online
Solution 1:
$(".select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
Solution 2
$("#itemId0").select2("container").find("div.select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
With Solution 1 nothing happens. With solution 2 I get the error message in the select 2 js file
0x800a138f - JavaScript runtime error: Unable to get property 'apply'
of undefined or null reference
Can anyone please help?
Here is my HTML
<select id='itemId0' name='product[0][name]' class='form-control col-lg-5 itemSearch' >
<option></option>
</select>
AND the full select2 javascritp
function productFormatResult(product) {
if (product.loading) product.text;
var html = "<table><tr>";
html += "<td>";
html += product.text;
html += "</td></tr></table>";
return html;
}
// alert(html);
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='" + product.id + "'/>";
return selected + product.text;
}
//$("#itemId0").select2();
$("#itemId0").select2({
ajax: {
url: "#Url.Action("GetProducts", "Inventories")",
dataType: 'json',
data: function (params) {
return {
q: params.term
};
},
processResults: function (data, params) {
return { results: data };
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: productFormatResult,
templateSelection: productFormatSelection,
dropdownClass: 'bigdrop'
});
// $(".select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');
$("#itemId0").select2("container").find("div.select2-drop").append('<table width="100%"><tr><td class="row"><button class="btn btn-block btn-default btn-xs" onClick="modal()">Add new Item</button></div></td></tr></table>');

check it
$('#select2').select2({
placeholder: 'This is my placeholder',
language: {
noResults: function() {
return `<button style="width: 100%" type="button"
class="btn btn-primary"
onClick='task()'>+ Add New Item</button>
</li>`;
}
},
escapeMarkup: function (markup) {
return markup;
}
});
Update: (Explanation)
If you need to add button in select2 if no result found you just need to returnHTML Button code from noResults function and Add escapeMarkup function to render custom templates.
language: {
noResults: function() {
return `<button style="width: 100%" type="button"
class="btn btn-primary"
onClick='task()'>+ Add New Item</button>
</li>`;
}
},
escapeMarkup: function (markup) {
return markup;
}
Try below example to see how it looks.
https://jsfiddle.net/Hamza_T/yshjqw85/32/

Here is an example in codepen
html is below
<select id="CustomSelect" multiple="multiple">
<option value="volvo">BMW</option>
<option value="saab">Jaquar</option>
<option value="mercedes">RR</option>
<option value="audi">Audi</option>
</select>
CSS is below
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#banner-message {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
Script is below
$("#CustomSelect").select2({
width: '100%',
allowClear: true,
closeOnSelect: false
}).on('select2:open', function () {
let a = $(this).data('select2');
if (!$('.select2-link').length) {
a.$results.parents('.select2-results')
.append('<div class="select2-link2 select2-close"><button>Close</button></div>')
.on('click', function (b) {
});
}
});

I think this can be done with Select2's Adapters and Decorators (https://select2.org/advanced/default-adapters). However, personally I find this approach really heavy and to be honest I don't understand the documentation regarding this area.
What I personally do, is binding on the select2:open-event and appending a add-new-button container.
Here is an example:
// create new container
$('#select2').select2CreateNew("Create new");
// generic function
$.fn.select2CreateNew = function( text ) {
// bind to "open"-event
this.on( 'select2:open', function( e ) {
let name = $( this ).attr( 'name' );
let html = '<div class="s-add-new-container">' + text + '</div>';
let $resultContainer = $( '[aria-controls="select2-' + name + '-results"]' )
.closest( '.select2-dropdown' ).find( '.select2-results' );
// avoid duplicates ~ append "create new" to result bottom
if ( $resultContainer.find( '.s-add-new-container' ).length === 0 ) $resultContainer.append( html );
} );
}
Customize the code or add some click-event handler for whenever the user clicks on the container.
For styling I'm using this CSS:
.s-add-new-container {
padding: 7px;
background: #f1f1f1;
border-top: 1px solid #c7c7c7;
}
.select2-dropdown.select2-dropdown--below {
border-radius: 0px;
box-shadow: 0px 5px 10px #6b6b6b59;
}
.s-add-new-container:hover {
background: #3db470;
color: white;
cursor: pointer;
}

Related

Why does my CSS code renders incorrectly on iOS/MacOS?

We developed a web app on Vue 3 and it displays perfectly on every browser except on iOS and Mac OS devices.
This is worse if you're using Safari, however some issues occur even on Chrome for Mac.
This problem causes forms to always be shown blank, without displaying a placeholder or user input. It also makes several other elements to misalign.
We even tried making a new form and removing all stylesheets, but the problem persists.
Here is the code for one of the forms:
<template>
<div>
<form class="contactus" #submit.prevent="saveMessage">
<div class="row">
<h1 class="titleFormAbout">
{{ $t("contactus.componentForm.text1") }}
</h1>
</div>
<p style="margin-bottom: 30px;">{{ $t("contactus.componentForm.text9") }}</p>
<input type="text" class="form-control formContact" :placeholder="$t('contactus.componentForm.text2')" id="name" required />
<input type="email" class="form-control formContact" :placeholder="$t('contactus.componentForm.text3')" id="email" required />
<vue-tel-input
v-model="phone"
id="phone"
class="formControl formContact"
></vue-tel-input>
<br />
<textarea
class="form-control formContact"
name=""
id="message"
rows="10"
:placeholder="$t('contactus.componentForm.text5')"
required
></textarea>
<br />
<vue-recaptcha
style="margin-bottom: 14px"
#validate="validated"
/>
<div class="row">
<div class="col-6">
<input
class="form-control "
type="Submit"
id="submitButton"
:value="$t('contactus.componentForm.text6')"
disabled
/>
</div>
<div class="col-6">
<button class="form-control clear" #click="clearForm" >
{{ $t("contactus.buttonClear") }}
</button>
</div>
</div>
<br />
<div class="alert" id="Response" role="alert"></div>
</form>
</div>
</template>
<script>
import axios from "axios";
import VueRecaptcha from "../forms/vue-recaptcha.vue";
const hostName = location.port =="" ?location.protocol + "//" + location.host:'http://'+location.hostname+':3000';
export default {
components: {
VueRecaptcha,
},
data() {
return {
config: {
headers: {
//'Content-Type': 'application/x-www-form-urlencoded'
"Content-Type": "multipart/form-data",
},
},
};
},
methods: {
validated(){
const htmlElement=document.getElementById('submitButton');
htmlElement.classList.add('submit');
htmlElement.disabled=false;
},
clearForm() {
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementsByName("telephone")[0].value = "";
document.getElementById("message").value= "";
},
saveMessage() {
//alert(document.getElementsByClassName("highlighted")[0].getElementsByTagName('span')[0].innerHTML)
const responseBox = document.getElementById("Response");
const params = new FormData();
const countryPhone = document.getElementsByClassName("highlighted");
var countryPhoneid = "+52";
if (countryPhone.length > 0) {
countryPhoneid =
countryPhone[0].getElementsByTagName("span")[0].innerHTML;
}
params.append("name", document.getElementById("name").value);
params.append("email", document.getElementById("email").value);
params.append("phone",countryPhoneid + " " + document.getElementsByName("telephone")[0].value);
params.append("message", document.getElementById("message").value);
axios
.post(hostName + "/api/contact", params, this.config)
.then((response) => {
responseBox.innerHTML = this.$t("contactus.componentForm.text7");
responseBox.classList.add("alert-success");
setTimeout(() => {
responseBox.classList.remove("alert-success");
}, 5000);
console.log(response);
})
.catch((err) => {
responseBox.innerHTML = this.$t("contactus.componentForm.text8");
responseBox.classList.add("alert-danger");
setTimeout(() => {
responseBox.classList.remove("alert-danger");
}, 5000);
console.log(err);
});
responseBox.hidden = false;
setTimeout(() => {
responseBox.hidden = true;
}, 5000);
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementsByName("telephone")[0].value = "";
document.getElementById("message").value = "";
},
},
mounted() {
document.getElementsByName("telephone")[0].placeholder=this.$t('contactus.componentForm.text10');
const listcountry = document.getElementsByClassName("vti__dropdown-list");
listcountry[0].getElementsByTagName("li")[137].classList.add("highlighted");
document.getElementsByName("telephone")[0].required = true;
document
.getElementsByName("telephone")[0]
.addEventListener("input", (textin) => {
const telephone = document.getElementsByName("telephone")[0];
//console.log(parseInt(textin.data));
//console.log(Number.isInteger(textin.data));<
if (Number.isInteger(parseInt(textin.data))) {
// console.log(telephone.value);
} else {
telephone.value = telephone.value.slice(
0,
telephone.value.length - 1
);
}
});
},
};
</script>
<style>
.contactus .submit {
background: #008b9e;
color: white;
font-weight: bold;
}
.contactus .formContact{
border: 2px solid #BAD1FF;
margin-top: 2vh;
margin-bottom: 2vh;
}
.contactus .clear {
background: rgba(0, 0, 0, 0.25);
font-weight: bold;
}
.contactus .titleFormAbout {
margin-top: 20px;
margin-bottom: 20px;
text-align: left;
color: #00a8c6;
font-weight: bolder;
margin-left: 12px;
text-transform: none;
}
form.contactus {
padding-left: 5vw;
padding-right: 5vw;
}
.contactus form li {
color: black;
}
.contactus .alet {
text-align: center;
}
.contactus .contactus p{
text-align: justify;
}
</style>
Here you can see the type of behaviour we're getting:
On iOS/MacOS:
The same elements on Windows/Android devices:
Can anyone please tell me if this is a common issue and if there's a solution? We have been stuck with this problem for two weeks and we're losing our minds.
Thanks.

Floating Label not working on jquery mobile 1.4.4

I am trying to make a floating label float when you click the input. I am using CSS and jquery(This is in a jquery mobile 1.4.4 platform). My code only seems to work on an input with a data-role of "none," and it won't work on a normal input. How can I make this work on a normal input?
This is my CSS:
.inputAnimation {
display: inline-block;
position: relative;
margin: 0 0px 0 0;
}
.inputAnimation label {
position: absolute;
top: 5px;
left: 15px;
font-size: 12px;
color: #aaa;
transition: .1s all linear;
cursor: text;
}
.inputAnimation.active label {
top: -15px;
}
This is my HTML:
<div data-role="page" id="signUpPage">
<div data-role="main" class="ui-content">
<form>
<div class="inputAnimation">
<label for="username">Name</label>
<input id="username" name="username" type="text" />
</div>
<div class="inputAnimation">
<label for="email">Email</label>
<input data-role="none" id="email" name="email" type="text" />
</div>
</form>
</div>
And this is my jquery
$(document).ready(function () {
$('input').each(function () {
$(this).on('focus', function () {
$(this).parent('.inputAnimation').addClass('active');
});
$(this).on('blur', function () {
if ($(this).val().length == 0) {
$(this).parent('.inputAnimation').removeClass('active');
}
});
if ($(this).val() != '') $(this).parent('.inputAnimation').addClass('active');
});
});
Here is the demo
Link to the jsfiddle
Thanks!
When jQM enhances the input it adds a DIV such that .inputAnimation is now a grandparent of the input instead of parent. The simplest change is to use the .parents() instead of .parent() method:
$('input').each(function () {
$(this).on('focus', function () {
$(this).parents('.inputAnimation').addClass('active');
});
$(this).on('blur', function () {
if ($(this).val().length == 0) {
$(this).parents('.inputAnimation').removeClass('active');
}
});
if ($(this).val() != '') $(this).parents('.inputAnimation').addClass('active');
});
Updated FIDDLE

Bootstrap 3 column class interfering with jquery-ui droppable div

I'm using jQuery-UI v1.11.2 in order to create some draggable and droppable divs, and Boostrap 3.1.1 as well.
I'd like to know why a Boostrap column class is interfering with the draggable "hint".
In other words, as I drag an image from my Gallery div to my Dashboard div, the Dashboard div comes in FRONT of the image hint. Then once I DROP my image on the Dashboard div, the image re-appears.
If I remove the col-md-8 class from the Dashboard div, this problem goes away.
Here are two screen shots to demonstrate:
1) WITHOUT the Bootstrap column class on the right div (image hint looks good)
2) With the Bootstrap column class on the right div (image hint disappears)
Here's the HTML code :
<section id="gadgets-view" class="mainbar" data-ng-controller="gadgets">
<div class="container-fluid">
<div class="row-fluid">
<!-- based on http://jqueryui.com/droppable/#photo-manager -->
<div class="ui-widget ui-helper-clearfix col-md-4"> <-- GALLERY OF WIDGETS -->
<ul id="gallery" class="gallery ui-helper-reset ui-helper-clearfix">
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header">Tree Grid</h5>
<img src="images/treegrid.jpg" alt="Hierarchy Grid" width="96" height="72">
</li>
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header">Area Chart</h5>
<img src="images/chart_area.jpg" alt="Area Chart" width="96" height="72">
</li>
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header">Bar Chart</h5>
<img src="images/chart_bar.png" alt="Bar Chart" width="96" height="72">
</li>
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header">Column Chart</h5>
<img src="images/chart_column.png" alt="Column Chart" width="96" height="72">
</li>
<li class="ui-widget-content ui-corner-tr">
<h5 class="ui-widget-header">Line Chart</h5>
<img src="images/chart_line.png" alt="Line Chart" width="96" height="72">
</li>
</ul>
</div>
<div class="col-md-8">
<div id="dashboard" class="ui-widget-content ui-state-default "> <-- DROPPABLE DASHBOARD -->
<h4 class=""><span class="ui-icon ui-icon-image"></span>Dashboard</h4>
</div>
<div>
</div>
</div>
</section>
The CSS :
<style>
.ui-widget-header{
font-size: 65%;
font-family: "Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
}
.ui-state-highlight {
border: 2px dashed #d3d3d3; /* override to show dashed border when dragging */
}
#gallery {
float: left;
width: 75%;
min-height: 12em;
}
.gallery.custom-state-active {
background: #eee;
}
.gallery li {
list-style: none;
float: left;
width: 96px;
padding: 0.4em;
margin: 0 0.4em 0.4em 0;
text-align: center;
}
.gallery li h5 {
margin: 0 0 0.4em;
cursor: move;
}
.gallery li a {
float: right;
}
.gallery li a.ui-icon-zoomin {
float: left;
}
.gallery li img {
width: 100%;
cursor: move;
}
#dashboard {
float: left;
width: 45%;
height:500px;
padding: 1%;
}
#dashboard h4 {
line-height: 25px;
margin: 0 0 0.4em;
}
#dashboard h4 .ui-icon {
float: left;
}
#dashboard .gallery h5 {
display: none;
}
The JavaScript to create drag/drop areas :
<script>
$(function () {
// there's the gallery and the dashboard
var $gallery = $("#gallery"),
$dashboard = $("#dashboard");
// let the gallery items be draggable
$("li", $gallery).draggable({
cancel: "a.ui-icon", // clicking an icon won't initiate dragging
revert: "invalid", // when not dropped, the item will revert back to its initial position
containment: "document",
helper: "clone",
cursor: "move"
});
// let the dashboard be droppable, accepting the gallery items
$dashboard.droppable({
accept: "#gallery > li",
activeClass: "ui-state-highlight",
drop: function (event, ui) {
debugger;
deleteImage(ui.draggable);
}
});
// let the gallery be droppable as well, accepting items from the dashboard
$gallery.droppable({
accept: "#dashboard li",
activeClass: "custom-state-active",
drop: function (event, ui) {
recycleImage(ui.draggable);
}
});
// image deletion function
var recycle_icon = "<a href='link/to/recycle/script/when/we/have/js/off' title='Remove gadget' class='ui-icon ui-icon-minus'></a>";
function deleteImage($item) {
$item.fadeOut(function () {
var $list = $("ul", $dashboard).length ?
$("ul", $dashboard) :
$("<ul class='gallery ui-helper-reset'/>").appendTo($dashboard);
//$item.find("a.ui-icon-dashboard").remove(); // DO NOT REMOVE ORIGINAL WIDGET ICON - 11/19/2014 BM:
$item.append(recycle_icon).appendTo($list).fadeIn(function () {
//$item.animate({ width: "48px" }).find("img").animate({ height: "36px" });
$item.animate().find("img").animate();
});
});
}
// image recycle function
var dashboard_icon = "<a href='link/to/dashboard/script/when/we/have/js/off' title='Add this gadget' class='ui-icon ui-icon-plus'</a>";
function recycleImage($item) {
$item.fadeOut(function () {
$item
.find("a.ui-icon-refresh")
.remove()
.end()
.css("width", "96px")
.append(dashboard_icon)
.find("img")
.css("height", "72px")
.end()
.appendTo($gallery)
.fadeIn();
});
}
// image preview function, demonstrating the ui.dialog used as a modal window
function viewLargerImage($link) {
var src = $link.attr("href"),
title = $link.siblings("img").attr("alt"),
$modal = $("img[src$='" + src + "']");
if ($modal.length) {
$modal.dialog("open");
} else {
var img = $("<img alt='" + title + "' width='384' height='288' style='display: none; padding: 8px;' />")
.attr("src", src).appendTo("body");
setTimeout(function () {
img.dialog({
title: title,
width: 400,
modal: true
});
}, 1);
}
}
// resolve the icons behavior with event delegation
$("ul.gallery > li").click(function (event) {
var $item = $(this),
$target = $(event.target);
if ($target.is("a.ui-icon-dashboard")) {
deleteImage($item);
} else if ($target.is("a.ui-icon-zoomin")) {
viewLargerImage($target);
} else if ($target.is("a.ui-icon-refresh")) {
recycleImage($item);
}
return false;
});
});
I found the problem you describe (but i did not found a relation with the Bootstrap Grid Classes).
For my the problem seems to be related to the z-index and can be solved by adding the following style rules at the end of your CSS code:
.ui-draggable-handle {
z-index: 1;
}

Jquerymobile Slider range +

In Jquerymobile range slider, I can set a value from 0 to 100 and it will show 0 to 100. In my case, I would like to set the range from 0 to 100, and 100+. If the user pushes to end, instead of showing the value of 100, how can I show it as 100+?
The inputs in the jQM rangeslider are type="range". This type only accepts numbers, so the text '100+' cannot be set as the value of the input.
One workaround could be to just position a '+' next to the 100:
Working DEMO
In the rangeslider markup, I have added a <span> with a class of labelPlus:
<div data-role="rangeslider">
<label for="range-1a">Rangeslider:</label>
<input type="range" name="range-1a" id="range-1a" min="0" max="100" value="40" />
<label for="range-1b">Rangeslider:</label>
<input type="range" name="range-1b" id="range-1b" min="0" max="100" value="80" />
<span class="labelPlus">+</span>
</div>
The labelPlus class CSS initially hides the span but absolutely positions it in the correct spot:
.labelPlus{
display: none;
position: absolute;
right: 0px;
font-size: 14px;
font-weight: bold;
text-align: right;
width: 48px;
line-height: 30px;
margin-right: 18px;
margin-top: 8px;
}
Finally in javascript we handle the change event on the input and check to see if we are at 100. If so, show the span:
$("#range-1b").on("change", function(){
var val = $(this).val();
if (parseInt(val) >= 100) {
$(".labelPlus").show();
} else {
$(".labelPlus").hide();
}
});
I have created Fiddle.
$(function() {
$( "#slider" ).slider({
range: true,
min: 0,
max: 110,
slide: function( event, ui ) {
if(ui.value>100)
{
$("#ammount").text("100+")
}
else
{
$( "#ammount" ).text(ui.value );
}
}
});
});

jqGrid:Font Awesome Icons

I am trying to use Font Awesome icons in place of the jqueryUI icons for the toolbar in my jqGrid (add,edit,delete,view icons).
This demo is exactly what I would like to accomplish. I've read Oleg's answer that demonstrates removing the icon class and adding the Font Awesome icons in its place. But when I try to do that nothing changes. I believe I'm possibly referencing the icons wrong.
I downloaded Font Awesome 4.0.3 and I have jqGrid 4.5.4--In the _icons.scss file of the FA file tree the icons are referenced like this:
.#{$fa-css-prefix}-pencil:before { content: $fa-var-pencil; }
But in Oleg's suggested code the new icons are labeled "icon-pencil":
$grid.jqGrid("navGrid", "#pager", {editicon: "icon-pencil",
addicon: "icon-plus", delicon: "icon-trash", searchicon: "icon-search",
refreshicon: "icon-refresh", viewicon: "icon-file",view: true});
$("#pager .navtable .ui-pg-div>span").removeClass("ui-icon");
This is my code: I only did the edit icon for this example. I also used the new label for the icons, "fa-pencil".
jQuery("#grid").jqGrid('navGrid','#grid_toppager"', {editicon: "fa-pencil", edit:true});
$('#grid_toppager .navtable .ui-pg-div>span').removeClass('ui-icon');
What combination of code do I need in order to replace the ui-icons with the Font Awesome icons?
Any helpful tips would be appreciated, thanks
I agree that my old answer can't be used with Font Awesome 4 because the names of the classes are changed in version 4. I use Font Awesome 4 myself in solutions which I develop for my customers and I decide to share it with other.
The files jQuery.jqGrid.fontAwesome4.css, jQuery.jqGrid.fontAwesome4.js and jQuery.jqGrid.checkboxFontAwesome4.js contains new jqGrid method initFontAwesome and formatter: "checkboxFontAwesome4". The demo demonstrates the usage of the files:
The usage of suggested method initFontAwesome is very simple. First of all one need to include additional CSS and JavaScript files:
<link rel="stylesheet" type="text/css"
href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css">
...
<link rel="stylesheet" type="text/css" href=".../ui.jqgrid.css" />
<link rel="stylesheet" type="text/css" href=".../jQuery.jqGrid.fontAwesome4.css" />
...
<script type="text/javascript" src=".../i18n/grid.locale-en.js"></script>
<script type="text/javascript" src=".../jquery.jqGrid.min.js"></script>
<script type="text/javascript" src=".../jQuery.jqGrid.fontAwesome4.js"></script>
Then one modify well known line
$("#grid").jqGrid({
... // jqGrid options and callbacks
});
to
$("#grid").jqGrid("initFontAwesome").jqGrid({
... // jqGrid options and callbacks
});
To use formatter: "checkboxFontAwesome4" instead of predefined formatter formatter: "checkbox" one need just includes jQuery.jqGrid.checkboxFontAwesome4.js after jquery.jqGrid.min.js (or jquery.jqGrid.src.js):
<script type="text/javascript"
src=".../jQuery.jqGrid.checkboxFontAwesome4.js"></script>
The formatter "checkboxFontAwesome4" have some advantage to formatter: "checkbox":
one can select the row by clicking on the icons. The standard formatter: "checkbox" uses disabled <input type="checkbox">. Clicking on disabled control will be blocked on the most web browsers. I posted before "clickableCheckbox" (see here and here).
The tests which I made with grids having many rows and columns using the tree checkbox formatters shows that formatter "checkboxFontAwesome4" is the most quick in rendering (in all web browsers where I it tested), formatter: "checkbox" is lower and "clickableCheckbox" is the mostly slow. So formatter "checkboxFontAwesome4" is not only cool, but it's really quick in rendering.
At the end I includes the current state of jQuery.jqGrid.fontAwesome4.css, jQuery.jqGrid.fontAwesome4.js and jQuery.jqGrid.checkboxFontAwesome4.js:
jQuery.jqGrid.fontAwesome4.css:
.ui-jqgrid .ui-pg-table .ui-pg-div>span.fa, #jqContextMenu .ui-menu-item>a>span.fa {
text-indent:0;
height: auto;
width: auto;
background-image: none;
overflow: visible;
padding-top: 1px;
}
.ui-jqgrid .ui-pg-table .ui-pg-div {
text-indent:0;
height: auto;
width: auto;
background-image: none;
overflow: visible;
padding-top: 1px;
}
.ui-jqgrid .ui-jqgrid-titlebar-close.fa-title span { font-size: 18px; display: inline-block; }
.ui-jqgrid .ui-jqgrid-titlebar-close.fa-title { margin-top: 0; top: 0; padding-left: 2px; padding-bottom: 2px;}
.ui-jqgrid .ui-icon-asc.fa { height: auto; margin-top: 0; }
.ui-jqgrid .ui-icon-asc.fa, .ui-jqgrid .ui-icon-desc.fa {
height: auto; margin-top: 2px; margin-left: 2px;
}
.ui-jqgrid .s-ico>.ui-state-disabled.fa, .s-ico>.ui-state-disabled.fa { padding: 0; }
.ui-jqdialog .ui-jqdialog-titlebar-close { text-decoration: none; right: 0.2em !important}
.ui-jqdialog .ui-jqdialog-titlebar-close>span { margin-top: 3px; margin-left: 5px;}
.ui-jqdialog .EditTable .fm-button-icon-right { padding-left: 0; padding-right: 0.5em; float:right;}
.ui-jqdialog .EditTable .fm-button-icon-left { padding-left: 0; float:left; }
.ui-jqdialog .EditButton>.fm-button { display: block; width: auto; }
.ui-jqdialog .EditButton>.fm-button>span { float: left; margin-left: 0.5em; margin-right: 0;}
.ui-jqgrid .ui-jqdialog .fm-button>span { margin-left: 0.5em; margin-right: 0; }
.ui-jqdialog>.ui-resizable-se { bottom: -3px; right: -3px}
jQuery.jqGrid.fontAwesome4.js:
/*global $ */
(function ($) {
"use strict";
/*jslint unparam: true */
$.extend($.jgrid, {
icons: {
common: "fa", // will be implemented later
scale: "", // will be implemented later. For example as "fa-lg"
titleVisibleGrid: "fa fa-arrow-circle-up",
titleHiddenGrid: "fa fa-arrow-circle-down",
titleIcon: "ui-corner-all fa-title",
close: "fa fa-times",
edit: "fa fa-pencil fa-fw",
add: "fa fa-plus fa-fw",
del: "fa fa-trash-o fa-fw",
search: "fa fa-search fa-fw",
refresh: "fa fa-refresh fa-fw",
view: "fa fa-file-o fa-fw",
pager: {
first: "fa fa-step-backward fa-fw",
prev: "fa fa-backward fa-fw",
next: "fa fa-forward fa-fw",
last: "fa fa-step-forward fa-fw"
},
form: {
prev: "fa fa-caret-left",
next: "fa fa-caret-right",
save: "fa fa-floppy-o",
undo: "fa fa-undo",
close: "fa fa-times",
delete: "fa fa-trash-o"
},
searchForm: {
reset: "fa fa-undo",
query: "fa fa-comments-o",
search: "fa fa-search"
}
}
});
$.extend($.jgrid.nav, {
editicon: $.jgrid.icons.edit,
addicon: $.jgrid.icons.add,
delicon: $.jgrid.icons.del,
searchicon: $.jgrid.icons.search,
refreshicon: $.jgrid.icons.refresh,
viewicon: $.jgrid.icons.view
});
$.extend($.jgrid.defaults, {
fontAwesomeIcons: true // the new option will be used in callbacks
});
$.extend($.jgrid, {
originalCreateModal: $.jgrid.originalCreateModal || $.jgrid.createModal,
createModal: function (aIDs, content, p, insertSelector, posSelector, appendsel, css) {
$.jgrid.originalCreateModal.call(this, aIDs, content, p, insertSelector, posSelector, appendsel, css);
if ($(insertSelector).find(">.ui-jqgrid-bdiv>div>.ui-jqgrid-btable").jqGrid("getGridParam", "fontAwesomeIcons")) {
$("#" + $.jgrid.jqID(aIDs.modalhead) + ">a.ui-jqdialog-titlebar-close>span.ui-icon")
.removeClass("ui-icon ui-icon-closethick")
.addClass($.jgrid.icons.close);
$("#" + $.jgrid.jqID(aIDs.themodal) + ">div.jqResize").removeClass("ui-icon-grip-diagonal-se");
}
}
});
$.extend($.jgrid.view, {
beforeShowForm: function ($form) {
var $dialog = $form.closest(".ui-jqdialog"),
$iconSpans = $dialog.find("a.fm-button>span.ui-icon");
$iconSpans.each(function () {
var $this = $(this), $fmButton = $this.parent();
if ($this.hasClass("ui-icon-triangle-1-w")) {
$this.removeClass("ui-icon ui-icon-triangle-1-w")
.addClass($.jgrid.icons.form.prev);
} else if ($this.hasClass("ui-icon-triangle-1-e")) {
$this.removeClass("ui-icon ui-icon-triangle-1-e")
.addClass($.jgrid.icons.form.next);
} else if ($this.hasClass("ui-icon-close")) {
$fmButton.removeClass("fm-button-icon-left")
.addClass("fm-button-icon-right")
.html("<span class=\"" + $.jgrid.icons.form.close + "\"></span><span>" + $fmButton.text() + "</span>");
}
});
}
});
$.extend($.jgrid.del, {
afterShowForm: function ($form) {
var $dialog = $form.closest(".ui-jqdialog"),
$tdButtons = $dialog.find(".EditTable .DelButton"),
$fmButtonNew = $("<td class=\"DelButton EditButton\" style=\"float: right;\">"),
$iconSpans = $tdButtons.find(">a.fm-button>span.ui-icon");
$tdButtons.css("float", "right");
$iconSpans.each(function () {
var $this = $(this), $fmButton = $this.parent();
if ($this.hasClass("ui-icon-scissors")) {
$fmButton.html("<span class=\"" + $.jgrid.icons.form.delete + "\"></span><span>" + $fmButton.text() + "</span>");
$fmButtonNew.append($fmButton);
} else if ($this.hasClass("ui-icon-cancel")) {
$fmButton.html("<span class=\"" + $.jgrid.icons.form.undo + "\"></span><span>" + $fmButton.text() + "</span>");
$fmButtonNew.append($fmButton);
}
});
if ($fmButtonNew.children().length > 0) {
// remove between buttons
$tdButtons.replaceWith($fmButtonNew);
}
}
});
$.jgrid.extend({
initFontAwesome: function () {
return this.each(function () {
var $grid = $(this);
$grid.bind("jqGridFilterAfterShow", function (e, $form) {
// an alternative to afterShowSearch
var $dialog = $form.closest(".ui-jqdialog"),
$iconSpans = $dialog.find("a.fm-button>span.ui-icon");
$iconSpans.each(function () {
var $this = $(this), $fmButton = $this.parent();
$this.removeClass("ui-icon");
if ($this.hasClass("ui-icon-search")) {
$this.closest(".EditButton").css("float", "right");
$fmButton.addClass("fm-button-icon-right")
.html("<span class=\"" + $.jgrid.icons.searchForm.search + "\"></span><span>" + $fmButton.text() + "</span>");
} else if ($this.hasClass("ui-icon-arrowreturnthick-1-w")) {
$this.closest(".EditButton").css("float", "left");
$fmButton.addClass("fm-button-icon-left")
.html("<span class=\"" + $.jgrid.icons.searchForm.reset + "\"></span><span>" + $fmButton.text() + "</span>");
} else if ($this.hasClass("ui-icon-comment")) {
$this.closest(".EditButton").css("float", "right");
$fmButton.addClass("fm-button-icon-right")
.html("<span class=\"" + $.jgrid.icons.searchForm.query + "\"></span><span>" + $fmButton.text() + "</span>");
}
});
}).bind("jqGridAddEditBeforeShowForm", function (e, $form) {
// alternative to beforeShowForm callback
var $dialog = $form.closest(".ui-jqdialog"),
$iconSpans = $dialog.find("a.fm-button>span.ui-icon");
$iconSpans.each(function () {
var $this = $(this), $fmButton = $this.parent();
if ($this.hasClass("ui-icon-triangle-1-w")) {
$this.removeClass("ui-icon ui-icon-triangle-1-w")
.addClass($.jgrid.icons.form.prev);
} else if ($this.hasClass("ui-icon-triangle-1-e")) {
$this.removeClass("ui-icon ui-icon-triangle-1-e")
.addClass($.jgrid.icons.form.next);
} else if ($this.hasClass("ui-icon-disk")) {
$this.closest(".EditButton").css("float", "right");
$fmButton.html("<span class=\"" + $.jgrid.icons.form.save + "\"></span><span>" + $fmButton.text() + "</span>");
} else if ($this.hasClass("ui-icon-close")) {
$this.closest(".EditButton").css("float", "right");
$fmButton.removeClass("fm-button-icon-left")
.addClass("fm-button-icon-right")
.html("<span class=\"" + $.jgrid.icons.form.undo + "\"></span><span>" + $fmButton.text() + "</span>");
}
});
}).bind("jqGridHeaderClick", function (e, gridstate) {
var $icon;
if (this.p.fontAwesomeIcons) {
$icon = $(this).closest(".ui-jqgrid").find(".ui-jqgrid-titlebar>.ui-jqgrid-titlebar-close>span");
if (gridstate === "visible") {
$icon.removeClass("ui-icon ui-icon-circle-triangle-n fa-arrow-circle-down")
.addClass($.jgrid.icons.titleVisibleGrid).parent().addClass($.jgrid.icons.titleIcon);
} else if (gridstate === "hidden") {
$icon.removeClass("ui-icon ui-icon-circle-triangle-n fa-arrow-circle-up")
.addClass($.jgrid.icons.titleHiddenGrid).parent().addClass($.jgrid.icons.titleIcon);
}
}
}).bind("jqGridInitGrid", function () {
var $this = $(this), $pager, $sortables;
if (this.p.fontAwesomeIcons) {
$pager = $this.closest(".ui-jqgrid").find(".ui-pg-table");
$pager.find(".ui-pg-button>span.ui-icon-seek-first")
.removeClass("ui-icon ui-icon-seek-first")
.addClass($.jgrid.icons.pager.first);
$pager.find(".ui-pg-button>span.ui-icon-seek-prev")
.removeClass("ui-icon ui-icon-seek-prev")
.addClass($.jgrid.icons.pager.prev);
$pager.find(".ui-pg-button>span.ui-icon-seek-next")
.removeClass("ui-icon ui-icon-seek-next")
.addClass($.jgrid.icons.pager.next);
$pager.find(".ui-pg-button>span.ui-icon-seek-end")
.removeClass("ui-icon ui-icon-seek-end")
.addClass($.jgrid.icons.pager.last);
$this.closest(".ui-jqgrid")
.find(".ui-jqgrid-titlebar>.ui-jqgrid-titlebar-close>.ui-icon-circle-triangle-n")
.removeClass("ui-icon ui-icon-circle-triangle-n")
.addClass("fa fa-arrow-circle-up").parent().addClass("ui-corner-all fa-title");
$sortables = $this.closest(".ui-jqgrid")
.find(".ui-jqgrid-htable .ui-jqgrid-labels .ui-jqgrid-sortable span.s-ico");
$sortables.find(">span.ui-icon-triangle-1-s")
.removeClass("ui-icon ui-icon-triangle-1-s")
.addClass("fa fa-sort-asc fa-lg");
$sortables.find(">span.ui-icon-triangle-1-n")
.removeClass("ui-icon ui-icon-triangle-1-n")
.addClass("fa fa-sort-desc fa-lg");
}
});
});
}
});
}(jQuery));
jQuery.jqGrid.checkboxFontAwesome4.js:
/*global jQuery */
(function ($) {
"use strict";
/*jslint unparam: true */
$.extend($.fn.fmatter, {
checkboxFontAwesome4: function (cellValue, options) {
var title = options.colModel.title !== false ? ' title="' + (options.colName || options.colModel.label || options.colModel.name) + '"' : '';
return (cellValue === 1 || String(cellValue) === "1" || cellValue === true || String(cellValue).toLowerCase() === "true") ?
'<i class="fa fa-check-square-o fa-lg"' + title + '></i>' :
'<i class="fa fa-square-o fa-lg"' + title + '></i>';
}
});
$.extend($.fn.fmatter.checkboxFontAwesome4, {
unformat: function (cellValue, options, elem) {
var cbv = (options.colModel.editoptions) ? options.colModel.editoptions.value.split(":") : ["Yes", "No"];
return $(">i", elem).hasClass("fa-check-square-o") ? cbv[0] : cbv[1];
}
});
}(jQuery));
UPDATED: Another demo contains some additional CSS styles which improve visibility of jqGrid if one includes bootstrap.css of the Bootstrap 3.0.2. I am sure that the styles are not the best, but there fix the problems which I found in my tests. Below are the styles:
.ui-jqgrid .ui-pg-table .ui-pg-input, .ui-jqgrid .ui-pg-table .ui-pg-selbox {
height: auto;
width: auto;
line-height: inherit;
}
.ui-jqgrid .ui-pg-table .ui-pg-selbox {
padding: 1px;
}
.ui-jqgrid { line-height: normal; }
div.ui-jqgrid-view table.ui-jqgrid-btable {
border-style: none;
border-top-style: none;
border-collapse: separate;
}
.ui-jqgrid .ui-jqgrid-titlebar-close.fa-title {
border-collapse: separate;
margin-top: 0;
top: 0;
margin-right: 2px;
height: 22px;
width: 20px;
padding: 2px;
}
.ui-jqgrid .ui-jqgrid-titlebar-close.fa-title.ui-state-hover span {
margin-top: -1px;
margin-left: -1px;
}
.ui-paging-info { display: inline; }
.ui-jqgrid .ui-pg-table { border-collapse: separate; }
div.ui-jqgrid-view table.ui-jqgrid-btable td {
border-left-style: none
}
div.ui-jqgrid-view table.ui-jqgrid-htable {
border-style: none;
border-top-style: none;
border-collapse: separate;
}
div.ui-jqgrid-view table.ui-jqgrid-btable th {
border-left-style: none
}
.ui-jqgrid .ui-jqgrid-htable th div {
height: 14px;
}
.ui-jqgrid .ui-jqgrid-resize {
height: 18px !important;
}
UPDATED 2: One more demo works with Font Awesome 4.2 and Bootstrap 3.2. The usage is very easy. One should include some .css (jQuery.jqGrid.fontAwesome4.css and jQuery.jqGrid.bootstrap-fixes.css) and .js files (jQuery.jqGrid.fontAwesome4.js and jQuery.jqGrid.checkboxFontAwesome4.js) and to use .jqGrid("initFontAwesome") before the grid are created. To fix problems with height of editing form at the second opening I used beforeInitData: function () { $("#editmod" + this.id).remove(); } additionally. One can download the latest versions of jQuery.jqGrid.fontAwesome4.css, jQuery.jqGrid.bootstrap-fixes.css, jQuery.jqGrid.fontAwesome4.js and jQuery.jqGrid.checkboxFontAwesome4.js from here.
For custom buttons, here is quick and... work around:
$(grid).jqGrid('navButtonAdd', pager, {
buttonicon: 'none',
caption: '<span class="my-fa-icon fa fa-barcode"></span> My Caption Here',
id: 'btnMyButton'
})
if you need to change the caption dynamically, update the div (representing the button) html (not text):
var myButton = $($(grid)[0].p.pager + '_left ' + 'td#btnMyButton');
$(myButton ).html('<span class="my-fa-icon fa fa-barcode"></span> My NEW Caption Here');
I included a css class, .my-fa-icon, just in case you want to add some customization (and make the display closer to what jqGrid does) - for example, you can add this to your css file:
.ui-jqgrid .ui-jqgrid-pager .ui-pg-button .ui-pg-div span.my-fa-icon { margin: 0 2px; width: 1.4em; font-size: 1.4em; float: left; overflow: hidden; }

Resources