checkboxes not styled after ajax call - c#

I have a script file scripts.js with a function that styles all checkboxes in page. This file is referenced in the master page.
There is a user control and a aspx test page for it. On page load, the UC shows a list of checkboxes and the style is applied.
On clicking a button, an ajax call gets a list from database and binds some more checkboxes to the page. But for the new checkboxes, the style is not applied. What could be going wrong.
scripts.js:
function selectcheckBtn() {
alert(1);
if ($("input:checkbox").prev("span").length === 0) {
alert(2);
$("<span class='uncheked'></span>").insertBefore("input:checkbox")
}
$("input:checkbox").click(function () {
check = $(this).is(":checked");
if (check) {
$(this).prev("span").addClass("cheked").removeClass("uncheked")
} else {
$(this).prev("span").addClass("uncheked").removeClass("cheked")
}
});
$("input:checked").prev("span").addClass("cheked").removeClass("uncheked")
}
ctrl.ascx:
<script>
function ShowMore() {
$.ajax({
url: "/_layouts/15/handlers/ShowMore.ashx",
data: {},
success: function (msg) {
//append new chkbox list to existing list. It is hidden at first and later faded in.
$(".divList").append(msg);
selectcheckBtn();
$(".hideDiv").fadeIn(300).removeClass("hideDiv");
},
error: function (msg) {
alert("An error occurred while processing your request");
}
});
}
</script>
Show more
On page load both alerts pop. But on clicking 'Show More', only alert(1) pops.
There are no errors in browser console.
Rendered HTML:
//with style applied to chkboxes on page load
<div><span class="uncheked"></span><input type="checkbox" runat="server" id="406">
<label>Compare</label></div>
//with no style applied to new chkboxes
<div><input type="checkbox" runat="server" id="618"><label>Compare</label></div>

I did not understand why the if condition wasn't true in selectcheckBtn();, for the new chkboxes. So, added a new class for the checkboxes and wrote this workaround.
Now calling this function instead of selectcheckBtn(); in the ajax code, worked.
function StyleCheckBox() {
$(".chkBx").each(function () {
if ($(this).prev("span").length === 0) {
$("<span class='uncheked'></span>").insertBefore($(this));
}
$("input:checkbox").click(function () {
check = $(this).is(":checked");
if (check) {
$(this).prev("span").addClass("cheked").removeClass("uncheked")
} else {
$(this).prev("span").addClass("uncheked").removeClass("cheked")
}
});
$("input:checked").prev("span").addClass("cheked").removeClass("uncheked")
});
}

Related

Black screen after bootbox.dialog in mvc view with jquery

The function i have called in jquery for add and update the record
$.post("/Project/ProjectManagement", { PrjDetails: JSON.stringify(PrjObj) }, function (Data) {
var result = JSON.parse(JSON.stringify(Data));
if (result.status == true) {
GetAllProjects();
var dialog = bootbox.dialog({
title: '<h4 style="color:white">Project Management and Tracking System</h4>',
message: '<p style="font-weight:700;">' + result.message + '</p>',
buttons: {
success: {
className: 'shadow mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent pull-left',
label: "OK"
}
}
});
$('#ProjList').modal('hide');
// window.location.href = '/Project/ProjectManagement';
}
else {
bootbox.alert("Error");
}
})
}
after click on edit button and save changes, i give the bootbox.dialog and when i click ok l got black screen with disabled touch.
when i check in developer options it is due to modal.backdrop.in opacity with.5
When i searching for this error i got the solution and i answered my question
after click on ok button of bootbox.dialog and i hiding that modal by $('#modalid').modal('hide'); and i hide the backdrop by using this jquery snippet $('.modal-backdrop').fadeOut(400);
and my error is solved...

Jquery Tabs - return selected tab dynamically

On page load I would like to display selected tab dynamically. This is so validation is displayed for the correct tab. I have the following code:
<script type="text/javascript">
$(document).ready(function () {
var selectedTabId= $("#SelectedTab").val();
alert(selectedTabId);
$('#tabs').tabs(
{
cache: false,
beforeActivate: function (event, ui) {
selectedTabId = ui.newPanel.attr('id');
$("#SelectedTab").val(selectedTabId);
},
selected: selectedTabId
})
});
</script>
The selected tab is correct which is set in a hidden field
<input type="hidden" value="#Model.SelectedTab" id="SelectedTab" name="SelectedTab" />
I have tried numerous options from links on stackoverflow and can't get the slected tab to display.
Stackoverflow:selecting & loading a jquery tab programatically
Stackoverflow: Set Jquery ui active tab on page load/reload
$("#tabs").tabs('select', selectedTabId);
selected was deprecated as of 1.9 and is now replaced by active, try:
As discovered in comments, you need to specify the index of the tab to select NOT the ID:
$('#tabs').tabs(
{
cache: false,
beforeActivate: function (event, ui) {
selectedTabId = ui.newPanel.index();
$("#SelectedTab").val(selectedTabId);
},
active: selectedTabId
})
Make sure the selectedTabId is the zero-based index.
I got this to work, not sure if best approach.
$("#tabs").tabs(
{
active: $("#SelectedTabToFind").val(),
cache: false
});
I set the value of SelectedTabToFind in the controller.

How do I call up a jQuery UI dialog from ASP.NET code behind without a client-side event?

I'm trying to open a jQuery UI dialog from my C# ASP.NET code based on a value being outside a certain range, rather than based on a button click or other client-side event. Here's the Javascript function that should create the dialog (at the top of the .aspx page):
<script type="text/javascript">
//Total out of range dialog
function ShowRangeDialog() {
$('#rangeDialog').dialog({
modal: true,
width: 'auto',
resizable: false,
draggable: false,
close: function (event, ui) {
$('body').find('#rangeDialog').remove();
},
buttons:
{
'OK': function () {
$(this).dialog('close');
}
}
});
}
</script>
Here's the dialog div itself (at the bottom of the .aspx page):
<div id="rangeDialog" style="display: none;" title="Total out of range">
<p>
Your line items total is out of the range allowed by the approval level you chose.
Please check the approval range and adjust the line items or quantities.
</p>
</div>
And here's the section of the C# code behind that attempts to display the dialog:
if (currTotal < lowerLim || currTotal > upperLim)
{
//Show jQuery dialog telling user that their line items total is out of range
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "dlgOutOfRange",
"ShowRangeDialog();", true);
}
The code in the if block is being reached and executed if I step through it in the debugger, but the dialog isn't being displayed. What am I missing?
I modified my function slightly, based on a question/answer I found at How do I open a jQuery UI Dialog from my c# code behind?, and now it works. Here's the modified function:
<script type="text/javascript">
//Total out of range dialog
function ShowRangeDialog() {
$(function() {
$('#rangeDialog').dialog({
modal: true,
width: 'auto',
resizable: false,
draggable: false,
close: function (event, ui) { $('body').find('#rangeDialog').remove(); },
buttons: { 'OK': function () { $(this).dialog('close'); }
}
})
}).dialog("open");
}
</script>
try this
if (currTotal < lowerLim || currTotal > upperLim)
{
//Show jQuery dialog telling user that their line items total is out of range
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "dlgOutOfRange",
"ShowRangeDialog();", true);
}
You should just be calling the function name.
Also, you may want to try startupscript instead of registerclientscriptblock. You have to be sure that your script gets added AFTER the function is defined, and not before.
if (currTotal < lowerLim || currTotal > upperLim)
{
//Show jQuery dialog telling user that their line items total is out of range
Page.ClientScript.RegisterStartupScript(this.GetType(), "dlgOutOfRange",
"ShowRangeDialog();", true);
}

Prevent scrolling to top using .load()

I'm trying to prevent the scrolling to the top when using jQuery's .load function. I've read at SO that you can use event.preventDefault(); event.stopPropagation();. Here is the link to this question. But when using beginform, you don't have an event here.
I also tried to put a click event on the submit button, but this also didn't work.
Thanks in advance!
This is the code of the view. When success the function closeFancyReservationCancel is called.
#using (
Ajax.BeginForm("Cancel",
"Reservation",
new AjaxOptions { HttpMethod = "POST",
OnSuccess = "closeFancyReservationCancel"},
new { id = "cancelForm" }))
{
...
}
)
And this is the jQuery function
function closeFancyReservationCancel() {
$.fancybox.close();
$('#reservationList').load(ResolveUrl('~/Reservation/reservationList'));
}
function ResolveUrl(url) {
if (url.indexOf("~/") == 0) {
url = baseUrl + url.substring(2);
}
return url;
}
Here a part of my HTML:
<div id="reservationList" class="tblContainer">
#Html.Action("reservationList", "Reservation")
</div>
The action reservationList returns a view with the table. Only the body of the table has an overflow: auto;.
EDIT: added more information
I have a div with a list of my reservations table. I am using MVC3 to show that list. When press the cancel button, the div will reload by the .load function.
EDIT
Here my HTML view with the table:
Pastebin
You can simply get the Scroll amount before loading. And apply the same scroll amount after load is finished
function closeFancyReservationCancel() {
$.fancybox.close();
var scroll_amount= $('#reservationList').scrollTop();
$('#reservationList').load(ResolveUrl('~/Reservation/reservationList'),
function() {
$('#reservationList').scrollTop(scroll_amount);
});
}
If you want you can also use .scrollLeft() amount.

Prevent Full Postback from __doPostBack

I have a content page that contains the following...
UpdatePanel1 - containing Error Display Divs
contains update triggers for both buttons
UpdatePanel2 - containing process 1 with an asp:button
updatePanel3 - containing process 2 with an asp:button
JavaScript that presents the user with a Popup confirm Jquery Messagebox based on the process they are executing.
UpdatePanel 2 or 3 becomes visible based on the users selection from the menu options.
When I click a button the messagebox pops and the page is processed correctly using __doPostback from the messagebox response and the page does a full postback.
I would rather the page do a partial postback and the content it had and display the Error Display Divs if there was an error. Any assistance would be appreciated.
nothing special about the button
<asp:Button ID="ResetSomething" runat="server" Text="ResetSomething" Width="275px" />
here is the content page script block
<script type="text/javascript" language="javascript">
<!--
function pageLoad() {
setform();
};
function setform() {
var reset1_button = $('input[id*=ResetSomething]');
var reset2_button = $('input[id*=ResetSomethingElse]');
reset1_button.click(function() {
var element = $(this);
$.prompt('Message1', { show: 'slideDown', buttons: { Ok: true, Cancel: false },
submit: function(v, m, f) { submit_reset_callback(v, m, element); }
});
return (false);
});
var submit_reset_callback = function(result, messages, element) {
if (result) { __doPostBack("ResetSomething");}
return (false);
};
reset2_button.click(function() {
var element = $(this);
$.prompt('Message2', { show: 'slideDown', buttons: { Ok: true, Cancel: false },
submit: function(v, m, f) { submit_update_callback(v, m, element); }
});
return (false);
});
var submit_update_callback = function(result, messages, element) {
if (result) { __doPostBack("ResetSomethingElse"); }
return (false);
};
};
-->
</script>
this is the code behind for the OnInit:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.PreLoad += (sender, args) =>
{
this.ClientScript.GetPostBackEventReference(this, "arg");
if (!IsPostBack) { return; }
string __targetaction = this.Request["__EVENTTARGET"];
string __args = this.Request["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(__args)) return;
if (__targetaction == "ResetSomething")
{
ResetSomething();
}
if (__targetaction == "ResetSomethingElse")
{
ResetSomethingElse();
}
this.upnlNotifications.Update();
};
}
Define the function below and replace your __doPostBack calls with doPostBackAsync(controlId, null).
function doPostBackAsync(eventName, eventArgs) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
prm._asyncPostBackControlIDs.push(eventName);
}
if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
prm._asyncPostBackControlClientIDs.push(eventName);
}
__doPostBack(eventName, eventArgs);
}
The controlId should be the id of the button to generate async postback else full postback occurs in the page.
For that you can use the clientidmode as static e.g
<asp:Button ID="button1" runat="server" ClientIDMode="Static"/>
//then you can use below code
_doPostBack('button1', '');//clientidmode forces buttonid = id given by us
Check its correct?
If so then you can get the async postback instead of a full page postback.
This helped me.
Thanks #Tim for his comment.

Categories