How do I execute a function in JavaScript when a text box is populated with text? The text box with be hidden from the user. It will be populated by a USB magnetic card swiper.
Pseudo code:
<script language="javascript" type="text/javascript">
function MyFunction() {
//execute this function when MyTxtBox is populated
}
</script>
<asp:TextBox id="MyTxtBox" runat="server" Visible="false" />
Seems like you're doing this when the page loads. If you are, this would work.
$(document).ready(function(){
if($('#MyTxtBox').val().length > 0){
MyFunction();
}
});
If it's on change:
$(document).ready(function(){
$('#MyTxtBox').change(function(){
if($(this).val().length > 0){
MyFunction();
}
});
});
See munch's answer but use CSS to hide the text box as setting visible = false will result in the text box HTML not being rendered and therefore not being available on the client side.
<style type="text/css">
.USBBox
{
position: absolute;
left: -999em;
overflow: hidden;
}
</style>
<asp.textbox id="MyTextBox" runat="server" CSSClass="USBBox" />
You can then use jQuery's class selector to acces the text box and not worry about name mangling:
%('.USBBox')
If you have a lot of elements on the page however you might be better accessing by id, in which case use the client id to avoid any name mangling issues:
$('#<%= MyTextBox.ClientID %>')
Update
Used CSS solution provided in this link to hide the textbox from the user. Updated the USBBox CSS class with correct solution as setting display:none caused javaScript issues.
Attach to MyTxtBox's onChange event. You need to do a bit of ASP.NET to produce the appropriate ClientID for use in JavaScript, since ASP.NET will modify the MyTxtBox ID into something else.
<asp:TextBox id="MyTxtBox" runat="server" Visible="false" />
<script language="javascript" type="text/javascript">
function MyFunction() {
//execute this function when MyTxtBox is populated
}
document.getElementById("<%= MyTxtBox.ClientID %>").onChange = MyFunction;
</script>
Related
I'm having a problem putting Matt's Calendar Popup when using it for addEventListener. I'm doing it on ASP.net VB.
This aspx code works but only for IE
<script language="JavaScript" src="/Content/Scripts/CalendarPopup.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
var cal = new CalendarPopup();
</script>
<asp:TextBox ID="txtRequestDate" runat="server" MaxLength="10" Style="width: 70px; height: 15px;
border: 1px solid silver;"></asp:TextBox>
<a href="#" onclick="cal.select(document.forms['frmMain'].txtRequestDate,'aFrom','dd/MM/yyyy'); return false;"
name="aFrom" id="aFrom">Select</a>
But when I change it to addEventListener (so that it will work on Chrome)
Popup.js
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("selCalendar").addEventListener("click", showCalendar, false);
});
function showCalendar() {
var cal = new CalendarPopup();
//alert("After CalendarPopup");
cal.select(window.document.forms['frmMain'].txtRequestDate,'aFrom','dd/MM/yyyy'); return false;
}
aspx code
<script type="text/javascript" src="../../Content/Scripts/Popup.js"></script>
<script type="text/javascript" src="../../Content/Scripts/CalendarPopup.js"></script>
Select</td>
Please help to fix this problem as I'm doing trying to do this for 2 days now. Thanks
Link of Matt Kruse's CalendarPopup.js ==> http://forge.ipsl.jussieu.fr/epoll/browser/trunk/root/static/js/CalendarPopup.js?rev=61
While this might not help?
If you just drop in a plane jane text box, and choose this:
Then without any code then you get this:
So, as a FYI, there is a nice date picker built in.
<asp:TextBox ID="TextBox1" runat="server" TextMode="DateTimeLocal" Width="188px"></asp:TextBox>
So if you set txt mode, then you get this:
And if text mode = date, then this:
Now, this may or may not help you, but a nice date picker is built in - and no code or add-ins is required.
For start one basic bug is that you do not get the correct id from your textbox
on the javascript code, replace the txtRequestDate with
<%=txtRequestDate.ClientID%>
related : Accessing control client name and not ID in ASP.NET
I have a custom control which displays results of some operations.
It is hidden by default and its made visible on the code-behind of some other class.
Now I want to hide it after a certain amount of time. How do I do it?
Edit:
Some answers suggested adding following javascript block at the end of the custom control which is not working if Visible="false" is used on the custom control.
But I did not made that clear enough and so accepted that as an answer.
Have to take a look at: How to call javascript function from code-behind
The timeout function is correctly called if Visible="true" is used.
ASPX:
<control id="customControl" runat="server" Visible="false"/>
Solution if Visible="true" is used in markup:
Custom control - ASPX:
<div id="body">
<!-- custom control -->
</div>
<script type="text/javascript">
window.setTimeout(function() { document.getElementById('<%=Me.divBody.ClientID%>').style.display = 'none'; }, 2000);
</script>
Custom control - Code-behind:
Me.customControl.Visible = True
Solution if Visible="false" is used in markup:
From start the script block is not rendered and later is not added automatically. So we need to register it.
Custom control - ASPX:
<div id="divBody">
<!-- custom control -->
</div>
<script type="text/javascript">
window.setTimeout(function(){ alert("test"); });
</script>
Custom control - Code-behind:
Me.customControl.Visible = True
Dim hideScript AS String = "window.setTimeout(function() { document.getElementById('" & Me.divBody.ClientID & "').style.display = 'none'; }, 2000);"
ScriptManager.RegisterClientScriptBlock(Me.Page, Me.GetType, "script", hideScript, True)
Source: http://www.codeproject.com/Tips/85960/ASP-NET-Hide-Controls-after-number-of-seconds
I haven't seen any reference to jQuery in the question, hence vanilla JS solution:
Put this at the end of the User Control file
<script type="text/javascript">
setTimeout(function(){
document.getElementById("<%=this.ClientID%>").style.display = "none";
}, 5000);
</script>
You could have a property on the object which when executed changed the visible property to false if you were outside of a stipulated time frame, so you'd have a visible from and until field and have that generate a boolean when compared to the current time.
You can probably use the javascript setTimeout function to execute some code to hide the div which has the user control to hide after a time period
<div id="divUserControlContainer">
//put your user control embed code here
</div>
<script type="text/javascript">
$(function(){
window.setTimeout(function() {
$("#divUserControlContainer").hide();
}, 2000);
});
</script>
You achieve it by simple JQuery methods:
$("#CustomControl").hide(1000);
$("#CustomControl").show();
I have a hidden TextBox control on my page that updates a span tag on the keyup event using jQuery. When the page is posted back to the server, the innerHTML attribute is empty.
How do I get the value that was set during the keyup event?
Client side code:
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$('#MyHiddenTextBox').keyup(function(){
if($(this).val().length > 0){
SetSpanValue();
}
});
});
function SetSpanValue() {
var mytext = $('#MyHiddenTextBox').val();
$('#MySpanTag').html(mytext);
}
</script>
<style type="text/css">
.USBBox
{
position: absolute;
left: -999em;
}
</style>
<asp:TextBox ID="MyHiddenTextBox" runat="server" CssClass="USBBox" />
<span id="MySpanTag" runat="server" enableviewstate="true" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
Server side code
protected void btnSubmit_Click(object sender, EventArgs e)
{
string x = MySpanTag.InnerHtml; //this is coming back empty
}
Remember that asp.net is still built on top of html form submissions, and with html forms only input and select tags are submitted back to the server. So you need to make your javascript update an input of some type (hidden would work just fine) at the same time it updates the span.
Span tags are not posted back to the server, they are not input controls, regardless of runat or enableviewstate settings. I would recommend entering the data into an input element when entered into the span tag, then you can access the value of that input element (TextBox/HiddenField etc) when the postback occurrs.
The contents of the element are not sent to the server in a postback.
All EnableViewState="true" does for you is tracks the changes made to the InnerHtml on the server.
You'll need to put the data into a hidden input.
In addition to the fact that you cannot capture span values on postback (as others have answered)... ASP.Net will not accept values set via javascript for hidden form fields because it considers this a security threat.
I have gotten around this in the past by making the form field visible but hosting it inside a hidden div. Then you can set the value of the textbox and it will be posted back to the server.
<div style="display:none;"><asp:TextBox id="MyHiddenTextBox" runat="server" /></div>
I have an asp.net button which is runat server, there is a function handle that postback of button onclick.
How can I display a "loading ..." word in the page before going to the server procedure?
Hook up OnClientClick to some javascript function that returns true or false. The postback occurs if it returns true else it is canceled.
<asp:Button id="MyButton" runat="Server" Text="Close"
OnClientClick="return PromptClose();"/>
<script type="text/javascript">
function PromptClose(){
return prompt("Do you really want to close this window?");
}
</script>
You could use the onsubmit event of your page's form. This happens before the form is submitted, and will allow you to stop submission of the form if you need by cancel bubbling. In case you need this, the last 2 lines in this example will cancel bubbling across browsers.
<form runat="server" onsubmit="ShowLoading()">
</form>
<script type="text/javascript">
function ShowLoading(e) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = 'http://www.oppenheim.com.au/wp-content/uploads/2007/08/ajax-loader-1.gif';
div.innerHTML = "Loading...<br />";
div.style.cssText = 'position: fixed; top: 30%; left: 40%; z-index: 5000; width: 222px; text-align: center; background: #fff; border: 1px solid #000';
div.appendChild(img);
document.body.appendChild(div);
// These 2 lines cancel form submission, so only use if needed.
window.event.cancelBubble = true;
e.stopPropagation();
}
</script>
The JavaScript above is just for example, however this is (in my opinion) the preferred way to do what you're looking for. It looks something like this (in the center of the screen):
Loading...
This will work for any element that raises a PostBack, so you don't have to manually call ShowLoading() on every button or form element you may have on your page. I would replace the contents of ShowLoading() with some real loading functionality and not just the example code I threw together.
Look at OnClientClick, you can add a call to a js function, or inline JS there.
Or you can wire into the button with JQuery and display a modal dialog with an async callback.
Like every other web developer on the planet, I have an issue with users double clicking the submit button on my forms. My understanding is that the conventional way to handle this issue, is to disable the button immediately after the first click, however when I do this, it doesn't post.
I did do some research on this, god knows there's enough information, but other questions like Disable button on form submission, disabling the button appears to work. The original poster of Disable button after submit appears to have had the same problem as me, but there is no mention on how/if he resolved it.
Here's some code on how to repeat it (tested in IE8 Beta2, but had same problem in IE7)
My aspx code
<%# Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script language="javascript" type="text/javascript">
function btn_onClick()
{
var chk = document.getElementById("chk");
if(chk.checked)
{
var btn = document.getElementById("btn");
btn.disabled = true;
}
}
</script>
<body>
<form id="form1" runat="server">
<asp:Literal ID="lit" Text="--:--:--" runat="server" />
<br />
<asp:Button ID="btn" Text="Submit" runat="server" />
<br />
<input type="checkbox" id="chk" />Disable button on first click
</form>
</body>
</html>
My cs code
using System;
public partial class _Default : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btn.Click += new EventHandler(btn_Click);
btn.OnClientClick = "btn_onClick();";
}
void btn_Click(object sender, EventArgs e)
{
lit.Text = DateTime.Now.ToString("HH:mm:ss");
}
}
Notice that when you click the button, a postback occurs, and the time is updated. But when you check the check box, the next time you click the button, the button is disabled (as expected), but never does the postback.
WHAT THE HECK AM I MISSING HERE???
Thanks in advance.
I think you're just missing this tag:
UseSubmitBehavior="false"
Try it like this:
<asp:Button ID="btnUpdate" runat="server" UseSubmitBehavior="false" OnClientClick="if(Page_ClientValidate()) { this.disabled = true; } else {return false;}" Text = "Update" CssClass="button" OnClick="btnUpdate_Click" ValidationGroup="vgNew"/>
Explanation
UseSubmitBehavior="false" converts submit button to normal button (<input type="button">). If you don't want this to happen, you can hide submit button and immediately insert disabled button on its place. Because this happens so quickly it will look as button becoming disabled to user. Details are at the blog of Josh Stodola.
Code example (jQuery):
$("#<%= btnSubmit.ClientID %>").click(function()
{
$(this)
.hide()
.after('<input type="button" value="Please Wait..." disabled="disabled" />');
});
fallen888 is right, your approach doesn't work cross-browser. I use this little snippet to prevent double-click.
"Disabling" HTML controls doesn't always produce consistent behavior in all major browsers. So I try to stay away from doing that on the client-side, because (working with the ASP.NET model) you need to keep track of element's state on client and server in that case.
What I'd do is move button off the visible part of the window by switching the button's className to a CSS class that contains the following:
.hiddenButton
{
position: absolute;
top: -1000px;
left: -1000px;
}
Now, what to put in place of the button?
Either an image that looks like a disabled button
Or just plain text that says "Please wait..."
And this can be done the same way but in reverse. Start with the element being hidden at page load and then switch to a visible className on form submit.
We use the following JQuery script, to disable all buttons (input type=submit and button), when one button is clicked.
We just included the script in a global JavaScript file, so we don't have to do remember anything when creating new buttons.
$(document).ready(function() {
$(":button,:submit").bind("click", function() {
setTimeout(function() {
$(":button,:submit").attr("disabled", "true");
}, 0);
});
});
This script could easily be extended with a check for Page_ClientValidate().
document.getElementById('form1').onsubmit = function() {
document.getElementById('btn').disabled = true;
};
This is the correct and simple way to do this:
It works in all browsers (unlike the accepted solution above).
Create a helper method in your application (say in a Utlity Namespace):
Public Shared Sub PreventMultipleClicks(ByRef button As System.Web.UI.WebControls.Button, ByRef page As System.Web.UI.Page)
button.Attributes.Add("onclick", "this.disabled=true;" + page.ClientScript.GetPostBackEventReference(button, String.Empty).ToString)
End Sub
Now from the code behind of each of your web pages you can simply call:
Utility.PreventMultipleClicks(button1, page)
where button1 is the the button you want to prevent multiple clicks.
What this does is simply sets the on click handler to: this.disabled=true
and then appends the buttons own post back handler, so we get:
onclick="this.disabled=true";__doPostBack('ID$ID','');"
This does not break the default behaviour of the page and works in all browsers as expected.
Enjoy!
FOR JQUERY USERS
You will get into all sorts of problems trying to add javascript directly to the onClick event on ASP.NET buttons when using jQuery event listeners.
I found the best way to disable buttons and get the postback to work was to do something like this:
$(buttonID).bind('click', function (e) {
if (ValidateForm(e)) {
//client side validation ok!
//disable the button:
$(buttonID).attr("disabled", true);
//force a postback:
try {
__doPostBack($(buttonID).attr("name"), "");
return true;
} catch (err) {
return true;
}
}
//client side validation failed!
return false;
});
Where ValidateForm is your custom validation function which returns true or false if your form validates client side.
And buttonID is the id of your button such as '#button1'
For debugging purposes, what happens if you put an else clause against the if(chk.checked)?
Make sure that your javascript function returns true (or a value that would evaluate to boolean true), otherwise the form won't get submitted.
function btn_click()
var chk = document.getElementById("chk");
if(chk.checked)
{
var btn = document.getElementById("btn");
btn.disabled = true;
return true; //this enables the controls action to propagate
}
else return false; //this prevents it from propagating
}
One can also try the following way to prevent double clicking of the "SUBMIT" Button:
.buttonload {
background-color: lightgrey; /* Grey background */
border: none; /* Remove borders */
color: black; /* Black text */
padding: 12px 24px; /* Some padding */
font-size: 16px; /* Set a font-size */
}
/* Add a right margin to each icon */
.fa {
margin-left: -12px;
margin-right: 8px;
}
<!DOCTYPE html>
<html>
<head>
<!-- Add icon library -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script type="text/javascript">
$(function () {
SubmitButton = $("#btn");
SubmitButton.on("click", function () {
result = ValidateRecords();
if (result) {
$(this)
.hide()
.after('<button disabled class="buttonload"><i class= "fa fa-spinner fa-spin"></i>Processing Data...</button >');
}
});
});
function ValidateRecords() {
var DateTime = document.getElementById('lit').value;
if (!DateTime.trim()) {
return false;
}
else {
return true;
}
}
</script>
</body>
</html>
EXPLANATION(In Order of Code Appearance above):
CSS : Handles the spinner element used as part of the icon tag in the replaced button.
Adding the Icon Library in header is mandatory in case if you want to use the icon class fa-spinner.
In the script tag Validate method is called to check if all the mandatory form elements are filled prior clicking the submit button
Post the validation is successful, I am hiding the submit button[.hide()] and replacing with another button[.after()].
Setting the DISABLED property on the new button is mandatory or else it will work as an active button.
NOTE: I have used Button to replace the submit Button. But you can use input text or any other suitable element as per your requirements