Autocomplete in a modal is not listed/populated - jquery-ui

I am creating an 'assign button' which calls a modal. In this modal will search a username queried from a database table. This autocomplete should be listed in the modal box, in fact it is not. I am using Jquery UI for this.
The "No search result" text is behind the modal, as well the assignee is listed behind the modal.
I am detailing my code in this jsfiddle
This is my original code:
$("#user_name").autocomplete({
source: function(request, response) {
$.ajax({
url: "https://dummyjson.com/products",
// url: "<?= site_url('Inventory/readuser'); ?>",
method: "get",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
console.log("response --> ", data);
response(data); //callback fn
}
}) //ajax
console.log("ok");
}, //source
select: function(event, ui) {
$('[name="username"]').val(ui.item.username);
$('[name="role"]').val(ui.item.role);
$('[name="location"]').val(ui.item.location);
}
}); //#user_name
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js" integrity="sha512-57oZ/vW8ANMjR/KQ6Be9v/+/h6bq9/l3f0Oc7vn6qMqyhvPd1cvKBRWWpzu0QoneImqr2SkmO4MSqU+RpHom3Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<i class="bx bxs-filter-alt text-white-50"></i>Assign
</div>
<div class="modal fade" id="updateUser" tabindex="-1" aria-labelledby="updateUser" aria-hidden="true">
<div class="modal-dialog modal-dialog-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Assign user ...</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<fieldset class="border rounded-3 p-2">
<legend class="float-none w-auto px-2 small">type a user name</legend>
<div class="frmSearch">
<input type="text" class="form-control form-control-sm" id="user_name" name="user_name" size="20" maxlength="3">
<div id="suggesstion-box"></div>
</div>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-save-filter" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-save-filter" data-bs-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
but in fiddle I am using dummy json from
https://dummyjson.com/docs/products
Please advise how to put the listed value into the green box in the modal.

Please review the following:
https://jsfiddle.net/Twisty/orv2j67n/1/
JavaScript
$("#user_name").autocomplete({
appendTo: "#suggestion-box",
source: function(request, response) {
$.ajax({
url: "https://dummyjson.com/products",
method: "get",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
var results = $.map(data.products, function(v, i) {
v = $.extend(v, {
label: v.brand,
value: v.brand
});
return v;
});
console.log(results);
response(results);
}
});
console.log("ok");
},
select: function(event, ui) {
$('[name="label"]').val(ui.item.title);
}
});
Two changes to be aware of:
appendTo: "#suggestion-box",
Which element the menu should be appended to. When the value is null, the parents of the input field will be checked for a class of ui-front. If an element with the ui-front class is found, the menu will be appended to that element. Regardless of the value, if no element is found, the menu will be appended to the body.
I also added a $.map() in the Success. This ensure that the proper elements exist when passing the data back to response().
var results = $.map(data.products, function(v, i) {
v = $.extend(v, {
label: v.brand,
value: v.brand
});
return v;
});
console.log(results);
response(results);
This is discussed here: https://api.jqueryui.com/autocomplete/#option-source
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

Related

Vue.draggable Get Dragged Item and List ID

I've read all the documentation and stackoverflow I can find, but still am having issues with this.
I'm building a Trello clone with Vue and Rails.
I have many draggable lists.
Each list has draggable cards.
When I drag a card from one list to a second list, how do I persist this to my ajax rails endpoint?
I've tried using the #end method and the :move prop, but have had zero luck.
#app.vue
<template>
<draggable v-model="lists" group='lists' class="row dragArea" #end="listMoved">
<div v-for="(list, index) in lists" class="col-3">
<h6>{{ list.name }}</h6>
<hr />
<draggable v-model="list.cards" group='cards' class="dragArea" :move="cardMoved">
<div v-for="(card, index) in list.cards" class="card card-body mb-3">
{{ card.name }}
</div>
</draggable>
<div class="card card-body">
<input v-model="messages[list.id]" class="form-control" ></input>
<button v-on:click="submitMessages(list.id)" class="btn btn-secondary">Add</button>
</div>
</div>
</draggable>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: { draggable },
props: ["original_lists"],
data: function() {
return {
messages: {},
lists: this.original_lists
}
},
methods: {
cardMoved: function(event) {
console.log(event)
var data = new FormData
data.append("card[list_id]", WHERE_DO_I_FIND_THIS_ID)
data.append("card[position]", event.draggedContext.element.id)
Rails.ajax({
url: `/cards/${event.draggedContext.element.id}/move`,
type: "PATCH",
data: data,
datatype: "json"
})
},
}
}
</script>
Use the change event that contains all the dnd information you need and is called only once the drag operation is ended.
As suggested by #sovalina you need to pass extra infomation linked to the list:
:change="changed(list.id, $event)"
Also your div should be keyed:
<div v-for="(card, index) in list.cards" :key="card.name" class="card card-body mb-3">

How to load jqgrid on button click and send parameters to the action in jqGrid 4.6.0 in MVC

I want to load every year's data in jqgrid when I click on a button and after loading a modal form and selecting the year from drop down list. a diagram of the steps
but i don't know how to do this.
And this is my source code :
<!-- Page content -->
<div class="w3-content" style="max-width: 100%">
<div class="container" style="width:40%;margin-top:2%">
Filter
<div class="modal fade" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
</div>
<div class="modal-body">
<form id="myForm" dir="rtl">
<div class="form-group">
<label>Year</label>
#Html.DropDownListFor(model => model.YEAR_ABBR, ViewBag.YearList as MultiSelectList, "--select--", new { #class = "form-control", #id = "ddlYear", multiple = "multiple" })
</div>
</form>
</div>
<div class="modal-footer">
Cancel
<input type="reset" value="GetRep" class="btn btn-success" id="btnSubmit" />
</div> </div>
</div> </div> </div>
<div dir="rtl" align="center" style="overflow:auto" class="tablecontainer">
<div id="rsperror"></div>
<table id="list" cellpadding="0" cellspacing="0"></table>
<div id="pager" style="text-align:center;"></div>
</div>
Now my script is something like this:
<script type="text/javascript">
$(document).ready(function () {
bindData();
$("#btnSubmit").click(function () {
$('#list').trigger('reloadGrid'); })
});
var bindData = function () {
$('#list').jqGrid({
url: '#Url.Action("Get_RepContracts","Home")',
postData: { YEAR_ABBR: function () { return $('#YEAR_ABBR').val(); } },
datatype: 'json',
jsonReader: {
root: "Rows",
page: "Page",
},
mtype: 'GET',
//columns names
colNames: ['Vahed_Descript' ],
colModel: [
{ name: 'Vahed_Descript', index: 'Vahed_Descript', align: 'right', width: 200, sorttype: "number", }
],
pager: $('#pager'),
rowNum: 800,
rowList: [ 800 ,1000],
sortname: 'Vahed_Descript',
hidegrid: false,
direction: "rtl",
gridview: true,
rownumbers: true,
footerrow: true,
userDataOnFooter: true,
loadComplete: function () {
calculateTotal();
$("tr.jqgrow:odd").css("background", "#E0E0E0");
},
loadError: function (xhr, st, err) {
jQuery("#rsperror").html("Type: " + st + "; Response: " + xhr.status + " " + xhr.statusText);
} , loadonce: true
}) ;
And here the button code ( My modal form works well. when I click the filter button, the filter options in my modal form appear, and then I select the year from year dropdownlist in modal and then i click the report button, after that the below code fires and I can see the selected year's data in action "Get_RepContracts" but it does not bind to my jqgrid):
Thanks in Advance...
UPDATE : Now My code is like below :
$(document).ready(function () {
bindData();
$("#btnSubmit").click(function () {
var myPostData = $('#list').jqGrid("getGridParam", "postData");
$('#list').trigger('reloadGrid');
$("#myModal").modal("hide");
}) });
var bindData = function () {
$('#list').jqGrid({
url: '#Url.Action("Get_RepContracts","Home")',
postData: {
YEAR_ABBR : function () { return $("#YEAR_ABBR").val();},
} ,
datatype: 'json',
jsonReader: { ........
It seems to me that you have small problem with the usage of correct id of select element. Your HTML code contains #id = "ddlYear" parameter of #Html.DropDownListFor:
#Html.DropDownListFor(
model => model.YEAR_ABBR,
ViewBag.YearList as MultiSelectList,
"--select--",
new {
#class = "form-control",
#id = "ddlYear",
multiple = "multiple"
}
)
but you still use
postData: {
YEAR_ABBR: function () { return $("#YEAR_ABBR").val(); }
}
To solve the problem you should just modify the code to
postData: {
YEAR_ABBR: function () { return $("#ddlYear").val(); }
}

Modal Function Button Onclick

I have created a Modal on a Create View. I have three buttons - 'Add Conditions', 'No Conditions', and 'Cancel'. When clicking each button I would like it to perform an action. So far the only button that works is the 'Cancel' button as I am using data-dismiss="modal" and not code in my controller. My question is how do you access a ActionResult in your controller. I have tried the following Modal code and corresponding Ajax code.
Modal:
<button type="button" id="confirmItem" data-target="#confirmModal" data-toggle="modal" #*data-id="#AddConditions">Create</button>
<body>
<br/>
<div class="modal fade" id="confirmModal" tabindex="-1" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dissmiss="modal" aria-hidden="true">#*×*#</button>
<h4 class="modal-title">Confirm</h4>
</div>
<div class="modal-body">
<p>Confirm that Requested Burn Conditions should be added.</p>
</div>
<div class="modal-footer">
<button id="btnAddConditions" type="button" class="btn btn-primary">Add Conditions</button>
<button id="btnNoConditions" type="button" class="btn btn-primary" >No Conditions</button>
<button data-dismiss="modal" type="button" class="btn btn-default">Cancel</button>
</div>
</div>
</div>
</div>
</body>
Ajax:
<script type="text/javascript">
var checkConditon;
$(document).ready(function(){
$(".confirmItem").click(function (e) {
checkConditon = $(this).data('id');
alert("confirm item " + $(this).data('id'));
});
$('#btnAddConditions').click(function () {
alert("add condition " + $(this).data('id'));
window.location = "/RequestedBurns/AddCondition/" + checkConditon;
});
$('#btnNoConditions').click(function () {
$.ajax({
type: "POST",
url: "Create",
success: function (){
alert("success")
},
error: function (error) {
alert("Error Ajax not working: " + error);
}
});
});
});
</script>
tried below code to call controller actions from ajax in MVC.
var checkConditon = $(".confirmItem").data('id');
var url = '#Url.Action("AddCondition", "RequestedBurns")';
$.ajax({
url: url,
type: "POST",
data: { checkConditon : checkConditon },
success: function (data) {
alert('success');
},
error: function (error) {
alert("Error Ajax not working: " + error);
}
});

Close ui-bootstrap modal with mouse click with no backdrop

I'm currently migrating ui-bootstrap from 0.5.0 to 0.14.3 (yep, I haven't checked for updates for that long). In 0.5.0 there was a 'modal' directive with the 'options' config object. There was a 'backdropClick' option, which allowed the modal to be closed when mouse-clicked outside of it. In 0.14.3 the $uibModal service doesn't have such option. It has a 'backdrop' property, which could be set to 'static', allowing you to close the modal with a mouse click, but the modal has a backdrop. And what if it hasn't? Could I close it with a mouse click with 'backdrop' property set to 'false'?
There is a workaround for this missing feature.
You can use a directive to detect a "click outside" event and then in the related event call the close modal method.
In the example below (adapted from ui.bootstrap docs) I used angular-click-outside directive:
angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap','angular-click-outside']);
angular.module('ui.bootstrap.demo').controller('ModalDemoCtrl', function ($scope, $uibModal, $log, $document) {
$scope.items = ['item1', 'item2', 'item3'];
$scope.animationsEnabled = true;
$document.on('click', function(event) {
});
$scope.open = function (size) {
var modalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModalContent.html',
controller: 'ModalInstanceCtrl',
backdrop: false,
size: size,
resolve: {
items: function () {
return $scope.items;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
$scope.toggleAnimation = function () {
$scope.animationsEnabled = !$scope.animationsEnabled;
};
});
// Please note that $modalInstance represents a modal window (instance) dependency.
// It is not the same as the $uibModal service used above.
angular.module('ui.bootstrap.demo').controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$uibModalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
<!doctype html>
<html ng-app="ui.bootstrap.demo">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-1.0.3.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<script src="//rawgit.com/IamAdamJowett/angular-click-outside/master/clickoutside.directive.js"></script>
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div id="my-modal" click-outside="cancel()">
<div class="modal-header">
<h3 class="modal-title">I'm a modal!</h3>
</div>
<div class="modal-body">
<ul>
<li ng-repeat="item in items">
{{ item }}
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</div>
<div class="modal-footer">
<button class="btn btn-primary" type="button" ng-click="ok()">OK</button>
<button class="btn btn-warning" type="button" ng-click="cancel()">Cancel</button>
</div>
</div>
</script>
<button type="button" class="btn btn-default" ng-click="open()">Open me!</button>
<button type="button" class="btn btn-default" ng-click="open('lg')">Large modal</button>
<button type="button" class="btn btn-default" ng-click="open('sm')">Small modal</button>
<button type="button" class="btn btn-default" ng-click="toggleAnimation()">Toggle Animation ({{ animationsEnabled }})</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>
</body>
</html>

jQuery Mobile collapsible panel and KNockjs observable array

Can someone help me to figure out why my collapsible panel won't expand? My html markup with jquery mobile appears to be working. The data gets bound to the collapsible set via a foreach loop, but the panels will not expand.
html:
<div data-role="collapsible-set" class="ui-block-a" data-bind="foreach: opportunityData">
<div data-collapsed="true" data-role="collapsible" >
<h3>
<span data-bind="text: name" />
</h3>
<p data-bind="text: company" />
</div>
</div>
JS:
function OpportunityViewModel() {
var self = this;
self.opportunityData = ko.observable([]);
$.ajax({
url: 'url....',
type: 'GET',
async: true,
cache: false,
crossDomain: true,
dataType: 'jsonp',
success: function (data) {
self.opportunityData(data)
},
error: function (jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
}); //end ajax call
}; //end viewmodel
ko.applyBindings(new OpportunityViewModel());
});
I just found the solution, just create a new out side div then put foreach in that div:
<div data-bind="foreach: opportunityData">
<div data-role="collapsible-set" class="ui-block-a" >
<div data-collapsed="true" data-role="collapsible" >
<h3>
<span data-bind="text: name" />
</h3>
<p data-bind="text: company" />
</div>
</div>
</div>

Resources