No result appear in the autocomplete - jquery-ui

The action return a JSonResult and the content is correct. I missed something in the autocomplete code ?
HTML :
<input type="text" class="span12" id="mytextbox" />
The javascript :
<script>
$(document).ready(function () {
$("#mytextbox").autocomplete({
minLength: 2,
source: function(request,response) {
$.ajax({
url: "MyController/MyAction",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { firstname: item.FirstName, lastname: item.LastName, code: item.Code };
}))
}
})
},
messages: {
noResults: "", results: ""
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.firstname + "<br>" + item.lastname + "</a>")
.appendTo(ul);
};
})
</script>

The next code works, where availableTags replace your ajax.
<script>
$(document).ready(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC"];
$("#mytextbox").autocomplete({
minLength: 2,
source: availableTags,
messages: {
noResults: "", results: ""
}
}).data("ui-autocomplete").renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.firstname + "<br>" + item.lastname + "</a>")
.appendTo(ul);
};
});
</script>
This might be helpful: http://api.jquery.com/jQuery.data/#jQuery-data-element
Update:
The problem is this line:
.data("ui-autocomplete").renderItem = function (ul, item) {
you got
.data("ui-autocomplete").**_**renderItem = function (ul, item) {

Related

select2+ASP.NET+MVC set values back to dropdown in edit mode

i am using select2 plugin with ASP.NET+MVC with multiple select option. i am able to save values into database of selected item. now I want to show those values (basically text which associate with those saved ids) into dropdown which has select2 plugin in edit mode.
how can i do that. below is my code.
$(document).ready(function () {
/* below values want to set to dropdown list
var selectedValue1 = '43,48,47,57';
$('#ddlCity1').select2({
multiple: true,
placeholder: "Select City",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
dataType: 'json',
delay: 250,
url: '#Url.Action("GetCityList", "DemoMVC")',
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.City
});
});
return { results: newData };
},
cache: true
},
formatResult: function (element) {
return element.text + ' (' + element.id + ')';
},
formatSelection: function (element) {
return element.text + ' (' + element.id + ')';
},
escapeMarkup: function (m) {
return m;
},
});
$(".city1").on("select2:select", function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
$('.city1').on('select2:unselect', function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
});
//Dropdown with select2 control
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>City</label>
<select id="ddlCity1" class="city1" style="width:500px"></select>
</div>
</div>
</div>

set value to select2 dropdown which retrieved from database in ASP.NET MVC

<script type="text/javascript">
$(document).ready(function () {
//following values i retrived from database and i want to display into select2 dropdown
var selectedValue1 = '43,48,47,57';
$('#ddlCity1').select2({
minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: true,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%",
ajax: {
dataType: 'json',
delay: 250,
url: '#Url.Action("GetCityList", "DemoMVC")',
data: function (params) {
return {
searchTerm: params.term
};
},
processResults: function (data) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
//id part present in data
id: item.Id,
//string to be displayed
text: item.City
});
});
return { results: newData };
},
cache: true
},
});
$(".city1").on("select2:select", function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
$('.city1').on('select2:unselect', function (e) {
currentSelectedVal = $(e.currentTarget).val();
console.log(currentSelectedVal) // get selected values
});
});
//Dropdown with select2 control
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>City</label>
<select id="ddlCity1" class="city1" style="width:500px"></select>
</div>
</div>
</div>
i assume that this action "GetCityList" returned json
$('#ddlCity1').select2({ minimumInputLength: 0, //for listing all records > set 0
maximumInputLength: 20, //only allow terms up to 20 characters long
multiple: true,
placeholder: "Select",
allowClear: true,
tags: false, //prevent free text entry
width: "100%"
});
function ("/DemoMVC/GetCityList", {}, "json", success, falier) {
$.ajax({
url: url,
data: paramters,
contentType: "application/json; charset=utf-8",
dataType: returnFormat,
success: function (data) {
success(data);
let htmlData = "<option value='' selected disabled hidden>Select City...</option>";
for (let i = 0; i < Object.values(data)[1].length; i++) {
htmlData = htmlData + Template(Object.values(data)[1][i]);
}
$("#ddlCity1").html(htmlData);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText + ': ' + xhr.responseText + ': ';
console.log('Error - ' + errorMessage);
},
type: 'GET',
});
}
function Template(item) {
let itemHtml = "<option value='" + item.id + "'>" + item.city + "</option>";
return itemHtml;
}

React-rails- Invariant Violation: traverseParentPath(...): Cannot traverse from and to the same ID Error in setState

require('./SliderBox');
window.FullPage = React.createClass({
propTypes: {
items: React.PropTypes.object,
},
getInitialState:function(){
return{
layout : [],
items: []
}
},
leaveBox : function(){
var newItem = this.state.layout[this.state.index];
//ar newItems = this.state.items.push(newItem);
var newIndex = this.state.index + 1;
this.setState({items:this.state.items.concat(newItem) ,index : newIndex })
},
getLayout : function(){
$.ajax({
url:"url.com",
headers: { 'Access-Control-Allow-Origin': '*' },
type:'GET',
dataType: 'json',
crossDomain: true,
cache: false,
success: function(data) {
this.setState({layout: data});
this.setState({items :this.state.items.concat(data[0]), index: 1 })
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
componentWillMount:function(){
this.getLayout();
},
componentDidMount: function(){
},
loadMoreContents:function(){
var url = "SomeLink.com"
},
handleLeave : function(){
this.leaveBox();
},
render: function(){
var j = 1;
var k = 0;
if(this.state.index != 1){
var sliderItems = this.state.items.map(function(item){
return(
<div> <SliderBox key={item.position}
title={item.name}
url={ "url"
exit= {this.handleLeave.bind(this)}
first= {k}
/> </div> )
},this);
return(
<div> {sliderItems} </div>
)
}else {
if(this.state.layout.length > 0 ){
return(<div> <SliderBox key={this.state.layout[0].position}
title={this.state.layout[0].name}
url={ "url"}
exit= {this.handleLeave.bind(this)}
first= {j}
/>
</div>
)}else
{
return(<div></div>)
}
}
}
});
module.exports = FullPage;
So basically my error comes at the this.setState , please help thanks.The traverse path error occurs only when i Integrate with Rails. it works perfect with normal react. wHile using react-rails this error occurs

Reusable jquery ajax requests

I am developing a web application using asp.net mvc... I am listing out the details of Clients,Staff,Reports via ajax requests using jquery... What i am doing is writing seperate functions(jquery ajax requests) for each actions (ie) view,add,edit,Delete ...
//Clients
function getClients(currentPage) {
$.ajax({
url: "Clients/GetClients",
data: { 'currentPage': (currentPage + 1), 'pageSize': 5 },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
if (data.isRedirect && data.isRedirect === true) {
alert('must redirect to ' + data.redirectUrl);
location = 'http://www.google.com';
}
else {
var divs = '';
$("#hfId").val('');
$("#ResultsDiv").empty();
$.each(data.Results, function() {
divs += '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + this.ClientName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No :</span> <span class="resultfieldvalues">' + this.ClientMobNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + this.ClientId + ' onclick="storeIds();"/></span><br/><br/><span class="resultfields">Address :</span> <span class="resultfieldvalues">' + this.ClientAddress + '</span></div>';
});
$("#ResultsDiv").append(divs);
$(".resultsdiv:even").addClass("resultseven");
$(".resultsdiv").hover(function() {
$(this).addClass("resultshover");
}, function() {
$(this).removeClass("resultshover");
});
$("#HfId").val("");
$("#HfId").val(data.Count);
}
}
});
return false;
}
//Drivers
function getDrivers(currentPage) {
$.ajax({
url: "Staff/GetDrivers",
data: { 'currentPage': (currentPage + 1), 'pageSize': 5 },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
if (data.isRedirect && data.isRedirect === true) {
alert('must redirect to ' + data.redirectUrl);
location = 'http://www.google.com';
}
else {
var divs = '';
$("#hfId").val('');
$("#ResultsDiv").empty();
$.each(data.Results, function() {
divs += '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + this.DriverName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No :</span> <span class="resultfieldvalues">' + this.DriverMobileNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + this.DriverId + ' onclick="storeIds();"/></span></div>';
});
$("#ResultsDiv").append(divs);
$(".resultsdiv:even").addClass("resultseven");
$(".resultsdiv").hover(function() {
$(this).addClass("resultshover");
}, function() {
$(this).removeClass("resultshover");
});
$("#HfId").val("");
$("#HfId").val(data.Count);
}
}
});
return false;
}
//get client by id
function getClientbyId(clientId) {
$.ajax({
url: "Clients/getClientById",
data: { 'clientId': clientId },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
$("#Name").val(data.ClientName);
$("#MobileNo").val(data.ClientMobNo);
$("#Address").val(data.ClientAddress);
$("#hfEditId").val(data.ClientId);
$("#adddiv").show();
$("#ResultsDiv").hide();
$("#PagerDown").hide();
$("#ImageButtonDiv").hide();
}
});
return false;
}
//get driver by id
function getDriverById(driverId) {
$.ajax({
url: "Staff/getDriverById",
data: { 'driverId': driverId },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
$("#Name").val(data.DriverName);
$("#MobileNo").val(data.DriverMobileNo);
$("#hfEditId").val(data.DriverId);
$("#adddiv").show();
$("#ResultsDiv").hide();
$("#PagerDown").hide();
$("#ImageButtonDiv").hide();
}
});
return false;
}
//clients delete
function deleteClients(clientIds) {
$.ajax({
url: "Clients/deleteClients",
data: { 'ids': clientIds },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
if (data.Result == "Success") {
getClients(0);
var maxvalues = $("#HfId").val();
$(".pager").pagination(maxvalues, {
callback: getClients,
current_page: 0,
items_per_page: 5,
num_display_entries: 5,
next_text: 'Next',
prev_text: 'Prev',
num_edge_entries: 1
});
return false;
}
}
});
$("#alert").remove();
topBar('successfully deleted');
return false;
}
//delete drivers
function deleteDrivers(driverIds) {
$.ajax({
url: "Staff/deleteDrivers",
data: { 'ids': driverIds },
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
success: function(data) {
if (data.Result == "Success") {
getDrivers(0);
var maxvalues = $("#HfId").val();
$(".pager").pagination(maxvalues, {
callback: getDrivers,
current_page: 0,
items_per_page: 5,
num_display_entries: 5,
next_text: 'Next',
prev_text: 'Prev',
num_edge_entries: 1
});
return false;
}
}
});
$("#alert").remove();
topBar('successfully deleted');
return false;
}
How to make these functions into a single function and just pass the values to the function... Is there way to do this...
As all your functions have similar AJAX setup options I would recommend you to setup common options globally using the $.ajaxSetup function:
$(function() {
$.ajaxSetup({
contentType: 'application/json; charset=utf-8',
global: false,
async: false,
dataType: 'json',
beforeSend: function() { $('.loading').show(); },
complete: function() { $('.loading').hide(); },
});
});
Next let's first consider the getClients and getDrivers functions. Those look pretty much the same. The only difference I can see between them is the url you are sending the AJAX request and the html that's being appended to the #ResultsDiv. So you could have two separate functions that handle the result:
function formatDriversResult(result) {
return '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + result.DriverName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No :</span> <span class="resultfieldvalues">' + result.DriverMobileNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + result.DriverId + ' onclick="storeIds();"/></span></div>';
}
and
function formatClientsResult(result) {
return '<div class="resultsdiv"><br /><span style="display: inline-block;width:220px;" class="resultName">' + result.ClientName + '</span><span class="resultfields" style="padding-left:10px;">Mobile No :</span> <span class="resultfieldvalues">' + result.ClientMobNo + '</span><span style="float:right; padding-right:2px;"><input type="checkbox" value=' + result.ClientId + ' onclick="storeIds();"/></span><br/><br/><span class="resultfields">Address :</span> <span class="resultfieldvalues">' + result.ClientAddress + '</span></div>';
}
And finally the two functions could be merged into a single one:
function getEntities(url, currentPage, formatResultFunction) {
$.ajax({
url: url,
data: { 'currentPage': (currentPage + 1), 'pageSize': 5 },
success: function(data) {
if (data.isRedirect && data.isRedirect === true) {
alert('must redirect to ' + data.redirectUrl);
location = 'http://www.google.com';
}
else {
var divs = '';
$("#hfId").val('');
$("#ResultsDiv").empty();
$.each(data.Results, function() {
divs += formatResultFunction(this);
});
$("#ResultsDiv").append(divs);
$(".resultsdiv:even").addClass("resultseven");
$(".resultsdiv").hover(function() {
$(this).addClass("resultshover");
}, function() {
$(this).removeClass("resultshover");
});
$("#HfId").val("");
$("#HfId").val(data.Count);
}
}
});
return false;
}
Now when you want to get the current clients:
var clients = getEntities("Clients/GetClients", currentPage, formatClientsResult);
and when you want to get the current drivers:
var drivers = getEntities("Staff/GetDrivers", currentPage, formatDriversResult);
Next let's consider the getClientbyId and getDriverById functions. They could be simplified to:
function getEntityById(data, url, formatResultFunction) {
$.ajax({
url: url,
data: data,
success: function(data) {
formatResultFunction(data);
$("#adddiv").show();
$("#ResultsDiv").hide();
$("#PagerDown").hide();
$("#ImageButtonDiv").hide();
}
});
return false;
}
The same pattern could be used for the rest.

Jquery UI autocomplete event change

Hi I got a problem with change event.
By documntation there should be object ui.item
After an item was selected; ui.item refers to the selected item. Always triggered after the close event.
But when I try it ui.item is undefined :( I want unset s_town_id when input in autocomplete doesn't match with data from script.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
// ui.item is undefined :( where is the problem?
$("#s_town_id").val(ui.item.id);
}
});
});
I find out solution where I testing event.originalEvent.type if it is meneuselected or not and after fail I unset s_town_id. But any better solution is still wellcome.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
try
{
if(event.originalEvent.type != "menuselected")
{
// Unset ID
$("#s_town_id").val("");
}
}
catch(err){
// unset ID
$("#s_town_id").val("");
}
}
});
});
if ui.item is not defined that means your json source is not well formed.
You have to send a json source like this:
[{"label":"Jean","value":1},{"label":"carl","value":2}]
You can add more key to the array but at least you have to set "label" and "value".
Check the json string.
Also I reckon you to use the last version of autocomplete 1.8.1 at the moment

Resources