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.
Related
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
}
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>
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 .
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.
I have a button (<asp:button id="MyButton" runat="server" />). I want this button to be automatically clicked onload. So I added JavaScript for that to happen:
<script language="javascript" type="text/javascript">
var myButton = document.getElementById('myButton');
myButton.click();
</script>
The error I'm getting is "Microsoft JScript runtime error: 'myButton' is null or not an object"
The page this button is on has a MasterPage in the back. Would that be the reason this is happenening?
document.getElementById() is case sensitive. Try document.getElemenById('MyButton').
You want to write the client ID rather than the server ID.
<script language="javascript" type="text/javascript">
var myButton = document.getElementById('<%=MyButton.ClientID%>');
myButton.click();
</script>
I see, this code will run before the button is loaded on the client so you will need to place this script block after the button or if you are using jQuery or something similar they will offer document ready functionality. The following code will be run once the document has loaded completely.
$(document).ready(function () {
var myButton = $('#<%=MyButton.ClientID%>');
myButton.click();
});
You'll want to set a few properties to implement your requirements.
<asp:button
id="MyButton"
runat="server"
UseSubmitBehavior="false"
OnClientClick="return changeBackgroundColor();" />
Setting the UseSubmitBehavior to false means that the button will not post back to the server. The OnClientClick property is as literal as it sounds. When clicked the client will execute the JavaScript code specified.
What is the Id of the button in the rendered HTML on the client side? ASP .NET has a tendency to have longer auto-generated client-side IDs for its own use. One thing you could do is set the name attribute of the button and reference that in the JavaScript.
Also of potential use to you is a method of finding a .NET client ID using jQuery.
The button probably has another ID when it's rendered to the client. Try to set ClientIDMode="Static" for the button. Then the id will be then same as on the server side.
Change the id="MyButton" to id="myButton" case matters in javascript/DOM
The page may not have loaded fully so when this code is executed 'myButton' may not be available yet. You can either make a function that calls this on body load:
<body onload="functionForButton()">
or put your script at the end of the body tag:
<script language="javascript" type="text/javascript">
var myButton = document.getElementById('myButton');
myButton.click();
</script>
</body>
Also make sure the case is the same. MyButton != myButton
Change your script to :
<script language="javascript" type="text/javascript">
var myButton = document.getElementById('<%= myButton.ClientID %>');
myButton.click();
</script>
And put this script at the end of page just before </body>.