Javascript confirm in if condition statement in asp.net - javascript

I've javascript confirmation function like this:
<script type = "text/javascript">
function Confirm() {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Your team is incomplete. Do you want to save data?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
I want to show this when the team really incomplete. I check it in save button click. If false; I want to call JS confirm function:
if ((teamList.Contains("Purchasing") && teamList.Contains("Quality") && teamList.Contains("Process") && teamList.Contains("R&D")))
{ }
else
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "CallMyFunction", "Confirm()", true);
}
If confirm returns yes, I want to save them. If no, I don't want to save them.
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
// Do save operations
}
These code snippets returns null first time, and it returns my confirm answer (yes or no) when the other button clicks.
How can I do?

Related

In Javascript IF-ELSE, IF Statement is not working

I am trying to work on verifying OTP. Here I have two components that are:
Textbox which takes input of OTP. id="txtOTP"
An Status Line (here i have used <i> tag) that shows status of verified OTP. id="statusLine"
I am using JavaScript for this purpose.
function checkOTP()
{
var OTP = "1234";
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if (OTP.value == myOTP)
{
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
}
else if (OTP.value != myOTP)
{
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
As Per my code it should go to the if's scope if OTP is correct, and it should go to the else's scope if OTP is wrong.
However, it always goes to the else's scope even though I am writing the correct OTP in the textbox. I have even tried this code without using if with the else statement (like else if() { } ).
You need to either change myOTP to a number or use double equals:
var myOTP = parseInt(txtOTP.value);
Or:
if (OTP == myOTP) {...}
Also note that you don't need else if (...) - just use else {...}.
OTP is a Number but you check OTP.value in if/else if statements
function checkOTP()
{
var OTP = 1234;
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if(OTP === myOTP )
{
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
}
else if(OTP != myOTP )
{
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
Here is a solution. Its based on the comments and previous answers:
function checkOTP() {
var OTP = "1234";
var txtOTP = document.getElementById('txtOTP');
var statusLine = document.getElementById('statusLine');
var myOTP = txtOTP.value;
if (OTP == myOTP) {
console.log('Entered in Valid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "green";
statusLine.innerHTML = "OTP Verified, Generating Your Pass and Redirecting to the Next Page... ";
console.log('Exit From Valid OTP');
return true;
} else {
console.log('Entered in Invalid OTP');
statusLine.style.display = "inline";
statusLine.style.color = "red";
statusLine.innerHTML = "Invalid OTP. Please Try Again";
console.log('Exit From Invalid OTP');
return false;
}
}
You needed to write OTP instead of OTP.value and you don't need and else if for the opposite. Just else will do.
try adding a else statement after the else if since the syntax is :
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

ASP.NET Executing JavaScript Confirm alert message in C# code behind only if condition is satisfied

I am using a confirmation window that will add a new value to database if the user clicks OK in the popup window. Also i have to verify a specific criteria before that. I have button and text box and the text box contains a required field validator. So if i click the button this validator fires first.
I will enter a number in this text box and press add, it will fetch a name value corresponding to this number from database and if name is found then it should ask a confirmation "Do you want to add this name?" and if name is not found then it should just popup a alert saying "name not found". If number value is less than 6 then it will show another popup saying "number not valid". I have done this as given below.
ASP.NET
<asp:TextBox ID="text_add" runat="server" MaxLength="6"></asp:TextBox>
<asp:RequiredFieldValidator ID="required_add_" ControlToValidate="text_add" ErrorMessage="Required" runat="server">Required</asp:RequiredFieldValidator>
<asp:Button ID="button_add" runat="server" Text="Add" OnClientClick="Confirm()" OnClick="button_add_Click" />
JavaScript
<script type = "text/javascript">
function Confirm() {
if (Page_ClientValidate()) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you confirm?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
}
</script>
C#
protected void button_add_Click(object sender, EventArgs e)
{
if (text_add.Text.Length < 6)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Number not valid!')", true);
}
else
{
//fetch name from DB
if (//name found)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
//add the name
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Name not found!')", true);
}
}
}
Here what happens is whenever i enter a number into text box and click the button, the Confirm() function is executed at first even if the number is less than 6 digits and in case i enter 6 digits and the name is not found in database same way the Confirm() function is executed. If i enter number less than 6 digits the confirm box comes first and after that the alert saying "number not valid" comes. How can i fire the confirm() function only if the conditions are met. I want to fire the confirm() function only if the button press event goes into the if (//name found) condition.
EDIT
I have removed the OnClientClick from the button and then changed the C# code to the following
protected void button_add_Click(object sender, EventArgs e)
{
if (text_add.Text.Length < 6)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Number not valid!')", true);
}
else
{
//fetch name from DB
if (//name found)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "confirm", "Confirm();", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
this.AddData(sender, e);
}
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Name not found!')", true);
}
}
}
protected void AddData(object sender, EventArgs e)
{
// add data
}
I have made a seperte function to add data. I have added the ScriptManager to open confirm box and removed the OnClientClick in button. Now when i press the button the confirm box opens only if all conditions are satisfied. But when i press OK in confirm box nothing happens. The AddData function is not executed.
Change your confirm function to this:
function Confirm() {
if (Page_ClientValidate() &&
document.getElementById('text_add').value.length >5) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you confirm?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
else return false;
}
And change The
onClientClick=Confirm();
to this:
onClientClick= return Confirm()
to avoid submit under 6 length text.
You must have a hidden field between your post backs that shows it is in first post back or after confirmation:
<asp:HiddenField ID="isReadyForSave" runat="server" Value="false"/>
And change your code:
protected void button_add_Click(object sender, EventArgs e)
{
if(isReadyForSave.Value == "true" && Request.Form["confirm_value"] == "yes")
{
AddData();
isReadyForSave.Value = "false";
return;
}
if (text_add.Text.Length < 6)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Number not valid!')", true);
}
else
{
//fetch name from DB
if (//name found)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "confirm", "Confirm();", true);
isReadyForSave.Value = "true";
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Name not found!')", true);
}
}
}
And change you javascript confirm() function to this:
function Confirm() {
if (Page_ClientValidate() &&
document.getElementById('text_add').value.length >5) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm("Do you confirm?")) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
return true;
}
else return false;
}

Mvc validation and loader

In form post method in MVC view,
if validation fires then loader should not come and display only validations
else no validations fire then loader should come and save the data.
What I have tried:
placed loader on form submit in javascript and disable the button.
$("#frmContact").submit(function (e) {
$(".loading").css("display", "inline");
});
1) loader : Issue is that if validation fires, then loader also come alongwith validations and then need to reload the page and input data.
2) Disable Submit button : If I disable the Submit button on click and if validation fire then after button remains the disable instead enable. So if validation is there then enable the button and if validations are not fire then disable the button.
All this to avoid the duplicate entry as if button enables then if user clicks on submit.
You can do it this way
HTML :
<div id="ajax-loader" style="display:none;">
<img src="<?php echo $loaderSrc; ?>" style="height: 200px;width: 200px;">
</div>
<input type="submit" id = "btnSubmit" value="Submit" name="yt0" onclick="return validateForm();">
In script : (here you can change the fields...i am showing one of my example)
var error_flag = true;
var error_required = true;
$('#btnSubmit').click(function(e){
e.preventDefault();
if(error_flag && error_required){
$("#ajax-loader").css("display", "block");
$('form#login-form').submit();
}
});
function validateForm(){
var user_pass = document.getElementById('LoginForm[user_pass]').value;
var dob = document.getElementById('LoginForm_dob').value;
var re_pass = document.getElementById('re_pass').value;
var user_name = document.getElementById('LoginForm[user_name]').value;
var email = document.getElementById('LoginForm[email]').value;
var tnc = document.getElementById('checkbox1').checked;
// alert(tnc);
var filter=/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if(user_name == ''){
validate('LoginForm[user_name]','Nick name is required.');
}else if(email == ''){
removeerror('LoginForm[user_name]');
validate('LoginForm[email]','Email is required.');
}else if(!filter.test(email)){
removeerror('LoginForm[email]');
validate('LoginForm[email]','Please enter valid email.');
}else if(user_pass == ''){
// removeerror('LoginForm[email]');
validate('LoginForm[user_pass]','Password is required.');
}else if(user_pass.length < 6){
removeerror('LoginForm[user_pass]');
validate('LoginForm[user_pass]','Min length should be 6.');
}else if(re_pass == ''){
removeerror('LoginForm[user_pass]');
validate('re_pass','Repeat password is required.');
}else if(user_pass != re_pass){
removeerror('re_pass');
validate('re_pass','Password does not match.');
}else if(dob == ''){
removeerror('re_pass');
validate('LoginForm_dob','Dob is required.');
}else{
if(tnc == false){
document.getElementById('tnc_check').innerHTML = 'Please agree Terms and Condition' ;
document.getElementById("tnc_check").style.color = "red";
error_required = false;
}else{
error_required = true;
document.getElementById("tnc_check").style.display = "none";
removeerror('LoginForm_dob');
}
}
}
function validate(id,msg){
document.getElementById(id).style.border='4px solid red';
document.getElementById(id).value = "";
document.getElementById(id).placeholder = msg;
error_required = false;
}
function removeerror(id){
document.getElementById(id).style.border='none';
error_required = true;
}
Check validation on form submit or button submit event using javascript.
if($('#MyForms').valid())
{
// Do something (Valid)
}
else
{
// Do something (invalid)
}
the answer is simple. put valid in the form post event. all is what you want.
$("#frm").submit(function (e) {
if ($(this).valid()) {
$(".loading").css("display", "inline");
}
});

javascript validation with regex breaking all javascript

I'm writing javascript to validate a business calculator / orderform
another team mate has written the math code, but when I put in my code the whole thing stops.
I can't find my error (I'm more a css/html person)
help?
//Order Detail Variables//
var clientname =document.getElementById(clientname);
var phonenumber =document.getElementById(phoneno);
var deliveryaddress=document.getElementById(deliveryaddress);
var suburb =document.getElementById(suburb);
var postcode =document.getElementById(postcode);
var state =document.getElementById(state);
var deliverydistance = document.getElementById(deldistance);
var bagsordered =document.getElementById(bagsordered);
var orderdetailsarray = new Array();
//validation//
// these are boolean variables that when made true//
//by the validation will allow the calculation and logging to occur//
var clientnamevalid = new Boolean(false);
//Regex Variables//
//these are the regex patterns that are used to //
//confirm that the data is valid//
var alpha = pattern=/^[a-zA-Z\-]+$/;
function validation()
{
function validation();
{console.log (clientname);
if(alpha.test(clientname));
var clientnamevalid = true;
if { clientnamevalid = true;
alert(client name valid); //to be replaced with inline alert
}
else {
alert("client name invalid");
}
}
Edit Updated code:
the vars are now
var clientname =document.getElementById('clientname');
the function:
function validation()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert('client name valid')
}
else
{
alert("client name invalid");
}
}
Edit Updated code 2:
<button name="calculate" id="calcbutton" onclick="validate()"> Calculate </button>
function validate()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert('client name valid');
}
else
{
alert("client name invalid");
}
if clientnamevalid = true;
{
function calculateorder();
}
}
edit 3:
function validate()
{console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid);
{
alert("client name valid"); //edited from single quotations
}
else
{
alert("client name invalid");
}
if (clientnamevalid == true);
{
calculateorder();
}
else
{
alert ("please review form");
}
}
calc order func:
function calculateorder()
{
orderdetailsarray [0] = document.forms["orderform1"] ["clientname"].value;
orderdetailsarray [1] = document.forms["orderform1"] ["phoneno"].value ;
orderdetailsarray [2] = document.forms["orderform1"] ["deliveryaddress"].value;
orderdetailsarray [3] = document.forms["orderform1"] ["suburb"].value;
orderdetailsarray [4] = document.forms["orderform1"] ["postcode"].value;
orderdetailsarray [6] = parseFloat(document.forms["orderform1"] ["deldistance"].value);
orderdetailsarray [7] = parseFloat(document.forms["orderform1"] ["bagsordered"].value);
orderdetailsarray [8] = document.forms["orderform1"] ["orderdate"].value;
//gross calculation
var grossbagcost = orderdetailsarray[7] * millendcost;
grossbagcost = Math.round(grossbagcost *100)/100;
document.forms["resultsform"] ["bagsgross"].value = grossbagcost;
//end gross calculation
//discount amount calculation
if (orderdetailsarray [7] <=50)
{
var discountedbagcost = grossbagcost * discountnil;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
else if (orderdetailsarray[7] >50 && orderdetailsarray[7] <100)
{
var discountedbagcost = grossbagcost * discount4percent;
discountedbagcost = Math.round(discountedbagcost *100)/100;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
else if (orderdetailsarray[7] >=100)
{
var discountedbagcost = grossbagcost * discount7percent;
discountedbagcost = Math.round(discountedbagcost *100)/100;
document.forms["resultsform"] ["discount"].value = discountedbagcost;
}
updated code with null check
function validate()
{console.log (clientname);
//pattern test
var clientnamevalid == alpha.test(clientname);
if(clientnamevalid);
{
alert("client name valid");
}
else
{
alert("client name invalid");
//null check
}
if (x==null || x=="")
{
alert("Client name cannot be left blank");
clientnamenotnull == false;
}
else
{
clientnamenotnull == true;
}
//is the whole form valid
{
if (clientnamevalid == true)
if (clientnamenotnull) == true)
{
calculateorder();
}
else
{
alert ("please review form");
}
}
This appears to be problem area:
function validation()
{
function validation();
You have function inside another function.
Your function validation() is one big bug.
Did you mean
function validation(clientname)
{
console.log (clientname);
var clientnamevalid = alpha.test(clientname);
if (clientnamevalid)
{
alert('client name valid');
}
else
{
alert("client name invalid");
}
}
And you don't call that function in your code. And remember, parentheses and curly braces position does matter.
Another one, adding to anubhava's answer you need to change all getElementById from
document.getElementById(deldistance);
to
document.getElementById('deldistance');
In addition to anubhava and Surender,
the document.getElementById() get string.. so you need to change all this
//Order Detail Variables//
var clientname =document.getElementById(clientname);
var phonenumber =document.getElementById(phoneno);
var deliveryaddress=document.getElementById(deliveryaddress);
var suburb =document.getElementById(suburb);
var postcode =document.getElementById(postcode);
var state =document.getElementById(state);
var deliverydistance = document.getElementById(deldistance);
var bagsordered =document.getElementById(bagsordered);
and write the parameters between quotes.
for example:
var bagsordered = document.getElementById('bagsordered');
because as you wrote it, it confuse the compiler.
you can't pass the variable you just declare now at the same line you want his id.
if you're a css/html person as you say, you know that when you create an html button or div
you can define his id.
like <input type="button" id="order" value="press to order" />
now in javascript you can add functionality to this button. so when you want to get
this button in javaScript you can use the function document.getElementById('order')
see? I gave the id of the button that was declared in the html code.
hope you understand what i mean
Edit
look, when you have a button, as you said. for example i'll use the button I wrote before.
<input type ="button" id="order" value="press to order"/>
now if I have a function called "function()";
and I want that when the user will press on the button the function will be called
so I'll add to the html code of the button the onclick
so now it will be :
<input type = "button" id="order" value ="press to order" onclick="function()"/>
now when the user will click on that button, the function will be called and the code in it will performed
in addition, when you write a function that will change some label or button text.
you will need to get theirs id.
if my function is "changeText()". and I have a button with value "Hello" and id = "btn"
and I want to change the button value's from "Hello" to "wow"
so I need to get that button right?
and how do I get it?
with the method document.getElementById
here is the code:
function changeText()
{
var btn = document.getElementById('btn');
btn.value = "wow";
}
Edit 2:
clientnamevalid is boolean,right?
so when you want to check if it true or false, you can use the if statement.
if (clientnamevalid == true)
{
// do something, like call to calculateorder
calculateorder();
}
else // it's false
{
// do something else
}
note that you don't have to compare the 'clientnamevalid' variable or all another boolean variable to 'true' or 'false', the if statement does it alone. so you can write
if (clientnamevalid) // means that the clientnamevalid is true
{
calculateorder();
}
else
{
// do something else
}
Edit 3:
** From where you get the client name?! you need to enable the user to enter his name..
So you need a Form.. **
function validate()
{
console.log (clientname);
if (clientname != "" || clientname != null)
{
var clientnamevalid = alpha.test(clientname);
if(clientnamevalid)
{
alert("client name valid");
calculateorder();
}
else
{
alert("client name invalid, please review form");
}
}
else
{
alert("client name can't be empty!");
}
}

on button click, loop through text boxes javascript

I am trying to make a function actuated by a button click. On click, a function loops through each input type=text element, assigns their value attribute to variable, if that variable = null or variable = "" call method confirm('are you sure you want to save a blank row').
Here's my code/pseudo code:
<script type="text/javascript">
function isInputEmpty() {
$("#btnSave").click(function(){
$('input[type=text]').each(function(){
var x = $(this).attr('value');
var bool = false;
if(x == null || x == "")
{
bool = true;
}
else
{
send the request
}
if(bool == true)
{
if(confirm('Are you sure you want to save a blank URL?'))
{
send the request
}
else
{
do nothing or cancel the request
}
}
else
{
send the request
}
}
}
</script>
Here is my asp button code:
<asp:Button ID="btnSave" runat="server" Text="Save"/>
If you need more information, please let me know.
Thanks in advance
For ID issue, if you use ASP.Net 4.0 +, set ClientIDMode=Static
<asp:Button ID="btnSave" runat="server" ClientIDMode="Static" Text="Save"/>
JS
<script type="text/javascript">
function isInputEmpty() {
$("#btnSave").click(function(){
$('input[type=text]').each(function(){
var x = this.value;
var bool = false;
if(x === null || x === "")
{
bool = true;
}
else
{
send the request
}
if(bool === true)
{
if(confirm('Are you sure you want to save a blank URL?'))
{
LoadData();
}
else
{
return;//do nothing
}
}
else
{
send the request
}
}
}
function LoadData()
{
$.ajax({
type: "GET",
url: 'page.aspx',
timeout: 1000,
success:function(data){
//do work
},
error:function(jqxhr, status){
if(status==="error"){
//handle error
}
});
}
</script>
Since it's ASP.NET, that ID is going to be rendered different, try grabbing the Client ID (if the JS is in the same file, if it is not, use a unique class and assign the handler via that)
$("#<%=btnSave.ClientID%>").click(function() {
$("input:text").each(function() {
if (!this.value.length) {
var confirm = confirm('are you sure you want to save a blank row')
..
}
});
});
You can also do like below....
<script type="text/javascript">
function isInputEmpty() {
var bool = false;
$("#btnSave").click(function () {
$('input[type=text]').each(function () {
var x = $(this).attr('value');
if (x == null || x == "") {
bool = true;
}
});
if (bool == true) {
if (confirm('Are you sure you want to save a blank URL?')) {
//send the request
}
else {
//do nothing or cancel the request
}
}
else {
//send the request
}
});
}
</script>
It's not entirely clear what your question is, but other answers here have rightfully focussed on the ID issue and .Net webforms changing the element's ID.
The other solutions suggested are fine, but there is also another way, and that is searching by partial ID. When clientIDmode isn't set to static (or if you're pre .Net 4.0) the .NET ID will always have the original id appended after an underscore, so you can find your element using jquery like this:
$("[id$='_btnSave']").click(function(){ ...

Categories