DropDownList loses its property after using updatePanel in asp.net - javascript

I have below code to have intelligent dropdownlist in asp.net to have the search property there
<script type="text/javascript"> $(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({ allow_single_deselect: true }); </script>
The problem is that whenever I use updatepanel in this way:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<fieldset>
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
after that: it loses its property and returned as normal dropdownlist. Any idea how to fix this and make the update panel do not recreate the dropdownlist to its previous property?!

You need to execute that script again after an UpdatePanel update. Since the DOM still changes and the browsers loses the script bindings. You can use the PageRequestManager for that.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
//for after an updatepanel update
prm.add_endRequest(function () {
buildDropDownList();
});
//for normal page load
buildDropDownList();
function buildDropDownList() {
$(".chzn-select").chosen();
$(".chzn-select-deselect").chosen({ allow_single_deselect: true });
}
</script>

Related

How to Prevent Javascript Function Firing When ASP.NET Validation is Used

I'm calling a JavaScript DOM button click event to execute some code. However, I first need to validate if a textbox has a value in it. So, I'm using ASP.NET's RequiredFieldValidator control to validate the textbox. It works in that it will display an error message when the textbox is empty, however, the associated JavaScript button click event still fires.
How to do I prevent the JavaScript function from firing when I use an ASP.NET validation control?
By the way, I know I can use validation within JavaScript, but I'm hoping not to do that and just use ASP.NET validation controls only.
Here is my code (it's exactly how used with all the fluff removed):
<%# Page Language="VB" blah... %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="MyButton" runat="server" Text="Click Me" />
<asp:TextBox runat="server" ID="MyTextBox"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="MyRequiredFieldValidator" ControlToValidate="MyTextBox" Display="Dynamic" Text="*" ErrorMessage="The field is required.">
Required
</asp:RequiredFieldValidator>
</form>
<script type="text/javascript">
$(document).ready(function () {
const vMYBUTTON = document.querySelector('#MyButton');
SomeKindOfPluginObject.dom.addEvent(vMYBUTTON, 'click', function () {
console.log('Function started.');
console.log('My code executed.');
console.log('Function ended.');
event.preventDefault();
});
});
</script>
</body>
</html>
The issue is that the form submit is a click event, which is separate from the button click event.
Both of those events enter the queue one right after the other.
When the form is submitted, the server returns the required field error, then the next click event is processed which happens to be the JavaScript that you don't want to be called.
The server will need to render a page without the script until there are no errors
<!DOCTYPE html>
<html lang="en">
<head runat="server"></head>
<body>
<!-- /////////////////////////////////////////////////////////////
// Both the button click, and the JavaScript click events are
// triggerd when the form returns an error
///////////////////////////////////////////////////////////////-->
<form id="form1" runat="server">
<!-- /////////////////////////////////////////////////////////////
// When this button is clicked, it fires its own click event
///////////////////////////////////////////////////////////////-->
<asp:Button ID="MyButton" runat="server" Text="Click Me" />
<asp:TextBox runat="server" ID="MyTextBox"></asp:TextBox>
<asp:RequiredFieldValidator runat="server" ID="MyRequiredFieldValidator" ControlToValidate="MyTextBox" Display="Dynamic" Text="*" ErrorMessage="The field is required.">
Required
</asp:RequiredFieldValidator>
</form>
<script type="text/javascript">
$(document).ready(function() {
const vMYBUTTON = document.querySelector('#MyButton');
/////////////////////////////////////////////////////////////
// This event will fire because it is an
// additional click event that you are adding
/////////////////////////////////////////////////////////////
SomeKindOfPluginObject.dom.addEvent(vMYBUTTON, 'click', function() {
console.log('Function started.');
console.log('My code executed.');
console.log('Function ended.');
event.preventDefault();
});
});
</script>
</body>
</html>
You could do something simple to control the behavior by adding a variable to track the status of the form.
///////////////////////////////////////////////////////////////
// This event will be ignored until the server returns success
///////////////////////////////////////////////////////////////
SomeKindOfPluginObject.dom.addEvent(vMYBUTTON, 'click', function() {
if (someVariableSetOnTheServer == "invalid form") {
return;
}
console.log('Function started.');
console.log('My code executed.');
console.log('Function ended.');
event.preventDefault();
});
Another method would be to use the .NET JavaScript API to only run the code when Page_ClientValidate() returns true
if (Page_ClientValidate()) {
// run your code here
}

Document.ready method is called after pageload method - Jquery 3.3.2

I am facing one strange issue. I am upgrading my project to latest jQuery version 3.3.2. I have created a sample page which contains only update panel and a javascript link.
Now problem is instead of calling document.ready method, when I refresh the page (run the application), pageLoad method is called first and then document.ready method gets called.
I have tried using older version of jQuery 2.2.4 and up to that it was working fine with update panel, but when I upgraded to latest version 3.x.x it creates an issue.
Below is sample code
default.aspx page
<head runat="server">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.0.0.js"></script>
<%--<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.js"></script>--%>
<script src="Scripts/JavaScript.js"></script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div> Page body
</div>
<asp:ScriptManager runat="server" ID="sm" ScriptMode="Debug" EnableCdn="false"
EnablePartialRendering="true" LoadScriptsBeforeUI="true">
<CompositeScript>
<Scripts>
<asp:ScriptReference Name="MicrosoftAjax.js" />
<asp:ScriptReference Name="MicrosoftAjaxWebForms.js" />
</Scripts>
</CompositeScript>
</asp:ScriptManager>
<asp:UpdatePanel runat="server" ID="upSnapshot" UpdateMode="Conditional">
<ContentTemplate>
Update panel body
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
Javascript:
$j = jQuery.noConflict();
$j(document).ready(function () {
alert('document.ready');
});
function pageLoad(sender, args) {
alert('Pageload');
}
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded.
Where you have invoked the pageload() method ?
Can you share the HTML?

Inline scripting in SharePoint not working even after changing web.config

So, after a lot of searching I finally thought I enabled inline scripting on my sharepoint page (by changing the parser settings in web.config). However, the following still isn't working:
This:
<asp:Button runat="server" Text="Go!" id="GoBtn" OnClick="test()"/>
Should be calling this:
<script type="text/javascript" runat="server">
function test()
{
alert('Hello World!');
}
</script>
But it's not. Any suggestions?
OnClick attribute means server-side event.
You need:
<asp:Button runat="server" Text="Go!" id="GoBtn" OnClientClick="test()"/>
Try removing runat="server" from your script tag . There is no need for this .

Cannot call blockUI function from asp button

First of all it does work as a regular button:
<input type="button" value="Block" id="btnBlock" name="btnBlock"/>
But I need to work on an asp:button as well, I've tried this:
<asp:Button ID="btnBlock" runat="server" Text="Block" OnClientClick="btnClick"/>
But it doesn't work, just sends a JS error (edited):
Microsoft JScript runtime error: 'btnBlock' is undefined
My JS blockUI function:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#btnBlock').click(function() {
$.blockUI({ message: $('#myForm') });
});
});
</script>
I've also tried changing the blockUI function to this, but it doesn't seem to work, it doesn't recognize the asp code inside the script:
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#<%= btnBlock.ClientID %>').click(function() {
$.blockUI({ message: $('#myForm') });
});
});
</script>
In your asp button markup you've got
OnClientClick="btnClick"
This sets the client-side script that executes when a Button control's Click event is raised. That is the fired event looks for a javascript function called btnClick. The issue is that you are wiring the click event via jQuery $(selector).click(someFunction); and also in the OnClientClick event.
Change the asp button control to remove the OnClientClick event:
<asp:Button ID="btnBlock" runat="server" Text="Block" />
Keeping the javascript the same.

How to check If "mywindow" tab of the browser is active or not in asp.net 4.0?

Actually i am making website of online test/exam in asp.net using c# 4.0. And for giving exam the user needs to click on a button which will open a window with a JavaScript function.
function OpenForm() {
window.open('Test.aspx', 'mywindow',
'fullscreen=yes,titlebar=no,toolbar=no,statusbar=no,menubar=no');
}
And the thing i want is, while a Exam is going on, if user changes its tab or open a folder in his/her pc then i want to close the window i.e. "mywindow". i know its not possible in asp.net to achieve this so want to know how can i achieve this in javascript or jquery?
i have search out the net for few answers and now i know how to call a JavaScript function every time my "test.aspx" or "mywindow" page loads.
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
function endRequestHandler(sender, args)
{
yourFunction();
}
function yourFunction()
{
alert("aaa");
}
function pageLoad()
{
if(!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
}
</script>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="6000">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</form>
//i need to right the logic in yourFunction() to check whether "mywindow" or "test.aspx" is active or not if yes then i will display a message on alert("u are disqualified") and then close the "test.aspx"
Please someone help me out with this!!! please...!!
This is how I did it... I tested in Chrome/Opera/Firefox/IE... In IE it asked for permission to close the window on all the others it closed automatically....Not sure how to get around the IE bug at the moment.
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(window).focus();
$(window).blur(function () {
window.opener.BadStudent();
window.close();
});
$('#close').click(function () {
window.close();
});
});
</script>
EDIT: This script is placed on the page that they would end up on. Also I added a form element just to ensure that the window wouldn't close when a child element was selected and I didn't have any issues.
EDIT 2: The IE bug was due to javascript not opening the window. so insted use...
Link
and then...
<script type="text/javascript">
function BadStudent () {
alert("Your a bad student");
};
$(document).ready(function(){
$('#OpenWindow').click(function(e){
e.preventDefault();
Popup = window.open("#Url.Action("test")").focus();
});
});
</script>
The script that goes on the child window is still valid. Also this was done using jQuery for the selectors.

Categories

Resources