How to refresh the bootstrap multiselect checkbox and maintain original values of checkbox? - asp.net-mvc

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 = ''; }
});
});

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.

jQuery ui- creating a handle for selectable

I'm looking to combine sortable and selectable and want to create something something similar to handle for selectable. So in other words, if I have a list and a div inside the list elements I would be able to select the list item by just clicking on the div. So just like the handle option for sortable.
Sortable code:
$("#list3").sortable({
handle:'.PageTreeListMove',
connectWith: ".droptrue",
helper: function (e, li) {
this.copyHelper = li.clone().insertAfter(li);
$(this).data('copied', false);
return li.clone();
},
stop: function () {
var copied = $(this).data('copied');
if (!copied) {
this.copyHelper.remove();
}
this.copyHelper = null;
}
});
$("#list4").sortable({
dropOnEmpty: true,
receive: function (e, ui) {
var i=0;
ui.sender.data('copied', true);
ui.item.html('' + ui.item.text() + '<span class="PageTreeListDelete"> </span>');
ui.item.attr('id',ui.item.id);
ui.item.removeAttr('style');
ui.item.addClass("added");
var identicalItemCount = $("#list4").children('li#'+ui.item.attr('id')).length;
if (identicalItemCount > 1) {
$("#list4").children('li#'+ui.item.attr('id')).first().remove();
}
}
}).disableSelection();
**Selectable code:
$("#list3").selectable({
selecting: function(e, ui) {
var curr = $(ui.selecting.tagName, e.target).index(ui.selecting);
selectedItems.push("<li id="+$(ui.selecting).attr('id')+" class='added'><a href>"+$(ui.selecting).text()+"</a><span class='PageTreeListDelete'> </span></li>");
if(e.shiftKey&&prev>-1) {
$(ui.selecting.tagName, e.target).slice(Math.min(prev, curr), 1 + Math.max(prev, curr)).addClass('ui-selected');
} else {
prev = curr;
}
},
cancel:'ui-selected'
});

jQuery UI menu inside a jqGrid cell

I have created a grid and customized a column to contain a jquery UI menu like in the Split Button example
Everything works fine except for the fact that the menu window appear inside the cell causing a bad visual effect, that is, the cell height increase to make room for the menu window.
Have a look at the following screenshot for a visual explanation (nevermind about the menu item in disabled state).
Is there any way way to make the menu window appear on top of the table element in term of z-index?
Thanks very much for your valuable help, community :)
EDIT as per comment request:
The code to create the splitbutton menu is the following. First the column model markup
{ name: 'act', index: 'act', width: 80, sortable: false, search: false, align: 'center',
formatter: function (cellvalue, options, rowObject) {
var markup = "<div>" +
"<div class='actionsButtonset'>" +
"<button class='dshbd_ConfirmMonth' rel='" + rowObject.UmltID + "' rev='" + rowObject.IsConfirmAvailable + "' plock='" + rowObject.IsPeriodLocked + "' alt='Confirm'>Confirm</button>" +
"<button class='btnSelectMenu' rev='" + rowObject.IsUmltLocked + "' " + ">Select</button>" +
"</div>" +
"<ul class='actionMenu'>" +
"<li><a class='dshbd_UnlockMonth' href='#' rel='" + rowObject.UmltID + "' alt='Unlock'>Unlock</a></li>" +
"</ul>" +
"</div>";
return markup;
}
}
Then, inside the gridComplete event I have the following code (please note that some code is needed to enable/disable menu items
var confirmMonthBtn = $('.dshbd_ConfirmMonth');
$.each(confirmMonthBtn, function (key, value) {
var button = $(this);
var umltID = button.attr('rel');
button.button().click(function (event) {
event.preventDefault();
});
var isPeriodLocked = (button.attr('plock') === 'true');
if (!isPeriodLocked) {
var isConfirmAvailable = ($(this).attr('rev') === 'true');
if (!isConfirmAvailable) {
button.button({ disabled: true });
}
} else {
button.button({ disabled: true });
}
});
var currentPeriod = GetCurrentPeriod();
var period = GetCurrentViewPeriod();
var isCurrent = false;
if (currentPeriod != null && period != null) {
isCurrent = period.PeriodID == currentPeriod.PeriodID;
}
var selectBtns = $('.btnSelectMenu');
$.each(selectBtns, function (key, value) {
var button = $(this);
button.button({ text: false, icons: { primary: 'ui-icon-triangle-1-s'} });
button.click(function (event) {
var menu = $(this).parent().next().show();
menu.position({
my: 'left top',
at: 'left bottom',
of: this
});
$(document).on('click', function () {
menu.hide();
});
return false;
});
$('div.actionsButtonset').buttonset();
var menuElement = button.parent().next();
menuElement.hide();
menuElement.menu({
select: function (event, ui) {
var umltID = ui.item.children().attr('rel');
event.preventDefault();
}
});
if (!isCurrent) {
var isPeriodLocked = ($(this).attr('plock') === 'true');
if (isPeriodLocked) {
menuElement.menu({ disabled: false });
} else {
var isUmltLocked = ($(this).attr('rev') === 'true');
menuElement.menu({ disabled: !isUmltLocked });
}
} else {
//The current period is always unlocked
menuElement.menu({ disabled: true });
}
});
I prepared the demo for you which demonstrates how Split Button can be used inside of jqGrid. It displays
More detailed explanation of the demo I'll post later. Probably you will understand all yourself after examining of the code.

jQuery autocomplete completely unresponsive

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
});
});

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.

Resources