cancel in confirm function submitting form in javascript - javascript

Got a form that requires users to input an amount to donate. On clicking submit, a function is called and the function is meant to display the amount specified and prompt the user to confirm if the amount typed is the actual amount or not.
The Cancel option in the Confirm() keeps submitting the form instead of returning false.
function donationFormSend(){
get_donation_amount = document.getElementById("get_donation_amt").value;
if(get_donation_amount != ''){
return confirm("You have specified "+get_donation_amount+" as the amount you wish to donate. \n\n Are you sure you want to proceed with the donation?");
}
else{
alert("Amount must be specified to process your donation.");
return false;
}
}
<form method="post" action="">
<div>
<div>Donation Amount:</div>
<input name="amount" type="text" id="get_donation_amt" required="required" />
</div>
<input name="donation_submit" type="submit" id="Submit" value="Proceed" onclick="return donationFormSend();" />
</form>
Jsfiddle link
Would be pleased getting help with this.

I updated your jsfiddle so it's in the expected format (loading the js in the head) and returning the confirm result
return confirm('blah blah')
works perfectly well for me in FF! Just make sure you clear your cache and reload your page.

A way to do do it might be:
form :
<form id='test' method="post" action="">
<div>
<div>Donation Amount:</div>
<input name="amount" type="text" id="get_donation_amt" required="required" />
</div>
<input type="submit" value="submit" onClick="form_submit(this.value)">
<input type="submit" value="cancel" onClick="form_submit(this.value)">
</form>
javascript:
document.getElementById('test').addEventListener('submit',function (event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
})
form_submit= function (submited_by) {
if(submited_by == 'submit'){
alert('Submited')
}else if (submited_by == 'cancel'){
alert('cancelled')
}
}
I'd rather use a switch statement to make it expandable in the future but this should work.
Also I'm using jquery mostly because I'm not sure how to stop default action without it.
here's a JSFiddle with the code running.
EDIT: Updated to not use Jquery.
EDIT: well, I feel stupid now, realised it wasn't cancel button in a submit form but in a confirmation form.

In your HTML use : onclick="return donationFormSend();"
In Your Javascript: return confirm("Are you sure ....blah blah blah")

Related

Execute PHP function with Javascript onClick without page refresh

My research is pointing me to Ajax and/or JQuery, but I wanted to ask to make sure I understand and move in the right direction.
I've been looking to use a javascript onclick function to create a popup(alert) asking to confirm that I want to proceed and show the changes I'm about to make.
I hoped that I could use PHP $_POST or GET to echo the change in the popup/alert window. However without the page refresh it appears I can't do this, but looking for a confirmation? Should I be looking for Ajax to do this? Any thoughts/suggestions would likely give me a head start as php/ajax is sort of foreign to me.
Sample code:
<script>
function clicked() {
if (confirm('Do you want to submit? <?php if(isset($_POST['city'])){$city = $_POST['city'];echo $city;}?>'))
{
yourformelement.submit();
} else {
return false;
}
}
</script>
</head>
<form action="output.php" method="post">
<input name="city">
<input type="submit" onclick="clicked();" value="Button" />
</form>
</html>
You can get the input value with jQuery before submitting:
<form action="output.php" method="post" id="form">
<input name="city" id="city_input">
<input type="submit" value="Button" />
</form>
<script>
$('#form').submit(function(e) {
e.preventDefault();
let cityInputVal = $('#city_input').val();
if (confirm('Do you want to submit ' + cityInputVal + '?'))
{
this.submit();
} else {
return false;
}
});
</script>
The preventDefault() function stops the form submission and therefore, page refresh.

javascript Redirect submitted form after clicking ok in the alert box

I have a form
onclick confirm , i need to direct it to a particular url
function submitdata() {
if(confirm("Are You Sure You Want To Proceed?")) {
location.replace("http://www.w3schools.com");
} else {
alert("Cancelling");
}
}
</script>
After submitting this form submitdata() is called.
then i am getting an alert.
BUT MY FORM is not getting redirected
<form id="registration_form" action="" method="post" onsubmit="return submitdata();">
<div id="state"></div>
<div class="reg-id">
<label>
<input placeholder="State:" type="text" tabindex="3" name="user_state" id="reg_state" value="">
</label>
</div>
<div class="reg-id">
<label>
<input placeholder="City:" type="text" tabindex="3" name="user_city" id="reg_city" value="">
</label>
</div>
<div class="reg-id-last">
<label>
<input placeholder="Zip/Postal:" type="text" tabindex="3" name="user_zip" id="reg_zip" value="">
</label>
</div>
<input type="submit" value="Response" tabindex="3" name="reg_btn" id="id-submit">
</div>
</form>
if(confirm("Are You Sure You Want To Proceed?")) {
return true;
location.replace("http://www.w3schools.com");
}
return returns from the surrounding function. Nothing after it will be executed. You need to swap the two lines.
I got it
<script>
function submitdata() {
var r = confirm('Are you sure?');
if (r == true) {
window.open('http://www.google.com');
} else {
alert('it didnt work');
}
return false;
}
</script>
If you want the form to actually submit to that location, then the form data won't get sent with that redirect. You can submit the data by setting the action attribute of your form tag to the URL you want, and changing the form submit event to something like this:
function submitData(event) {
if(confirm('Are you sure you want to proceed?') == false){
event.preventDefault();
return false;
}
}
So instead of redirecting when the user clicks 'ok', you basically just cancel the form submit if the user doesn't click 'ok'.
If you didn't want to submit the data, then you just need to move your return statement, like melpomene suggested.
Note: I always write both event.preventDefault() and return false; but I think usually only return false; would work as well. But, better safe than sorry :)

Javascript form validation - PHP variable as VALUE - Invalid Input

I have an issue where I am validating form submission with javascript. The form is prefilled with results from the database as PHP values like this:
<form name="profiledit" action="profile_edited.php" method="POST" >
<h3>Name:</h3>
<input type="text" id="teamname" name="teamname"
value="<?php echo $result['teamname'];?>">
</form>
This is the javascript:
<script type="text/javascript">
function empty() {
tn = document.getElementById("teamname").value;
if (! /^[a-zA-Z0-9]+$/.test(tn)) {
alert("Please enter a valid Team Name");
return false;
}
}
</script>
The submit button is :
onClick="return empty();"
The problem is that is always tells me top "Please enter a valid Team Name" unless I retype the text in the box (that was supplied by the PHP value).
I cannot see any weird spaces or things in "view source".
What could the problem be?
Thanks.
EDIT1 : Sorry I forgot to paste closing brace. It was there in the code and this does work for BLANK forms OK. Just not when it has a prefilled value from PHP.
Try this
Check this link
Html
<form name="profiledit" action="" method="POST" id="profiledit">
<h3>Name:</h3>
<input type="text" id="teamname" name="teamname" value=""/>
<input type="button" id="submit" value="submit" name="submit" />
<input type="submit" id="submitform" value="submitform" name="submit" style="display:none;" />
</form>
Jquery
$('#submit').click(function(){
var pattern=/^[a-zA-Z0-9]*$/;
var tn = $("#teamname").val();
if(tn == "" && pattern.test(tn)){
alert('1');
}else {
//alert('2');
$('#submitform').trigger('click');
}
});
Hope its helps
Well, there was nothing wrong with the responses after all. My code was good and you guys code was good as well.
The problem?
Well I just happened to be testing with a teamname that had a SPACE in it!!!!!!!!!!
So having finally worked out that was the problem all along I would like to thank you all for your inputs.
I have used the regex instead : /^\w+( \w+)*$/
Allows words, numbers and a space.

Pop up if values are under -5

I have a database with a table called "quote". It stores a margin field which is updated by users using an ajax table. This is in "process2.php" file.
I want a pop-up message saying "are you sure you want to put this margin" when the user clicks on the submit button if a margin value is below 5".
This is my submit form.
<form action="process3.php" method="POST" enctype="multipart/form-data">
<input type="submit" name="submit" value="Generate Quote"/>
</form>
You could do this with JavaScript (and jQuery, in this example). Your form would need an ID, as below:
<form action="process3.php" method="POST" id="myForm">
<input type="text" name="checkMargin1" />
<input type="text" name="checkMargin2" />
<input type="submit" value="Send" />
</form>
And then this would go into the head of your document:
<script type="text/javascript">
$('#myForm').onSubmit(function() {
var check1 = $('input[name="checkMargin1"]').val();
var check2 = $('input[name="checkMargin2"]').val();
if (check1 <= 5 || check2 <= -5) {
var answer = confirm("Are you sure you want to submit?");
return answer;
} else {
return true;
}
});
</script>
That function is fired when your form is submitted. It gets the values of the two margin fields (adding more should be easy) and checks if they are over -5. If they are, then return true allows the form to submit. If they are not, then a prompt dialog asks the user, which returns true when they click "Okay" and false when they click "Cancel", thus allowing or stopping the form from being sent.
Hope this helps :)

JS validation false, form still submitting

I've got a JS problem. My validation seems to be working, checking that the user inputs a valid number which isn't zero, but the form is still submitting. I have seen this question asked many times but I can't find a solution that works for me. Any ideas would be great.
My Javascript
function checkNotZero()
{
var theNumber = document.getElementById("theNumber").value;
var str = /^\+?[1-9]\d*$/.test(theNumber);
if ( str == false ) {
alert('You have not entered a valid number');
return false;
} else {
document.getElementById('numberCheck').submit();
}
}
My HTML
<form action="/next.php" method="post" id="numberCheck">
<input type="text" id="theNumber" value="0">
<button id="submitButton" OnClick="checkNotZero();">Add to Basket</button>
</form>
Use an <input type="submit"> for the submit button.
Validate on the form's submit event rather than some onclick. Forms can get submitted in other ways than just clicking a button (for instance, pressing "enter", or procedurally through code).
Prefer .addEventListener to attributes for attaching events to elements. Use preventDefault() to prevent form submission.
Hi for the above requirement of 'validating form' java script validation should be done
when the form gets submitted. follow the below approach, form will not get submitted
until and unless the validation is correct.
<html>
<head>
<script type="text/javascript">
function checkNotZero()
{
var theNumber = document.getElementById("theNumber").value;
var str = /^\+?[1-9]\d*$/.test(theNumber);
if ( str == false ) {
alert('in');
alert('You have not entered a valid number');
return false;
} else {
document.getElementById('numberCheck').submit();
}
}
</script>
</head>
<body>
<form action="/next.php" method="post" id="numberCheck" onsubmit="return
checkNotZero()">
<input type="text" id="theNumber" value="0">
<button id="submitButton">Add to Basket</button>
</form>
</body>
</html>
the only change is <form action="/next.php" method="post" id="numberCheck"
onsubmit="return checkNotZero()">
do not use onclick event in submit button.

Categories