select2 4.0 - TypeError: $(...).select2(...).select2(...) is undefined - jquery-select2

Trying to finally change over to the 4.0 version of select2 and running into a problem.
All of this works perfectly fine on 3.5. On button click I open a bootstrap modal and load a remote page into it. I have tested all everything on a normal page (not in a modal) and it works correctly. When loaded in a modal as below the modal opens and everything like it always had for 3.5, but select2 is returning an error. I believe the issue here is the select2 is being loaded from a remote page... thing is this same remote loading method always worked flawlessly with 3.5.
TypeError: $(...).select2(...).select2(...) is undefined
js:
// show edit modal
$('#datatable2').on('click', '.dtEdit', function () {
var data = {
'filter_id': $(this).parents('tr').attr('id').replace('dtrow_', '')
};
$('#modal-ajax').load(
'/modals/m_filtering_applications_filters.php',
data,
function() {
$(this).modal('show');
changeSettings();
hourSelection();
}
);
});
// change filter modal confirmation
var changeSettings = function() {
// get the default filter
var default_filter = $("#filter_default").val();
//app list
$("#vedit-filter").select2({
placeholder: {
id: default_filter, // or whatever the placeholder value is
text: default_filter // the text to display as the placeholder
},
allowClear: true,
multiple: false,
tags: true,
createTag: function (query) {
return {
id: query.term,
text: query.term,
tag: true
}
},
ajax: {
dataType: 'json',
delay: 500,
type: 'post',
url: '/process/get_application_list.php',
data: function (params) {
return {
term: params.term, // search term
page: params.page, //page number
page_limit: 25, // page size
};
},
results: function (data, page) {
var more = (page * 25) < data.total; // whether or not there are more results available
return {
results: data.results,
more: more
};
}
}
}).select2('val', [default_filter]).on('change', function() {
$(this).valid();
});
}
m_filtering_applications_filters.php :
Just the contents of the modal which is loaded in :
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 class="modal-title">Change these settings?</h3>
</div>
<form id="application-filters-edit">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12 margin-bottom-30 form-group">
<div class="input-modal-group">
<label for="vedit-filter" class="f-14"><b>Application to filter :</b></label>
<select id="vedit-filter" name="settings[filter]" class="form-control select2">
<option value="<?php echo htmlspecialchars($result['filter'], ENT_QUOTES, 'UTF-8'); ?>" selected=""><?php echo htmlspecialchars($result['filter'], ENT_QUOTES, 'UTF-8'); ?></option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="settings[users][]" value="<?php echo $result['user_id']; ?>"/>
<input id="filter_default" type="hidden" name="settings[original]" value="<?php echo htmlspecialchars($result['filter'], ENT_QUOTES, 'UTF-8'); ?>"/>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<?php
if (!$result)
{
//disable the button
echo '<button type="button" class="btn btn-primary disabled" data-dismiss="modal"><i class="fa fa-check-circle"></i> Save Settings</button>';
}
else
{
// show the button
echo '<button class="btn btn-primary" type="submit"><i class="fa fa-check-circle"></i> Save Settings</button>';
}
?>
</div>
</form>
</div>
</div>
UPDATE:
Okay, the error is coming from :
}).select2('val', [default_filter]).on('change', function() {
$(this).valid();
});
attached to the end... this is for using the jquery validation script (I did not include this in the jS here), and again, worked fine in 3.5. Can you not add on to the select2() anymore with 4.0 or something?
When removing this line the error goes away, but the display of the select2 is very small in width and I cannot gain focus on the search box to enter any values so it is still unusable within the modal.
UPDATE2:
Realized the events changed with 4.0 so this seems to work :
}).on("change", function (e) {
$(this).valid();
});
Still cannot enter anything into the search box though. Also, I notice if I click on anything other than the arrow in the input box to show the dropdown it acts as if the mouse is being held down - it highlights all the text/content within the modal.

Solution : All the issues I was having with the select2 in my bs3 modal were solved by adding the following in my js :
$.fn.modal.Constructor.prototype.enforceFocus = $.noop;
The highlighting of content/text is gone. The focus on the search box is gone. For now everything seems to work great. I do not have any information as to what this line actually does at the moment, but will be researching this to find out and will add it back here for future reference for anyone.

Related

How to show a bootstrap modal success message on successfully added product to the cart

I have written a jquery for adding product to the cart and this is the partiallistofproduct.cshtml file.
<div class="container">
<div class="row">
<div class="col-sm-9 padding-right">
<div class="features_items">
<h2 class="admin-title text-center"></h2>
<!--Partial list of Products-->
#foreach (var item in Model)
{
<div class="features_items">
<!--features_items-->
<div class="col-sm-4">
<div class="product-image-wrapper">
<div class="single-products">
<div id="#item.ProductID" class="productinfo text-center">
<a href="#Url.Action("ReadProductDetails", "Home",new {id=item.ProductID })">
<img src="#Url.Content(item.ProductImage)" alt="" />
</a>
<h2>Rs #item.Price</h2>
<p>#item.ProductName</p>
#if (Session["UserName"] != null)
{
<p hidden id="userid">#Session["UserID"].ToString()</p>}
<input type="hidden" id="hdnSession" data-value="#Request.RequestContext.HttpContext.Session["Name"]" />
<input id="AddToCart" type="submit" value="Add to Cart" class="btn btn-default add-to-cart" />
</div>
<div class="product-overlay">
<div id="#item.ProductID" class="overlay-content">
<h2>Rs #item.Price</h2>
<p id="productid">#item.ProductID</p>
<a class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
</div>
</div>
</div>
</div>
</div>
</div><!--features_items-->
}
<!--Pagination part-->
#Html.PagedListPager(Model, page => Url.Action("Index", new { page, pageSize = Model.PageSize }))
showing #Model.FirstItemOnPage to #Model.LastItemOnPage of #Model.TotalItemCount Products
</div>
</div>
</div>
</div>
The following is the script file to add the product to the cart.Here i am able to add the product to the cart.
<script>
$(document).ready(function () {
//on click on add to cart class this will perform
$('.add-to-cart').click(function () {
//checking user is logged in or not otherwise redirect to login page
var sessionValue = $("#hdnSession").data('value');
var aaa = parseInt($(this).closest('div').prop('id'));
if (sessionValue != false) {
$.ajax({
url: 'Account/AddToCart',
data: { //Passing data
UserID: $("#userid").html(), //Reading text box values using Jquery
ProductID: $(this).closest('div').prop('id'),
Quantity: 1
},
type: 'POST',
dataType: 'json',
//on success message will show as an alert
success: function (data) {
if (data != null && data.success) {
alert(data.responseText);
} else {
// DoSomethingElse()
alert(data.responseText);
}
},
//on failure error message will occur
error: function (data) {
alert("error");
}
});
}
else {
//redirection to login page
window.location.replace("#Url.Action("Login", "Account")");
}
});
});
</script>
Here i want to show a bootstrap modal success message with successful adding the product to the cart. I dont know how to use bootstrap modal to show the success message.
So please help me to show a bootstrap modal success message.
Add modal in your view which you want to show on after successful addition of products to cart and add style:display:none
then inside Ajax Success function just write
$("#modal-Id").modal();

hold submit for modal dialog confirmation in mvc 5

I'm trying to display a modal dialog when data is submitted on my create view. I need the modal to force the submit to wait for user confirmation on the modal dialog. Then the data needs to be submitted. Below is my create view code using bootstrap 3.0 modal-dialog:
<div class="form-group">
#Html.LabelFor(model => model.Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="col-md-offset-2 col-md-10">
<input id="create" type="submit" value="Create" class="btn btn-default"/>
</div>
</div>
<div id="modalBox" class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">X</a>
<h1>Confirmation</h1>
</div>
<div class="modal-body">
<h6>Click YES to confirm</h6>
</div>
<div class="modal-footer">
<button id="noPost" class="btn btn-default" name="postConfirm" value="false" data-dismiss="modal">No Thanks</button>
<button id="yesPost" class="btn btn-primary" name="postConfirm" value="true" data-dismiss="modal">YES</button>
</div>
</div>
</div>
#section scripts{
<scripts>
$(function () {
var modalBox = function (e) {
e.preventDefault();
$("#modalBox").modal({ show: true });
};
$("#create").click(modalBox);
});
<scripts>
}
This does interrupt the submit function and brings up the modal dialog but I don't know how to submit the data back to the controller once a selection is made on the dialog. I have also tried using the jquery ui modal dialog with the script below:
<script>
$("#create").click(function (e) {
e.preventDefault();
$("#postModal").dialog("open");
});
$("#postModal").dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: {
"No Thanks": function (data) {
$("#create").submit();
$(this).dialog("close");
},
"YES": function () {
$("#create").submit();
$(this).dialog("close");
}
}
});
</script>
This does bring up the modal dialog but I still can't get it to submit the model data back to the controller. Any help would be appreciated.
UPDATE
By inspecting the produced html I discovered my input fields resided within a form that I didn't put there. I suspect this is due to me using the #Html.ValidationSummary(true) or something built into MVC. So instead of using:
$("#create").submit();
I used:
$("form:first").submit();
To submit the first, and only form, on the page and it worked!
Change your create button type to type=button, and make it to just open modal view. And make your yespost button in modal div holder to type submit . Also you can try to put whole modal div holder inside your form-group div. Here you are making post before openning modal view. It s because your button have 2 logic task, separate those task and this should work.

How to passing form params from formRemote to remoteFunction in GSP

example is very simple.
select the two search condition and return a table with pagination, the whole page will not refresh.
so i use the grails formRemote to submit the form, and the control return the gender with template and it work well. However, the pagination i want to use Jquery, but i cant pass the formRemote params to the remoteFunction using onSuccess method in formRemote.
Here it is the code:
<div class="formSep col-md-12">
<g:formRemote update="searchResult" class="form-inline" role="form" name="form"
url="[controller: 'autoRateRecord', action: 'search']" onSuccess="initPagination(data)">
<div class="form-group col-lg-2">
<g:select class="form-control" name="notified" from="${['done', 'undone']}"
noSelection="${['null': 'Oops']}">
</g:select>
</div>
<div class="form-group col-lg-2 pull-right">
<button type="submit" class="btn btn-primary btn-lg">
<span class="glyphicon glyphicon-search"></span> search
</button>
</div>
</g:formRemote>
</div>
<div id="searchResult">
<g:render template="searchList"/>
</div>
<script type='text/javascript'>
function initPagination(data) {
console.log("------> " + data)
$("#Pagination").pagination(10, {
callback: getRecordList(1),
prev_text: "prev",
next_text: "next",
items_per_page: 15,
num_edge_entries: 1
});
}
**!!!!!!! need formRemote data !!!!!!!**
function getRecordList(page_index) {
<g:remoteFunction controller="autoRateRecord" action="search" update="searchResult" params="'page='+page_index"/>
}
// On load, style typical form elements
$(function () {
});
</script>
the controller code is:
def search = {
log.info(ToStringBuilder.reflectionToString(params))
// logic .....
render(template: "searchList", model: [
autoRateRecords: result,
total : result.totalCount
])
}
I would change the pagination script to something like
$("#pageHiddenFieldId").val(pageNo);
$("#myForm").submit();

grails angularjs - modal not working as expected

I want to show modal(encouragementModal) only when user clicks on Encourage button.
Configuration
GSP View _encourage.gsp is :
<div ng-controller="EncouragementController">
<g:if test="${notEncouraged}">
<button class="btn" ng-click="openEncouragementModal()">Encourage</button>
<div modal="encouragementModal" close="closeEncouragementModal()" options="opts">
<div class="modal-header">
<h3>Encourage!</h3>
</div>
<div class="modal-body">
You are about to encourage with {{amount}}.
</div>
<div class="modal-footer">
<button class="btn btn-info cancel" ng-click="encourage()">Confirm</button>
<button class="btn btn-warning cancel" ng-click="close()">Cancel</button>
</div>
</div>
</g:if>
<g:else>
Thank you for encouraging.
</g:else>
The EncouragementController.js is
function EncouragementController($scope, $http) {
/**
* open payment dialog
*/
$scope.openEncouragementModal = function (amount) {
$scope.encouragementModal = true;
};
$scope.closeEncouragementModal = function () {
$scope.closeMsg = 'You canceled the encouragement’;
$scope.encouragementModal = false;
};
$scope.opts = {
backdropFade: true,
dialogFade:true
};
}
EncouragementController.$inject = [ '$scope', '$http'];
Question
Only the Encourage button should have been visible for the first time, but what I see is button along with the encouragementModal and it's buttons.
So, how do I do that?
References I followed
[1] Modal (ui.bootstrap.modal)
[2] Simple Grails + AngularJS Example
You need to hide it at first and only display it when scope.encouragementModal value is true.
<div modal="encouragementModal" ng-show="encouragementModal" options="opts">

Change position of input filed for jQuery Mobile Filter List

Im using the jQuery Mobile Filter List:
http://jquerymobile.com/test/docs/lists/lists-search-with-dividers.html
Is it possible to move the position of the input field so I can put it into a div already on my page?
Using jQuery's appendTo seems to work fine but its kind of a hacky solution. Thanks
this is what I found while searching for solution to a similar problem.
HTML code example:
<div data-role="page" id="page-id">
<div data-role="content">
<div data-role="fieldcontain">
<input type="search" name="password" id="search" value="" />
</div>
<div class="filter-div" data-filter="one">1</div>
<div class="filter-div" data-filter="two">2</div>
<div class="filter-div" data-filter="three">3</div>
<div class="filter-div" data-filter="four">4</div>
<div class="filter-div" data-filter="five">5</div>
</div>
</div>
JS code example:
$(document).delegate('#page-id', 'pageinit', function () {
var $filterDivs = $('.filter-div');
$('#search').bind('keyup change', function () {
if (this.value == '') {
$filterDivs.slideDown(500);
} else {
var regxp = new RegExp(this.value),
$show = $filterDivs.filter(function () {
return ($(this).attr('data-filter').search(regxp) > -1);
});
$filterDivs.not($show).slideUp(500);
$show.slideDown(500);
}
});
});
This way you can place your input text box anywhere on your page and it should properly filter a list of items you want.
JSFiddle DEMO: http://jsfiddle.net/cZW5r/30/

Resources