I am working on a donations website. In my page, I have a textbox which accepts a numeric value from the user (that is, money to be donated).
In my code-behind, I have a method which checks whether the value in the textbox is numeric. The method generates an error message if the number is invalid.
I also have a JavaScript which, after checking that the value in the textbox is numeric, opens a new tab to the website confirmation page, thanking the user for his donation. Here is the code of the javascript:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
if (textbox.value != "")
{
if (isNan(textbox) == false)
{
window.open("DonationConfirmation.aspx")
}
}
}
</script>
The problem is that the tab is NEVER opened, even if the number is valid. Can you please help me solve this problem? Thank you.
P.S.
Here is the code of the button that initiates the validation:
<asp:ImageButton ID="PayPalButton2" runat="server" ImageAlign="Middle"
ImageUrl="Resources/Icons/PayPalCheckOut.gif"
onclick="PayPalButton2_Click" OnClientClick="Open_Window()"/>
The function name is isNaN. Note: The final 'N' is capital. That should solve your problem.
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
if (textbox.value != "" && !isNaN(textbox.value)) {
window.open("DonationConfirmation.aspx");
}
}
</script>
edit
instead of isNan should be isNaN (javascript is casesensitive)
Shouldn't this line...
if (isNan(textbox) == false)
be this instead...
if (isNan(textbox.value) == false)
First, I would recommend explicitly parsing the number, not relying on the implicit ToNumber operation that will be applied when you pass a string into isNaN. Presumably your users are inputting decimal, so if it's meant to be a whole number (e.g., 10), use:
var num = parseInt(textbox.value, 10);
If it's meant to be a number with a fractional component (e.g., 10.5), use:
var num = parseFloat(textbox.value);
You probably want parseFloat for a currency value.
Then your if condition becomes isNaN (note that the final N is capped) on num:
<script type="text/javascript">
function Open_Window()
{
var textbox = document.getElementById('DonationTextBox');
var num = parseInt(textbox.value, 10);
if (!isNaN(num))
{
window.open("DonationConfirmation.aspx")
}
}
</script>
And lastly, are you sure that the client-side ID of the textbox really is 'DonationTextBox'? ASP auto-generates client-side IDs, you may need to use ClientID instead, e.g.:
var textbox = document.getElementById('<%=DonationTextBox.ClientID%>');
Here is a stripped down working jsFiddle example:
http://jsfiddle.net/pjgalbraith/QZeSF/
The html:
Open
<textarea id="donationTextBox">1</textarea>
And the js:
function openWindow() {
if($('#donationTextBox').val() && isNaN($('#donationTextBox').val()) === false)
window.open("http://www.google.com/", "mywindow");
}
$(document).ready(function() {
$('#PayPalButton2').click(function(){
openWindow();
});
});
Related
I am currently working on a C# MVC project. While entering user details into database I need to customize my MobilePhone field to only accept numbers. After some searching I found the below code :
$(document).on("keypress","#MobilePhone", function (e) {
var regex = new RegExp("^[0-9]\d*$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
e.preventDefault();
return false;
});
This code works for me, It only allows numbers to be entered in the Textbox.
But there is a problem, If a user copy some text and then paste the content in the Textbox nothing happens. Then if I press submitt button it submits and occur error.
So then I found this question :Disable Copy or Paste action for text box?
Answer to the question is :
$('#email').bind("cut copy paste",function(e) {
e.preventDefault();
});
But after I tried this I can not copy even numbers to the textbox. Is there any way I can prevent copying of alphabets and special characters only.
Just add some checks in your binding to prevent cut / copy / paste a non-number : https://jsfiddle.net/hswtutd9/
$(function() {
$("#email").bind("cut copy paste", function(e) {
const data = e.originalEvent.clipboardData.getData("Text")
if(! /\d./.test(data)) {
e.preventDefault()
}
})
})
why are you using text as your input type ????
if you are using strongly typed view ie editor for then just use data annotation
[DataType(DataType.PhoneNumber)]
public string PhoneNumber{get;set;} //i've used string here believing you initially made it as string and hence not effecting the code elsewhere
if you are using html inputs try
input type ="tel" note some brawser does not support tel for them i would prefer number
You can put the phone number validation code in a function and call if both places like:
function IsValidPhoneNumber(number) {
var regex = new RegExp("^[0-9]\d*$");
if (regex.test(number)) {
return true;
}
return false;
}
and now you can call it both places like:
$(document).on("keypress","#MobilePhone", function (e) {
if(!IsValidPhoneNumber($(this).val())) {
e.preventDefault();
return false;
}
}
$('#MobilePhone').bind("cut copy paste",function(e) {
if(!IsValidPhoneNumber($(this).val())) {
e.preventDefault();
return false;
}
});
or more better would be in a single event:
$(document).on("cut copy paste keypress","#MobilePhone", function (e) {
if(!IsValidPhoneNumber($(this).val())) {
e.preventDefault();
return false;
}
}
Now it would allow copying if the value satisfies the regular expression, you might need to tweak the function to check the whole number but this should give you idea how you can allow it there.
Hope it helped!
I'm opening a new window to another .aspx page in which I pass a couple of parameters and I wanted to re-pass the parameter ID from the actual page:
<asp:Button ID="Button1" runat="server" CausesValidation="False" meta:resourceKey="btnAddRow2"
OnClientClick="window.open('SecondPage.aspx?type=Usuaris&id=SPECIALID', '_blank')" Text="Miau" />
As you can see, the type parameter works well but I don't have the slightest idea how to get the "specialID" from the current page which would be:
http://blablabla.com/FirstPage.aspx?SPECIALID=36
So i want to get that 36 (which is a dynamic number so I can't actually put a 36 directly over there) in order to open the second page as follows:
http://blablabla.com/SecondPage.aspx?type=Usuaris&SPECIALID=36
As I said at the beginning the user IS at he FirstPage.aspx and upon pressing a button will go to the SecondPage.aspx
hi you can change the OnClientClick to call a javascript function which will get the specialId and then call the window.open with the full string.
for example
function openWindow(){
var specialId = document.getElementById('someElement').value;
window.open('SecondPage.aspx?type=Usuaris&id=' + specialId, '_blank')"
}
I finally could do it doing the following in the FirstPage.aspx:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
function AddUsuario() {
var id = getParameterByName("id");
window.open('SecondPage.aspx?type=Usuarios&id=' + id, '_blank');
location.reload();
}
On Page_Load() do following
Button1.Attributes.Add("onclick",
String.Format("window.open('SecondPage.aspx?type=Usuaris&id={0}', '_blank');",
Request.QueryString["SPECIALID"]));
I have to show confirmation dialogue on particular condition.And then proceed according to YES or No clicked.I tried with the following.
In aspx:
<script type="text/javascript">
function ShowConfirmation() {
if (confirm("Employee Introduced already.Continue?") == true) {
document.getElementById("hdn_empname").value = 1;
}
}
</script>
<asp:HiddenField ID="hdn_empname" runat="server" />
in cs:
if (reader2.HasRows)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "showAl", "ShowConfirmation();", true);
}
else
{
hdn_empname.Value ="1";
}
if ((hdn_empname.Value)=="1")
{
//some code to execute
}
But hdn_empname shows value="" while debuging.
Can anyone help me doing this?
Thanks in advance.
Try it
You need to ClientID
document.getElementById('<%=hdn_empname.ClientID%>').value = 1;
I found out your main problems
The hidden field values will assign after the if condition call.
Edit :
So, You need to call your logic's in javascript side using ajax
if (confirm("Employee Introduced already.Continue?") == true) {
//some code to execute
}
Where is your break point? If reader2.HasRows returns true your javascript will be registered. But it set the value on client and you get the result after postback.
hdn_empname is server controls Id which is different from client sided id, to get client sided id you need to use ClientID
try this:
document.getElementById('<%=hdn_empname.ClientID%>').value = "1";
You dont need to compare
if (confirm("Employee Introduced already.Continue?") == true)
this will work:
if (confirm("Employee Introduced already.Continue?"))
I have applied a textbox click validation and wanted to avoid any html tags in text box also the simple < (open tag) and >(close tag). The below code is working for but i want to add additional validations also for empty strings and other tags in html. Can some one please help modify the regex for the requirement.
function htmlValidation()
{
var re = /(<([^>]+)>)/gi;
if (document.getElementById(’<%=TextBox2.ClientID%>’).value.match(re)){ document.getElementById(’<%=TextBox2.ClientID%>’).value = “”;
return false;
}
return true;
}
Corrected Code above
In my opinion, I believe you'll have a good hard work if you want to validate such things.
Instead of preventing HTML content in a text box, other solution could be just html entity encode Text property, so <p>a</p> would be converted to >p<a>p<.
Result of that is you're going to render the HTML "as text" instead of getting it interpreted by Web browser.
Check this MSDN article:
http://msdn.microsoft.com/en-us/library/73z22y6h(v=vs.110).aspx
$("#<%= btnAdd.ClientID %>").click(function () {
var txt = $("#<%= txtBox1.ClientID %>");
var svc = $(txt).val(); //Its Let you know the textbox's value
var re = /(<([^>]+)>)/gi;
if(txt.val()!=""){
if (!txt.val().match(re)) {
//my Operations
//goes here
});
return false;
}
else {
alert("Invalid Content");
}
}
else {
alert("Blank value selected");
}
I have used Jquery function to check for regular expresion. This question is a linked question with
Using Jquery to add items in Listbox from Textbox
Now i can mark this as my final answer.
For a site I'm developing I have two html buttons, not ASP because I do not want them to postback. For the submit button I am calling a javascript function that implements PageMethods to call a C# method from the codebehind. Here is the code for the buttons and the javascript.
<fieldset id="Fieldset">
<button onclick="SendForm();">Send</button>
<button onclick="CancelForm();">Cancel</button>
</fieldset>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
PageMethods.SendForm(email, OnSucceeded, OnFailed);
}
function OnSucceeded() {
$get("Fieldset").innerHTML = "<p>Thank you!</p>";
}
function OnFailed(error) {
alert(error.get_message());
}
</script>
The codebehind method shown here:
[WebMethod]
public static void SendForm(string email)
{
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
else
{
if (IsValidEmailAddress(email))
{
bool[] desc = new bool[14];
bool[] local = new bool[14];
bool[] other = new bool[14];
for (int i = 1; i <= 14; i++)
{
desc[i] = ((CheckBox)Page.FindControl("chkDesc" + i.ToString())).Checked;
local[i] = ((CheckBox)Page.FindControl("chkLocal" + i.ToString())).Checked;
other[i] = ((CheckBox)Page.FindControl("chkOther" + i.ToString())).Checked;
/* Do stuff here */
}
}
else
{
throw new Exception("You must supply a valid email address.");
}
}
}
does not work unless it is declared as static. Declaring it as static blocks me from checking the checkboxes on the page because it generates a "An object reference is required for the non-static field, method, or property" error. So my problem can be fixed from either of two directions. A) Is there a way I can have this method work without declaring it as static? B) How do I check the checkboxes if the method is static.
It has to be static, no way around that; But you can access the Page like this
Page page = HttpContext.Current.Handler as Page;
and do FindControl on this page instance.
desc[i] = ((CheckBox)page.FindControl("chkDesc" + i.ToString())).Checked;
Page Methods are a special case of the legacy ASMX web service technology. They allow you to place the service in the codebehind class for the page, and keep you from needing a separate project for the service.
But they will never be able to access anything on the page itself. You'll have to do that from the client side, and pass the values of the check boxes to the service.
If you need to check the checkboxes, then you need to either use an UpdatePanel to do your AJAX stuff, or return something from your page method (ideally a string) and check the checkboxes based on what's returned in javascript on client.