Stop postback after alert by javascript in ASP.NET Code - javascript

I have a textbox and a button, on button's clientClick I call javascript function and there is also server side coding.
Problem is, the page gets post back even if I have return False in the javascript.
Here is my javascript function:
function checkALphaNumericFormat(str) {
//get previous value before editing
var txtUserId = document.getElementById('<%=txtUserId.ClientID%>');
var userId = txtUserId.value;
var patternAlphaNumeric = /^[A-z0-9]+$/gi;
var match = userId.match(patternAlphaNumeric);
//Check Null values
if (txtUserId.value != null && txtUserId.value != "") {
//Check for AlphaNumeric values for User Id
if (match == null) {
alert("Please provide valid AlphaNumeric User Id");
return false ;
}
return false ;
}
else {
alert("User Id field should not be null");
return false ;
}
return false ;
}
and I am calling this function on my Form as:
<asp:Button runat="server" ID="btnCreate" CssClass="loginButton" style="margin:0px 0px 1px 30px;" OnClientClick ="return checkALphaNumericFormat(this.value);" Text="CREATE" />

Try to call JavaScript function as below:
OnClientClick="if(!validateform()){return false;}
where validateform() should be your java script function. Your java script function should have return = true; at the end of function in successfull execution, like in below function:
function validateform()
{
var txtSearch = document.getElementById('<%=txtKeywordSearch.ClientID%>')
if(txtSearch.value == '')
{
alert('No Search Creatria Selected!');
return false;
}
return true;
}
Please try and let me know if it works for you.
Thanks,
Harish

Related

How to prevent blank fields using JavaScript?

I am using this to check if fields are empty. The problem is, the error message is never thrown when a field is empty, it allows submission. Is it because I am trying to run onclick and onclientclick on the button? This is my syntax
HTML
<asp:Button ID="main1212" runat="server" Text="Check If JS Works"
OnClick="DoSomethingDoNothing_OnClick" OnClientClick="return ValidateData();" />
JS
<script type="text/javascript">
function ValidateData() {
var main1212, dropdownselection, dropdownselection1, field21
main1212 = document.getElementByID("txt313").value;
dropdownselection = document.getElementByID("dropdownlist1").value;
dropdownselection1 = document.getElementByID("dropdownlist11").value;
field21 = document.getElementByID("txt12").value;
if (main1212 == '')
{
alert("Error");
return false;
}
if (dropdownselection == '')
{
alert("Error");
return false;
}
if (dropdownlist1 == '')
{
alert("Error")
return false;
}
if (field21 == '')
{
alert("Error");
return false;
}}
</script>
EDIT
If I open the browser console and press the button that should run my script their are no errors displayed?
It's missing a semi-colon in this line (not sure) of the function ValidateData:
var main1212,dropdownselection,dropdownselection1,field21;
(it's good to avoid extra spaces and also not create variables for this)
And it could be more simple, or like this:
window.onload=function(){document.getElementById('main1212').onclick=function(){ValidateData();};}

How do I stop server side event getting called

I have made a method for adding an image to the page for user feedback. I have tried the method on its own and now want to use it over and over again so it matches the validation on the site.
function ValidateFields(div, imgDiv) {
var validPass = true;
var elem = document.getElementById(div).value;
if (elem == "") {
var img = document.createElement("img");
img.src = "/assets/img/errorIcon.png";
var src = document.getElementById(imgDiv);
src.appendChild(img);
validPass = false;
//document.getElementById('lbl_pdf_title').innerText = ("Please enter a title for the PDF");
}
return (validPass);
}
When I used this method by passing in the correct values it works ok, but now I want to use the method like this:
function ValidatePdf() {
ValidateFields('txt_pdf_title', 'imgPdfError');
if (!ValidateFields()) {
// make it false
}
}
I want to use the method lots of times in the ValidatePdf() but it shows the symbol then carries on to run the serverside method.
This is my button click:
<button id="btn_submit_pdf"
runat="server"
class="btn btn-default"
title="Submit PDF"
onclick="if (!ValidatePdf()) return false;"
onserverclick="btn_submit_pdf_Click">
Submit
</button>
Do I need to pass another value to the ValidateFields()
I am at a loss as why it doesn't work.But does when you pass the original values in and call the method on the button click
For multiplie validation you just need to add another boolean value:
function ValidatePdf() {
var isValidate=true;
isValidate=isValidate && ValidateFields('txt_pdf_title', 'imgPdfError');
isValidate=isValidate && ValidateFields('txt_pdf_title1', 'imgPdfError1');
isValidate=isValidate && ValidateFields('txt_pdf_title2', 'imgPdfError2');
return(isValidate);
}
Or
function ValidatePdf() {
return(ValidateFields('txt_pdf_title', 'imgPdfError') && ValidateFields('txt_pdf_title1', 'imgPdfError1') && ValidateFields('txt_pdf_title2', 'imgPdfError2'));
}
Just return the result of ValidateFields:
function ValidatePdf() {
return ValidateFields('txt_pdf_title', 'imgPdfError');
}
You can also change your onclick to:
onclick="return ValidatePdf();"
so that it returns the result of ValidatePdf, which is now the result of ValidateFields.
Wrong way, should be:
function ValidatePdf() {
if (!ValidateFields('txt_pdf_title', 'imgPdfError')) {
// alert('not valid');
}
}

Return false does not prevent form submission

I have form that I need to validate using JavaScript and I need to show all the messages at the same time. E.g if the first name and surename is missing for two messages to appear. I've got this working with the below code but the form is still being returned back to the server. P Lease see below:
function validateForm() {
var flag = true;
var x = document.forms["myForm"]["firstname_4"].value;
if (x == null || x == "") {
document.getElementById("fNameMessage").innerHTML = "First name is required";
flag = false;
} else {
document.getElementById("fNameMessage").innerHTML = "";
}
var x = document.forms["myForm"]["surname_5"].value;
if (x == null || x == "") {
document.getElementById("sNameMessage").innerHTML = "Surename is required";
flag = false;
} else {
document.getElementById("sNameMessage").innerHTML = "";
}
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title") {
document.getElementById("titleMessage").innerHTML = "You need to select a title";
flag = false;
} else {
document.getElementById("titleMessage").innerHTML = "";
}
return flag;
}
My form and event :
<form action=""method="post" accept-charset="UTF-8" name="myForm" onsubmit="return validateForm();">
My Button:
<input type="submit" class="button" name="submit" id="submit" value="Submit">
Your code:
var y = document.forms["myForm"]["selectid"];
if (y.options[y.selectedIndex].value == "Title")
... triggers an exception and you don't catch it:
Uncaught TypeError: Cannot read property 'options' of undefined
Thus JavaScript code stops running.
Since everyone seems to be providing jQuery answers and I didn't see anything in your orignal code that was jQuery-esque I'll assume you aren't using jQuery.
You should be using the event.preventDefault:
Sources:
https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.submit
document.getElementById("submit").addEventListener(
"click", validateForm, false
);
function validateForm(){
// We should not assume a valid form!
var formValid = false;
// All your validation code goes here
if(formValid){
document.forms["myform"].submit();
}
}
try something like
if(flag){
document.getElementById("submit").submit();
}
else{
$('#submit').click(function (e) {
e.preventDefault();
});
}

Prevent page from posting back from JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
prevent postback of HtmlButton in C#
Here's my JavaScript function:
<script type = "text/javascript">
function CheckForEmptySearchBox(id) {
var index = id.substring(id.length - 1);
var boxContent = document.getElementById("contentMain__lvTSEntry__txtClientName_" + index).value;
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
}
</script>
And the markup:
<asp:Button ID="_btnSearch" runat="server" OnClientClick = "return CheckForEmptySearchBox(this.id)" />
This code is working, i.e. when the texbox is empty, the message prompt the user to enter search criteria and the javascript prevents the page to postback. However, when the user enters text, there's no message prompt but the page still doesn't postback. What's wrong?
EDIT
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
else {
return true;
}
The page is still not posting back.
you need to return true from your function if you mean it to return true....
<script type = "text/javascript">
function CheckForEmptySearchBox(id) {
var index = id.substring(id.length - 1);
var boxContent = document.getElementById("contentMain__lvTSEntry__txtClientName_" + index).value;
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
else{ return true;}
}
you are asking for a return onclientclick function and not returning any value when textbox having value that`s why its stuck
<asp:Button ID="_btnSearch" runat="server" OnClientClick = "return CheckForEmptySearchBox(this.id)" />
You are forgetting to return true if the validation passes:
function CheckForEmptySearchBox(id) {
var index = id.substring(id.length - 1);
var boxContent = document.getElementById("contentMain__lvTSEntry__txtClientName_" + index).value;
if (boxContent == "") {
alert("Please enter search criteria");
return false;
}
return true; //<--you forgot this
}

serverclick event is not fired when onclick javascript returns true?

I have a html input button like this
<input type="button" id="send_button" class="form_button" value="Send" onclick="return validateTextBoxes();" runat="server" />
And also I have javascript
<script language="javascript">
function validateTextBoxes()
{
var reading1 = document.getElementById('<%= meterReading1.ClientID%>').value;
var error = document.getElementById('<%= lblError.ClientID%>');
var btn = document.getElementById('<%= send_button.ClientID%>');
var ValidationExpression = /[\d]/;
if (reading1 == "" )
{
error.innerHTML = "Please enter Water Meter Reading.";
return false;
}
else if(!ValidationExpression.test(reading1)) {
error.innerHTML = "Please enter valid Meter Reading(It Contains only numbers)";
return false;
}
else
{
error.innerHTML = "";
return true;
}
}
</script>
And I am also calling this server click event in the code behind file
this.send_button.ServerClick += new System.EventHandler(this.send_ok);
So here is the problem when javscript returns true its not firing the serverclick event.
Please help me where I am doing wrong(I am using framework 1.1)
Thanks
I had this problem once and I actually had to do something like this:
onclick="if (validateTextBoxes()) { return true; } else { return false; }"
You absolutely should not have to do this and it made no sense to me why it would be have this way, but alas, I tried it and it worked :(

Categories