jQuery autocomplete completely unresponsive - asp.net-mvc

This is my first time really delving into jQuery with my ASP MVC3 intranet app. I need the autocomplete to be able to reference a list of items from a database. I followed the tutorial found here and thought "ok, that looks easy"... and now after implementing the code and researching other methods and bashing my head against the keyboard for at least four hours I'm not anywhere closer to making this work that before I wrote the code.
Here is the code from the view, w/the library declarations as well. FYI - I am taking over this project, so all the other javascript/Ajax you see was written by someone else with more experience than me. I put all the code in this section just in case something else is getting in the way.
<link href="../../Content/jquery-ui-1.9.2.custom.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#BankName").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1
});
$(function () {
$("#drpProducerType").change(function () {
var value = $(this).val();
if (value == "SoleProprietor") {
$("#Role").val(value);
$('#DSSfields').removeClass('noSee');
$('#DSSfields').addClass('seeMe');
//alert("Role must be set to \"Sole Proprietor\" as well. Monet will do this for you!");
}
else {
//TO DO: add role stuff here as well
$('#DSSfields').removeClass('seeMe');
$('#DSSfields').addClass('noSee');
}
});
$("#Role").change(function () {
var value = $(this).val();
if (value == "SoleProprietor") {
$("#drpProducerType").val(value);
alert("Producer Type changed to \"Sole Proprietor\" as well");
}
});
});
function ChangeChannel() {
//this function called if Market Segment changes, to update the channel
var pendistcode = document.getElementById('Pendist');
if (pendistcode == null) alert('Error: Cannot find Market Segment control');
$.ajax({
type: 'POST',
url: '/AgentTransmission/GetChannel/',
data: { pendist: pendistcode.value },
success: function (data) {
// alert("success: " + data);
$('#channelName').html(data);
$('#Channel').val(data);
},
error: function (data) {
alert("failure to obtain Channel name");
}
});
CheckTerritory('channel');
} //end ChangeChannel
function CheckTerritory(category) {
//this function called when changes happen that could change the territory (inddist)
//if the channel changed, or the alignment indicator, update the Territory
if ((category == "channel") | (category == "align")) UpdateTerritory();
//only trigger if the state or zip changed on the aligned address
if ((category == "L") && ($('#AlignmentL').attr('checked'))) UpdateTerritory();
if ((category == "M") && ($('#AlignmentM').attr('checked'))) UpdateTerritory();
} //end CheckTerritory
function UpdateTerritory() {
var i = $('#INDDist').val();
var p = $('#Pendist').val();
// alert(":" + i + ":" + p + ":");
//if ((i == "") || (p == "")) return;
if (p == "") return;
if ($('#INDDist').val() == "864") {
$('#INDDist').val("701");
}
else {
if ($('#INDDist').val() == "") {
$('#INDDist').val("864");
}
}
} //end UpdateTerritory
function MoreCompanies(row) {
//if the user clicks on the plus sign, add more company rows
if (row == '3') {
$('#plus2').html(' ');
$('#row3').removeClass('noSee');
$('#row3').addClass('seeMe');
}
if (row == '4') {
$('#plus3').html(' ');
$('#row4').removeClass('noSee');
$('#row4').addClass('seeMe');
}
if (row == '5') {
$('#plus4').html(' ');
$('#row5').removeClass('noSee');
$('#row5').addClass('seeMe');
}
} //end MoreCompanies
function CompanyFields() {
} //end CompanyFields
function ShowHideTerritory() {
alert('sunshine');
} //end ShowHideTerritory
</script>
The text box the autocomplete is supposed to work on
<div class="M-editor-label">
Bank\Agency Name
</div>
<div class="M-editor-field">
#Html.TextBoxFor(model => model.BankName, new { id = "BankName" })
#Html.ValidationMessageFor(model => model.BankName)
</div>
and here is the GetBanks method from the controller. I've set a breakpoint at the first line of this method and I've never been able to get it to hit.
//GET
public JsonResult GetBanks(string search)
{
var banks = from c in db.BankListMaster.Where(n => n.BankName.Contains(search))
select c.BankName;
banks = banks.Distinct();
return Json(banks, JsonRequestBehavior.AllowGet);
}
EDIT
If I replace the current .autocomplete code with the code suggested by this method instead , I get the following error in Chrome's debugger:
Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method '/AgentTransmission/GetBanks'
Here's the new code, I put it in the exact same spot as what I was previously using:
$(document).ready( function() {
$('#BankName').autocomplete('#Url.Action("GetBanks", "AgentTransmission")', {
dataType: 'json',
parse: function(data) {
var rows = new Array();
for(var i=0; i<data.length; i++){
rows[i] = { data:data[i], value:data[i].BankName };
}
return rows;
},
formatItem: function(row, i, n) {
return row.BankName + ' - ' + row.Description;
},
width: 300,
mustMatch: true,
});
});

I added an extra set of closing brackets to the autocomplete which cleared this up. The widget functions properly now.
$(function () {
$("#BankNameAuto").autocomplete({
source: '#Url.Action("GetBanks", "AgentTransmission")',
minLength: 1
});
});

Related

Drag and Drop between Two lists (List 2 only has sort)

I am struggling to get the required functionality from my current code.
Two Lists (grid style) List 1 - List 2
List 1 items are draggable to list 2, NOT sortable, cloned (but then disabled as you can only add item once)
List 2 droppable, you can sort, entire item html copies over from list 1.
Code Pen script
$(function () {
$('.box').draggable({
appendTo: "body",
helper: "clone"
});
$("#sortable2").droppable({
activeClass: "ui-state-default",
hoverClass: "ui-state-hover",
accept: ":not(.ui-sortable-helper)",
drop: function (event, ui) {
//add first element when cart is empty
if ($(this).find('.placeholder').length > 0) {
$(this).find('.placeholder').remove();
$("<li></li>").text(ui.draggable.text()).appendTo(this);
} else {
//used as flag to find out if element added or not
var i = 0;
$(this).children("li").each(function () {
if ($(this).offset().top >= ui.offset.top) {
//compare
$("<li class='box'></li>").text(ui.draggable.text()).insertBefore($(this));
i = 1;
return false; //break loop
}
});
if (i !== 1) {
//if element dropped at the end of cart
$("<li class='box'></li>").text(ui.draggable.text()).appendTo(this);
}
}
}
})
$(function() {
$( "#sortable2" ).sortable({
placeholder: "highlight",
items: "li:not(#sortable1)",
sort: function () {
$(this).removeClass("ui-state-default");
}
});
});
});
//Display action in text
$(function DisplayWhatDropped() {
var area = "Area Dropped";
var item = "fId of the item";
$(".result").html(
"[Action] <b>" + item + "</b>" + " dropped on " + "<b>" + area + "</b>"
);
});
Any assistance would be greatly appreciated.

How to refresh the bootstrap multiselect checkbox and maintain original values of checkbox?

I am trying to refresh a bootstrap 3.0 multiselect control.
On refresh, I want to reset the checkboxes to its previous state when the partial view was first rendered
How can I achieve that?
I tried following approach but didn't get success.
Maintained hidden field for storing selected checkbox values once view
was rendered.
On Reset button click:
2.1 Uncheck all checkboxes.
2.2 Check only those checkboxes whose value I got from hidden field.
j('#btnReset11').click(function () {
j("#divErrorMessage ul li").not(':first').remove();
j("#divErrorMessage").hide();
j("#divSuccessMessage").hide();
j("#includeSelectAllOption").find("option").removeAttr("selected");
j("#chkRoles ul li").removeClass("active");
j("#chkRoles .btn-group").find("button").removeAttr('title');
j("#chkRoles .btn-group").find("button").text('Select');
var value = j("#selectedCheckboxes").val();
valueItems = value.split(", ");
for (var i = 0; i < valueItems.length; i++) {
j('#' + valueItems[i]).attr('selected', 'selected');
j("#chkRoles ul li input[value=" + valueItems[i] + "]").parent().parent().parent().addClass("active");
var title = j("#chkRoles .btn-group").find("button").title;
j("#chkRoles .btn-group").find("button").removeAttr(title);
}
if (valueItems.length > 0) {
j("#chkRoles .btn-group").find("button").text(valueItems.length + ' selected');
}
else {
j("#chkRoles .btn-group").find("button").text('Select');
}
});
j(document.body).on('click', '#btnReset-Button', function () {
j("#divErrorMessage").hide();
j(this).parents('.PopupModalClass').find('input[type="text"],input[type="email"],select').each(function () {
if (this.defaultValue != '' || this.value != this.defaultValue) {
this.value = this.defaultValue;
setTimeout(function () {
j('.PopupModalClass #multiSelectDropdown').multiselect('refresh');
});
} else { this.value = ''; }
});
});

ASP.NET MVC Jquery Ajax post form serialize?

Ajax function
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: { model: $(this).serialize(), locations: getCheckedLocation(), reports: getCheckedReports() },
beforeSend: function () {
},
complete: function () {
},
success: function (result) {
$('#user_operations_container').html(result);
setTimeout(function () { LoadAction('#Url.Action("GetAllUsers", "User")') }, 1000);
$("#widgets ul li a").removeClass("link_active");
$("#widgets ul li:first-child a").addClass("link_active");
}
});
}
return false;
});
});
functions that are using in ajax data attribute
function getCheckedLocation() {
var nodes = $('#tt_location').tree('getChecked');
var s = '';
for (var i = 0; i < nodes.length; i++) {
if (s != '') s += ',';
s += nodes[i].text;
}
return s;
}
function getCheckedReports() {
var nodes = $('#tt_reports').tree('getChecked');
var s = '';
for (var i = 0; i < nodes.length; i++) {
if (s != '') s += ',';
s += nodes[i].text;
}
return s;
}
HTML
<div> // there are html helpers for model (dropdownlistfor, textboxfor,...)
</div>
<div> // checkbox tree (#tt_location)
</div>
<div> // checkbox tree (#tt_reports)
</div>
Controller
[HttpPost]
public ActionResult _EditUser(UserViewModel model,string locations,string reports)
{
// model = null
// locations and reports are expected. (not null)
}
Question
Why model is null?
When I use ajax data attribute like this = data: $(this).serialize(), , It works model is not null.
How can I post model, with additional data (locations,reports).
I hope I can explain. Thanks...
Try like this:
data:$('this').serialize() + "&locations=" + getCheckedLocation() "&reports=" + getCheckedReports()
It will work.
Hope it helps

SlickGrid styling after cell edit

I'm using SlickGrid (2.0) dataView with slick.editors. In the Grid, a user can edit any number of cells which then modifies the underlying grid data so that the edits are maintained when the grid scrolls. This works great. But I also want to provide visual feedback for all the edits since these are not saved to the database until user hit "Save Edits" button.
Problem is that the editor method resets the cell after it reads back the changed grid data. I need to maintain a background color change to indicate that it's been edited. Has anyone been able to do this?
Here is the relevent code (simple Integer editor):
function IntegerCellEditor(args) {
var $input;
var defaultValue;
var scope = this;
this.init = function() {
$input = $("<input type=text class='edited' type=text style='font:normal 12px arial; width:95px; text-align:right; border:none;' />");
$input.bind("keydown.nav", function(e) {
if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
e.stopImmediatePropagation();
}
});
$('#saveChanges').removeAttr("disabled"); // remove disabled attribute from "Save Changes" btn
$input.appendTo(args.container);
$input.focus().select();
};
this.destroy = function() {
$input.remove();
};
this.focus = function() {
$input.focus();
};
this.loadValue = function(item) {
defaultValue = item[args.column.field];
$input.val(defaultValue);
$input[0].defaultValue = defaultValue;
$input.select();
};
this.serializeValue = function() {
return parseInt($input.val(),10) || 0;
};
this.applyValue = function(item,state) {
item[args.column.field] = state;
};
this.isValueChanged = function() {
return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
document.getElementsByClassName('ui-widget-content slick-row')[row].className += 'edited';
};
this.validate = function() {
if (isNaN($input.val()))
return {
valid: false,
msg: "Please enter a valid integer"
};
return {
valid: true,
msg: null
};
};
this.init();
}
This line does nothing and I can't figure out how to do this:
document.getElementsByClassName('ui-widget-content slick-row')[row].className += 'edited';
Thanks
I am not an expert in SlickGrid but take a look a Example 14, I think it has similar information that would help you.
My idea would be something like:
subscribe to grid.onCellChange event
store changes in object
use grid.setCellCssStyles('highlight',changes) to update CSS or grid.addCellCssStyles
Hope that helps a little at least.

jquery mobile $.mobile.showpageloadingmsg() is not working

I wish to show loading message during page transition in jQM and backbone. But the showPageLoadingMeassage isnt working.
Following is my code:
collection.js
findById : function(artistId, page, limit, sort) {
$.mobile.showPageLoadingMsg('a', 'Loading......', false);
var self = this;
if (limit == undefined) {
limit = 10;
}
$.mobile.showPageLoadingMsg('a', 'Loading......', false);
console.log("hello");
$.ajax({
type: "GET",
url: siteURL + 'artists/artist_detail/artist_id' + artistId + '.json',
}).done(function(msg) {
var response = JSON.parse(msg);
if (response.status == true) {
var dataArray = response.data;
console.log(dataArray);
self.reset(dataArray);
if (self.length > 0) {
$.mobile.hidePageLoadingMsg();
}
//return dataArray;
} $.mobile.showPageLoadingMsg($.mobile.pageLoadErrorMessageTheme, 'Sorry! No records found', true);
setTimeout(function() {
$.mobile.hidePageLoadingMsg();
}, 1500);
}
});
}
where am i getting wrong?
edited:
it works when for search page:
... findByTitle : function(keyword, genre, language, page, limit, sort, collection, fan, featured) {
//~ console.log(page);
var self = this;
if (limit == undefined) {
limit = 10;
}
$.mobile.showPageLoadingMsg('a', 'Searching......', false);
$.ajax({....
found the answer on stackoverflow itself- jQuery Mobile - Problems getting showPageLoadingMsg to work with pagebeforeshow or pagebeforeceate.
It says that sometimes jQM doesn't adds the ui-loading class to the body so we have to do it manually.
$('body').addClass('ui-loading');
$.mobile.showPageLoadingMsg('a', 'Searching......', false);
and while hiding the loading msg:
setTimeout(function() {
$('body').removeClass('ui-loading'); //remove class
$.mobile.hidePageLoadingMsg();
}, 1000);
This function was also deprecated and in the current versions is not at all.

Resources