twitter bootstrap typeahead not working - javascript

I am working on twitter bootstrap typeahead and i am stuck as i am not getting any error and yet the auto complete is not working.
this is my input field
<input type="text" id="autocomplete" />
and this is my script
<script>
$('#autocomplete').typeahead({
source: function(process) {
var data = <?php Widgets::allProducts() ?>;
process(data);
},
matcher: function(item) {
return
item.name.toLocaleLowerCase()
.indexOf(this.query.toLocaleLowerCase()) != -1;
},
highlighter: function(item) {
return item.name;
},
updater: function (item) {
alert(JSON.parse(item).value);
return JSON.parse(item).name;
}
});
</script>
this is how my var data looks like
var data = [{"name":"Acne.org","id":"5"},{"name":"AcneFree","id":"6"},{"name":"Alpha Hydrox","id":"16"},{"name":"AmLactin","id":"17"},{"name":"Astara","id":"21"}];
What i want to do is get the product name listed (which is name in var data ) and upon selecting the product redirect the user to product page (with the help of product id which i am getting in var data as id).
I am just lost at this stage as i am not getting any error. I will appreciate any push to right direction.

Related

Get all data from gridmvc including all paging in javascript?

I am trying to fetch data from gridmvc and show graphs using chart.js its working fine but issue is that its showing just with pages. Because i have enabled paging in grid and when i click on next page then next grid data page graphs show, but i want to show graph of complete grid data includes all pages.
<div class="panel-body">
#await Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.ID).Titled("StudentID").Filterable(true);
columns.Add(c => c.Name).Titled("Name").Filterable(true);
columns.Add(c => c.Major).Titled("Major").Filterable(true);
columns.Add(c => c.Minor).Titled("Minor").Filterable(true);
columns.Add(c => c.Email).Titled("Email").Filterable(true);
columns.Add(c => c.Address).Titled("Address").Filterable(true);
columns.Add(c => c.GPA).Titled("GPA").Filterable(true);
}).Searchable(true, false, true).WithPaging(10).ChangePageSize(true).Sortable(true).EmptyText("No data found").Named("GridSearch").RenderAsync()
</div>
Javascript
function LoadChart() {
debugger;
var chartType = parseInt($("#rblChartType input:checked").val());
var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
$.each(items, function (i, row) {
$col1=$(row).children()[0].innerText;
$col2 = $(row).children()[1].innerText;
$col3 =$(row).children()[2].innerText;
$col4 =$(row).children()[3].innerText;
$col5 =$(row).children()[4].innerText;
$col6 =$(row).children()[5].innerText;
$col7 =$(row).children()[6].innerText;
json.push({ 'StudentID': $col1, 'Name': $col2, 'Major': $col3, 'Minor': $col4, 'Email': $col5, 'Address': $col6, 'GPA': $col7
})
// Map JSON values back to label array
var labels = json.map(function (e) {
return e.Name;
});
console.log(labels); // ["2016", "2017", "2018", "2019"]
// Map JSON values back to values array
var values = json.map(function (e) {
return e.GPA;
});
var chart=BuildChart(labels, values, "Students Name by GPA");
I want to show graphs which include complete data in gridmvc not just on current page.
but issue is that its showing just with pages. Because i have enabled
paging in grid and when i click on next page then next grid data page
graphs show, but i want to show graph of complete grid data includes
all pages.
var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
$.each(items, function (i, row) {
$col1=$(row).children()[0].innerText;
$col2 = $(row).children()[1].innerText;
$col3 =$(row).children()[2].innerText;
$col4 =$(row).children()[3].innerText;
$col5 =$(row).children()[4].innerText;
$col6 =$(row).children()[5].innerText;
$col7 =$(row).children()[6].innerText;
json.push({ 'StudentID': $col1, 'Name': $col2, 'Major': $col3, 'Minor': $col4, 'Email': $col5, 'Address': $col6, 'GPA': $col7
})
The issue relates the above scripts, since you implement paging, when using the above code to get the table resource, it only gets the current page records, then display the page grahps.
To solve this issue, you could get the records from the page model (Model) or create an action method to get all records, then, use JQuery Ajax method to call this method and get the grid data.
To get records from the page model, in your Asp.net Core MVC application, you could use the Json.Serialize() method to convent the Model to JSON string first, then use JSON.parse() method convent the JSON string to JavaScript Object, then loop through the Object and get all data.
Code like this (Index.cshtml)
#model List<StudentViewModel>
#section Scripts{
<script>
$(function () {
LoadChart();
});
function LoadChart() {
debugger;
//var chartType = parseInt($("#rblChartType input:checked").val());
//var items = $(".grid-mvc").find(".grid-table > tbody").children();
var json = [];
var items = JSON.parse('#Json.Serialize(Model)');
$.each(items, function (index, item) {
json.push({ 'StudentID': item.id, 'Name': item.name, 'Major': item.major, 'Major': item.major, 'Email': item.email, 'Address': item.address, 'GPA': item.gpa });
});
//show graphs based on the json array.
The screenshot like this:

angular js select box item missing after refresh

I trying to set drop-down box display the default item. First, item in drop-down box able to display correctly and I can select the item in order to save into database. Everything working fine, the problem is after I refresh the page, the default item always is empty, it should display the item that I save.
HTML
<select class="form-control" ng-model="sst_type" ng-options="type for type in
sst_types" ng-change="changeSstType(sst_type)"></select>
JS
.controller('sstCtrl', function ($scope, $rootScope, Module, settings,
toastr, actionBar, $uibModal) {
// scope properties
$scope.loading = true;
$scope.sst_types = ['Sotong', 'Bento'];
$scope.sst_all = [];
// scope functions
$scope.getSst = function () {
Module.getSst().then(function (res) {
$scope.loading = false;
if (res.sst_all) {
angular.forEach(res.sst_all, function (v) {
$scope.sst_all.push({
id: v.id,
name: v.name,
value: v.value,
percentage: (v.value * 100).toString(),
type: v.value == 0 ? 'Sotong' : 'Bento'
});
});
}
});
};
You need to return the id of the saved item from server. You can do that in the Module.getSst() call.
In foreach set $scope.sst_type to the matching one.
Good luck

AngularJS - run check against elements as they come back

I just followed this
JSFiddle example to create a little search box from an array object in my javascript. Now after some tweaking and research on search.object and filter:search:strict. Now that I have it filtering correctly, I modified a checkbox in the template that is checked upon loading the document and switched on or off based on a custom data attribute in the html that is updated by the json array.
How do I run this check once someone clears the search and the old items show back up again?
In the HTML I have this template
<div ng-repeat="o in objects | filter:search:strict | orderBy:'obj_name'" class="objectContainer">
<h3>{{o.obj_name}}</h3>
<label class="userToggleSwitch" >
<input class="userToggleInput" data-isactive="{{o.obj_isactive}}" type="checkbox">
<div class="slider round"></div>
</label>
</div>
In the JS
angular.element(document).ready(function(){
angular.module('searchApp',[])
.controller('searchCtrl', ['$scope','objHolder',function ($scope,objHolder) {
$scope.search = '';
$scope.objects = [];
$scope.objects = objHolder.getobjects();
}])
// fake service, substitute with your server call ($http)
.factory('objHolder',function(){
var objects = objList;
return {
getobjects : function(){
return objects;
}
};
});
});
The JS that modifies the items on document load is using jquery like this
$(document).ready(function(){
//console.log($('.userToggleInput'));
$.each($('.userToggleInput'), function(){
if($(this).data("isactive") == 1){$(this).attr('checked', true);}
if($(this).data("isactive") == 0){$(this).attr('checked', false);}
})
$('.userToggleInput').click(function(){
if ($(this).attr('checked') == undefined) {
// THIS IS WHERE WE WILL MAKE AN AJAX CALL TO A PHP CLASS
// TO REQUEST IF THE USER CAN BE TURNED ON - DUE TO LIC RESTRICTIONS
$(this).attr('checked',true);
} else {
$(this).attr('checked',false);
}
//console.log($(this).attr('checked'));
});
});
Created JS Fiddle to assist in Helping in this manner

Updating values being pulled from database using lou jquery multiselect

I am using lou's multiselect.js to update selected values that were previously stored in the database. I am getting the selected values from the database, however it's in the wrong column, as shown below. I would like to retrieve the values from the database that weren't selected(to be on the lef) along with those that have already been selected(to be on the right).
The list of items below(on the left) were already selected items being brought back from the database, but they should be under the Selected Product Types column instead. And then under Available Product Types the list of items that have not been selected as yet should be shown.
HTML
This gets the previously selected products from the database as shown in the picture above
<select multiple id="product-multi-select" name="product-multi-select" ng-model="input_doc_type.product" required>
#foreach($inputDocData[0]->product as $data)
<option value="{{$data->id}}" selected>{{$data->name}}</option>
#endforeach
</select>
JQuery
Gets all the products
<script type="text/javascript">
jQuery(function ($) {
$("#product-multi-select").multiSelect({
selectableHeader: "<div class='custom-header'>Available Product Types</div>",
selectionHeader: "<div class='custom-header'>Selected Product Types</div>"
});
$(document).ready(function() {
var products = [];
$.get('/admin/products/all-products', function(data, response) {
$.each(data, function(index, value) {
products.push(value.name);
});
$("#product-multi-select").multiSelect('select', products);
$(".ms-container").append('<i class="glyph-icon icon-exchange"></i>');
});
});
});
</script>
I'm not sure how to go about using this. Any assistance with this problem would be greatly appreciated.
To solve the problem I had to add an extra function in the js file which supports getting recognizing selected values (shown below). It's a replica of the addOption function that came with the file, but with one slight update.
multiselect.js
'selectedAddOption' : function(options){
var that = this;
if (options.value) options = [options];
$.each(options, function(index, option){
if (option.value && that.$element.find("option[value='"+option.value+"']").length === 0){
var $option = $('<option value="'+option.value+'" selected>'+option.text+'</option>'),
index = parseInt((typeof option.index === 'undefined' ? that.$element.children().length : option.index)),
$container = option.nested == undefined ? that.$element : $("optgroup[label='"+option.nested+"']")
$option.insertAt(index, $container);
that.generateLisFromOption($option.get(0), index, option.nested);
}
})
},
After adding that piece of code to the js file. I then made a request from the database which pulled in all unused products and then dynamically them to the select (shown below). This was added over on the Available Product Types side
// retrieve all products
$.get('/admin/products/all-products', function(data, response) {
$.each(data, function(index, value) {
$('#product-multi-select').multiSelect('addOption', { value: value.id, text: value.name, index: 0 });
});
$("#product-multi-select").multiSelect('refresh');
$(".ms-container").append('<i class="glyph-icon icon-exchange"></i>');
});
Finally, I then made another request which pulled in all products that were already selected, and this utlilized the selectedAddOption which I added to the js file. And these were then also added to the select box, over on the Selected Product Types side
// retrieve all selected products
<?php foreach ($inputDocData[0]->product as $val) { ?>
$('#product-multi-select').multiSelect('selectedAddOption', { value: <?php echo $val->id; ?>, text: '<?php echo $val->name; ?>', index: 0 });
<?php } ?>
$("#product-multi-select").multiSelect('refresh');
$(".ms-container").append('<i class="glyph-icon icon-exchange"></i>');
There are no present because they are dynamically added using jquery.
select multiple id="product-multi-select" name="product-multi-select[]" ng-model="input_doc_type.product" required></select>
The code did what it was supposed to do and there were no duplication of items in the list.
I hope this may become helpful to someone else.

Populate and display an html table based on the values from two dropdown menus

I have two cascading dropdown boxes controlled with JQuery and Ajax objects. The first determines the values in the second. Then, once a selection is made in the second, the values from the two dropdowns would be used to find a record in an SQL table and display the record in an html table.
So far the dropdowns work correctly but I'm having difficulty getting the record from the database and then displaying it on screen. I've done this before by getting the database values, sending them to the view in a Json object, and using an Ajax object to to create the table with Jquery. However, in this case I don't mind if the page reloads and would like to use a simpler method.
What is a simple method of sending two values from two dropdowns to the controller, using those values to find a record in an sql table, sending the values from the record back to the view to be displayed? Also, I don't want anything to be displayed until the second dropdown box has a selection made.
Here is what I have so far:
Controller methods:
List<Car> GetCars()
{
using (var service = new Service())
{
return service.GetCars().OrderBy(x => x.CarName).Select(x => new Car
{
CarId = x.CarId,
CarName = x.CarName
}).ToList();
}
}
List<Color> GetColors(int carId)
{
using (var service = new Services())
{
return service.GetColors(carId).OrderBy(x => x.ColorName).Select(x => new Color
{
ColorId = x.ColorId,
ColorName = x.ColorName
}).ToList();
}
}
[HttpPost]
public ActionResult CurrentSaus(int townCode, int fiscalYear)
{
var colors = GetColors(carId);
return Json(new SelectList(colors, "ColorId", "ColorName"));
}
Jquery methods:
$(document).ready(function () {
$("#Car_CarId").change(function () {
var carId = $(this).val();
var carName = $(":selected", this).text();
// put the car name into a hidden field to be sent to the controller
document.getElementById("Car_CarName").value = carName;
getColors(carId);
})
});
function getColors(carId) {
if (carCode == "") {
$("#Color_ColorId").empty().append('<option value="">-- select color --</option>');
}
else {
$.ajax({
url: "#Url.Action("Colors", "HotWheels")",
data: { colorId: clrId },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred");
},
success: function (data) {
var colors = "";
var numberOfColors = data.length;
if (numberOfColors > 1) {
colors += '<option value="">-- select color --</option>';
}
else {
var colorId = data[0].Value;
var colorName = data[0].Text;
document.getElementById("Color_ColorName").value = colorName;
}
$.each(data, function (i, color) {
colors += '<option value="' + color.Value + '">' + color.Text + '</option>';
});
$("#Color_ColorId").empty().append(colors);
}
});
}
and some of the html:
#Html.HiddenFor(x => x.Car.CarName)
#Html.HiddenFor(x => x.Color.ColorName)
<table>
<tr>
<td> Select Car:</td>
<td style="text-align:left">
#Html.DropDownListFor(
x => x.Car.CarId,
new SelectList(Model.CarList, "CarId", "CarName"),
"-- select town --")
<br />
#Html.ValidationMessageFor(x => x.Car.CarId)
</td>
</tr>
<tr>
<td> Select Color:</td>
<td colspan="4">
#Html.DropDownListFor(
x => x.Color.ColorId,
new SelectList(Model.ColorList, "ColorId", "ColorName"),
"-- select color --")
<br />
#Html.ValidationMessageFor(x => x.Color.ColorId)
</td>
</tr>
</table>
}
The easiest method is to use an old fashion FORM element and POST the values of the two drop downs to an action in your controller. That action would expect a carId and a colorId and use them to retrieve a record from the DB and then pass the result to your 'view' where you would take care of render/display the result.
Of course using this method has some caveats:
The entire page will refresh after a user selects a value from the
second drop down.
You would have to POST the form using JavaScript
when the user picks the second option, or at least enable a button so
the form can be POSTed.
You would have to keep track of the carId and
colorId in your controller and view
Another option is to use AJAX to POST (send to the server) the carId and colorId where and action in a controller will take care of using those parameters to find a record in the DB and then return a JSON object with the result. The response will be handled by a 'success' handler where you will take care parsing the JSON object and add rows to a table.
So if you feel more comfortable working on the server side of the code pick the first option, however if you prefer to use AJAX and do this in the front end use the later.

Categories

Resources