ASP.NET MVC5 Select2 not working - javascript

This is my first message in this forum, thanks in advance for your help and sorry if I make a bigger mistake here.
I'm trying to implement a select2 JQuery autocomplete combobox.
I copy some code and I can't see where is my mistake, but the edit text looks like a normal Edit text instead change as a Select2, the JavaScrypt is not working for some reason.
Here is my code:
The references in my indexcshtml:
<link href="~/Content/css/select2.css" type="text/css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.1.0.js"></script>
<script src="~/Scripts/select2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
my textbox who should be converted in a Combobox like cyndarela !
#using (Html.BeginForm())
{
#Html.TextBoxFor(a => a.SupplierId, new { id = "supplier" }) #Html.ValidationMessageFor(a => a.SupplierId)
<br />
<button type="submit">Submit</button>
}
and at the end my JavaScrypt:
<script >
$(document).ready(function () {
var pageSize = 20;
var optionListUrl = '#Url.Action("GetProducts", "Purchases")';
//Method which is to be called for populating options in dropdown //dynamically
$('#supplier').select2(
{
ajax: {
delay: 150,
url: optionListUrl,
//url: '/Purchases/GetProducts',
dataType: 'json',
data: function (params) {
params.page = params.page || 1;
return {
searchTerm: params.term,
pageSize: pageSize,
pageNumber: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.Results,
pagination: {
more: (params.page * pageSize) < data.Total
}
};
}
},
placeholder: "-- Select --",
minimumInputLength: 0,
allowClear: true,
});
});
</script>
is like #supplier is not working in the script
Thanks for your time guys !

I had the same issue.
The instruction
#Scripts.Render("~/bundles/scripts")
In your layout view includes all your scripts and they sometimes have some instructions that dispose the .send2()
So you can delete that line and just import the scripts .js files that you need including select2.

Related

How to load external JSON data via an ajax call on html page?

I created a dummy JSON file below to test out whether this html page works. How do I load the data via ajax request? The only error I got is
Uncaught ReferenceError: data is not defined.
How do I call this JSON file in my html page? Been trying but to no avail. Got this from view-source if it helps
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Matter Timeline</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<!-- load handlebars for templating, and create a template -->
<script src="dist/handlebars-v4.0.11.js"></script>
<script id="item-template" type="text/x-handlebars-template">
{{target}}
<font color="#229954"><b>{{status_green}}</b></font>
<font color="#A93226"><b>{{status_red}}</b></font>
<br/>
<font size="2" color="#2874A6">{{action}}</font>
<font size="2" color="#2874A6"><i>{{user}}</i></font> <br/>
<span class="tooltip-date">{{datetime}}</span>
</script>
<script src="dist/vis.js"></script>
<link href="dist/vis-timeline-graph2d.min.css" rel="stylesheet" type="text/css" />
<script>
function resettimeline() {
document.location.reload();
};
</script>
</head>
<body>
<p>
<center><h2>Matter Timeline</h2></center>
</p>
<div id="visualization"></div>
<script type="text/javascript">
var groups = new vis.DataSet([
{id: 0, content: 'Process/Task', value: 1},
{id: 1, content: 'Req/Matter/Doc', value: 2}
]);
var source = document.getElementById('item-template').innerHTML;
var template = Handlebars.compile(document.getElementById('item-template').innerHTML);
$.ajax({
url: 'http://127.0.0.1:8887/data.json',
dataType: "json",
success: function(data) {
//handle you data here
}
});
// create visualization
var container = document.getElementById('visualization');
var options = {
// option groupOrder can be a property name or a sort function
// the sort function must compare two groups and return a value
// > 0 when a > b
// < 0 when a < b
// 0 when a == b
groupOrder: function (a, b) {
return a.value - b.value;
},
orientation: {
axis: 'top',
item: 'top'
},
height: "85vh",
template: template
//timeAxis: {scale: 'day', step:3}
};
var timeline = new vis.Timeline(container);
timeline.setOptions(options);
timeline.setGroups(groups);
timeline.setItems(data);
timeline.on('doubleClick', function (properties) {
window.open('the_doc_url',
'newwindow',
'width=1000,height=600');
return false;
});
</script>
<br/>
Fit to Width
</body>
</html>
data.json
{
"data": [
{
id: 1, group: 0,
target: 'Request',
action: 'from',
user: 'SAS',
datetime: '7/10',
title: '<span class="tooltip-date">Date: 7/10/2017 09:00</span><br/>Req ID: R123',
start: new Date(2017,9,7, 9,0,0,0)
},
{
id: 2, group: 0,
target: 'Request',
action: 'by',
user: 'Alice',
datetime: '8/10',
title: '<span class="tooltip-date">Date: 8/10/2017 13:34</span><br/>Req ID: R123',
start: new Date(2017,9,8, 12,30,0,0)
}
]
}
AJAX means "Asynchronous JavaScript And XML", and it seems that you missed the asynch part. The code that is using the "data" variable is outside the callback, then this variable doesn't exist (or its value is undefined).
You need to use the json data after receiving it, something like this (it could probably be cleanup a little bit):
$.ajax({
url: 'http://127.0.0.1:8887/data.json',
dataType: "json",
success: function(data) {
//handle you data here
// create visualization
var container = document.getElementById('visualization');
var options = {
// option groupOrder can be a property name or a sort function
// the sort function must compare two groups and return a value
// > 0 when a > b
// < 0 when a < b
// 0 when a == b
groupOrder: function (a, b) {
return a.value - b.value;
},
orientation: {
axis: 'top',
item: 'top'
},
height: "85vh",
template: template
//timeAxis: {scale: 'day', step:3}
};
var timeline = new vis.Timeline(container);
timeline.setOptions(options);
timeline.setGroups(groups);
timeline.setItems(data.data);
timeline.on('doubleClick', function (properties) {
window.open('the_doc_url',
'newwindow',
'width=1000,height=600');
return false;
});
}
});

Treeview onNodeSelected not firing

Im using the Jon Miles treeview from https://github.com/jonmiles/bootstrap-treeview
I have generated a JSON data structure and the treeview displays nicely, however I cannot make the onNodeSelected event fire.
JS:
<script src="~/Scripts/jquery-3.1.1.js"></script>
<script src="~/Scripts/bootstrap-treeview.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script>
$(function () {
var defaultData = #Html.Raw(broadcaster.GetTreeViewData()); //Getting data from C# data structure
$('#tree').treeview({
color: "#428bca",
data: defaultData,
levels: 2
});
});
$('#tree').treeview({
onNodeSelected: function(event, data) {
alert('selected:')
}});
</script>
HTML:
<li>
<div id="tree"></div>
</li>
edit:
also tried the jQuery on()but no luck - nothing happens.
$('#tree').on('nodeSelected', function(event, data) {
alert('selected:')
you are initializing nodes 2 times..
it should be like this...
$(function () {
var defaultData = #Html.Raw(broadcaster.GetTreeViewData()); //Getting data from C# data structure
$('#tree').treeview({
color: "#428bca",
data: defaultData,
levels: 2,
onNodeSelected: function(event, data) {
alert('selected:')
}
});
});

Merging two json file and using it in autocoplete plugin

I am trying to merge two JSON file and using it in autocompleteplugin.
But I do get an error TypeError: $(...).easyAutocomplete is not a function even I have added js library for both auto complete and jquery.
My code look like this:
<script src="jquery-3.1.0.js"></script>
<link href="easy-autocomplete.min.css" rel="stylesheet" />
<script src="jquery.easy-autocomplete.min.js"></script>
<script>
$.getJSON("file1.json", function (data1) {
$.getJSON("file2.json", function (data2) {
var final = $.extend({}, data1, data2);
var options = {
data: final,
getValue: "name",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options); $('div.easy-autocomplete').removeAttr('style');
});
});
</script>
I made a working example based on your code.
Please check you have the correct paths when you include the script files. And also check if jQuery is included.
Hope will help you:
$.getJSON("https://api.myjson.com/bins/42jd0", function (data1) {
$.getJSON("https://api.myjson.com/bins/5bjqc", function (data2) {
var final = [];
final.push(data1.employees1);
final.push(data2.employees2);
var new_final = final[0].concat(final[1]);
var options = {
data: new_final,
getValue: "firstName",
list: {
match: {
enabled: true
}
},
theme: "square"
};
$("#KUNDE").easyAutocomplete(options); $('div.easy-autocomplete').removeAttr('style');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/easy-autocomplete.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/easy-autocomplete/1.3.5/jquery.easy-autocomplete.min.js"></script>
<div class='easy-autocomplete'>
<input id="KUNDE"/>
</div>
You can run the code here by hitting the Run code snippet button or you can also check the jsfiddle I've made here.

React table rows population issue

I am trying to generate an html table based on a Rest web service call using React. Only table header was displayed. The table rows are blank. If I debug it, after line
tableModel.rows = this.state.rows;
tableModel.rows was 'undefined'.
I counldn't figure out what's the issue.
<!DOCTYPE html>
<html>
<head>
<title>React Flux</title>
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="container" style="color:red"></div>
<script type="text/jsx">
var tableModel = {
cols: ["id", "name"],
rows: [],
}
var Table = React.createClass({
getInitialState: function () {
return {text: ''};
},
componentDidMount: function(){
$.ajax({
url: "http://localhost:8080/rest/user/findAll"
}).then(function(data) {
this.setState({
rows: data});
}.bind(this))
},
render: function() {
tableModel.rows = this.state.rows;
var _self = this;
var thead = React.DOM.thead({},
React.DOM.tr({},
this.props.cols.map(function (col) {
return React.DOM.th({}, col);
})));
var tbody = this.props.rows.map(function (row) {
return React.DOM.tr({},
_self.props.cols.map(function (col) {
return React.DOM.td({}, row[col] || "");
}));
});
return React.DOM.table({}, [thead, tbody]);
}
});
React.render(<Table cols={tableModel.cols} rows={tableModel.rows} />, container);
</script>
</body>
</html>
When your Table setState, it's render function will be recall, but why do you think it's props would be repopulate? It stay the same, mean Table this.props.rows === []. You could fix it by put the tableModel into Table state and using this.state instead of this.props, or wrap another class to Table to manage data fetching and populate data to Table class.

Kendo UI Mobile List View example not working with my code

Background: With some help (#korchev) I was able to figure out how to use JSONP to bind data to a template. (see this and this question). However, I wanted to be able to make the data displayed in a kendo UI Mobile List view as mentioned in the Kendo Docs.
Unfortunately, the mobile-list view example, uses arrays of data coded in the html which is unlike jsonp.
Also, I notice that the official mobile list-view example leaves this out : <script type="text/x-kendo-template" id="template">. And that is a problem because my code relies on that implementation.
Summary: I am new to the kendo UI mobile framework, and I don't understand how to use my existing code to yield a mobile list view. Sometimes I find the documentation confusing, and I would please like somebody to assist.
My code:
<div id="products"></div>
<script type="text/x-kendo-template" id="template">
<div class="product">
<p>#:title#</p>
<p>#:content#</p>
<p>#= author.slug #</p>
</div>
</script>
<script>
$(function() {
var template = kendo.template($("#template").html());
var dataSource = new kendo.data.DataSource({
schema: {
data: function(response) {
return [response.post];
}
},
transport: {
read: {
url: "http://www.techhelix.com/?json=get_post&id=1/",
dataType: "jsonp"
}
},
requestStart: function() {
kendo.ui.progress($("#products"), true);
},
requestEnd: function() {
kendo.ui.progress($("#products"), false);
console.log(JSON.stringify(dataSource, null, 4));
},
change: function() {
$("#products").html(kendo.render(template, this.view()));
}
});
dataSource.read();
});
</script>
Daniel, I would first start out with the Kendo Mobile List View example and get that working.
Once that works, you can do the following to bind to your datasource and template.
function mobileListViewDataBindInitGrouped() {
...Code for getting your dataSource here...
$("#products").kendoMobileListView({
dataSource: dataSource,
template: kendo.template($("#template").html()),
fixedHeaders: true
});
}
You just need to bind the list view to your data source. Here is a quick example:
<div data-role="view">
<ul data-role="listview"
data-source="myDataSource"
data-template="template"></ul>
<script type="text/x-kendo-template" id="template">
<div class="product">
<p>#:title#</p>
<p>#=content#</p>
<p>#= author.slug #</p>
</div>
</script>
</div>
<script>
var myDataSource = new kendo.data.DataSource({
schema: {
data: function(response) {
return [response.post];
}
},
transport: {
read: {
url: "http://www.techhelix.com/?json=get_post&id=1/",
dataType: "jsonp"
}
}
});
var application = new kendo.mobile.Application();
</script>
Also available live: http://jsbin.com/nisuzapu/1/edit

Categories

Resources