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.
Related
How to write a script in Javascript, which will measure the number of characters from the input text field on the form and if it is less than 2 will display an alert when you try to send the form, and if it is more than or equal to 2, will send the form with click send?
There are many ways of achieving this, including:
1- Adding a pattern attribute to your input element:
<form>
<input type="text" pattern=".{2,}">
<input type="submit" value="Submit">
</form>
In this case, if the input is invalid, the form will not submit and display the browser's default error message.
The regular expression .{2,} matches all strings with length 2 or more.
2 - Checking the length of the input value via Javascript, and taking action accordingly:
function validate() {
var text = document.getElementById("input").value;
if(text.length < 2) {
//display an alert or whatever
console.log("invalid");
return false; //form will not submit
}
return true; //form will submit
}
<form onsubmit = "return validate();">
<input type="text" id="input">
<input type="submit" value="Submit">
</form>
Using this method, once the form's submit button is clicked, the function validate() will execute. If the function returns true, the form will submit. If it returns false, the form will not submit.
Method 1 is quicker, while method 2 is more customizable/flexible.
In the submit button inside the form, consider doing the following:
<button onclick="checkValidity()">Submit</button>
And within <script> tags inside the body of the html add the following code:
function checkValidity(){
var val = document.getElementById('inputfield').value; //I'm assuming the id of the input text field to be inputfield
if(val.length<2) window.alert('too short');
}
Another simple way :
HTML :
<form id="form1">
<input id="input2" type="text" placeholder="your text here"></input>
<button type="submit">submit</button>
</form>
JS:
$('#form1').submit(function(event){
if($('#input2').val().length < 2){
event.preventDefault();
alert('ur input text will be more than 1 character');
}
});
Don't forget to import jQuery library before the code :
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
I am trying to write a very simple jQuery function which will have two main properties. The first one will be to check if the field is empty or not. The second one will be if the field is not empty to execute a form which will lead to a PHP coded page. I am very new to jQuery and I will be very grateful if someone can point where exactly is my mistake. Thank you in advance.
function Captcha() {
$('#Button').click(function() {
if ($("#Field").val().length == 0) {
alert("Please fill the box");
return false;
} else {
alert("Your code is saved");
return true;
}
});
}
$(document).ready(function() {
Captcha();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="success.php" id="Alpha" method="post" onsubmit="return Captcha();">
<input id="Field" type="text" placeholder="Enter key here">
<button id="Button" type="submit" form="Alpha">Confirm</button>
</form>
Don't work with the button's click event, work with the form's submit event because a form can be submitted via the keyboard and therefore the button can be circumvented.
You can see a working version here (Stack Overflow prevents submit code from working in the snippet environment below.)
$(function() {
$('#Alpha').on("submit", function() {
if ($("#Field").val().length == 0) {
alert("Please fill the box");
return false;
} else {
alert("Your code is saved");
return true;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="success.php" id="Alpha" method="post" onsubmit="return Captcha();">
<input id="Field" type="text" placeholder="Enter key here">
<button id="Button" type="submit" form="Alpha">Confirm</button>
</form>
You would want to validate the form fields when you actually submit the form. When you click on the button you are still in the process of triggering the submit.
Try changing this:
$('#Button').click(function() {
Into this:
$('#Alpha').on('submit', function() {
See if that helps.
Whenever I press the submit button it just submits the form and doesn't seem to run the checkSubmit function. Everything I've looked at in other examples suggests my code is correct. Is there something missing or wrong with the way I'm calling it?
<script language="javascript" type="text/javascript">
function checkSubmit() {
alert("This is an alert!");
if (document.getElementById("userID").value.length <1) {
alert("Please enter a User ID.");
return false;
}
else {
alert(document.getElementById("userID").value.length)
return true;
}
</script>
<form name="submitform1" method="POST" action="http://127.0.0.1/MyFile.php" onsubmit="return checkSubmit();">
Enter User ID: <input id="userID" name="userID" type=text size="25"/><br />
<input type="submit" name="submit" onclick="this.form.onsubmit();" value="Submit" >
</form>
<br />
Your code is missing the closing curly bracket for the checkSubmit() function for one.
In your HTML change the remove the onsubmit handler from the form element and change the onclick attribute on the submit button to call the function:
onclick="checkSubmit(event);"
Then, in your function, prevent the form from submitting, do your checks, then submit the form.
function checkSubmit(e) {
e.preventDefault();
// do checks
document.submitform1.submit();
}
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")
I have been battling for the past two days with the evil onbeforeunload function in JavaScript. I have a function that warns the user when they are about to close a page.
However before the page close I would like to submit the form using JavaScript's .submit().
This is my code:
function setPopUpWindow(submitForm){
window.onbeforeunload = function () {
if (submitForm == false ) {
//alert("It worked"); --This code gets called so I know it works
document.getElementById("CancelScripting").submit();
//return "Unsaved Data would be lost";
}
}
}
In my html I have two buttons, one is (supposed to) trigger the .submit() and the other will just ignore it.
<body>
<form action=tett.html id="popUpForm" method=POST>
<script>setPopUpWindow();</script>
<input type="submit" id="submit_button" onclick="setPopUpWindow(true);">
<input class=b1 type=submit id="CancelScripting" style="visibility:hidden" value="CancelScripting" >
</body>
The `setPopWindow value for the second input is not defined so it would be false.
For some reason the submit is not working well.
------------------------Edit to my question-----------------------------------------------
I would like to submit the form even if the user leaves the page by closing the X button on their window. This is the reason why I have the hidden button... Looks like people misunderstood my question.
The only thing you can do is to ask the user if they really want to leave the page:
<head>
<script type="text/javascript">
var submitForm = false;
window.onbeforeunload = function () {
if(submitForm == false){
return 'You have an unfinished form ...';
}
}
function setPopUpWindow(type){
submitForm = true;
}
</script>
</head>
<body>
<form action="" method="post" name="SubmitForm" id="SubmitForm">
<input type="submit" id="submit_button" onclick="setPopUpWindow(true);">
</form>
</body>
I think that what you want to do is submit the form rather than the button by doing something like:
document.forms["formId"].submit();
where formId is the id of the form.
Also, I dont see anywhere in your code where your form is but your buttons should be inside of form tags.
For example, it should look like this:
<body>
<script>setPopUpWindow();</script>
<form id="formId" action="" method="post">
<input type="submit" id="submit_button" onclick="setPopUpWindow(true);">
<input class=b1 type=submit id="CancelScripting" style="visibility:hidden" value="CancelScripting" >
</form>
</body>