I have a form with a text input:
<form name="form1">
<cfinput type="text" name="text1" id="text1" onChange="someFunc();">
</form>
I only want it to submit in certain cases. (I run some error-checking first)
<script>
function someFunc() {
if (1==2) {
document.form1.submit();
} else {
alert("Not submitting");
}
</script>
The problem is: even though the alert is triggering fine, somehow, the form is still submitting (There are no other submit statements aside from the one!).
Many thanks if anyone can shed some light on this . . .
There's a fundamental flaw with this approach. You are currently telling the form that when text1 changes, then call someFunc(). If true, use JavaScript to submit the form. If false, go on about your business. If you hit enter in the text input, the form still submits. If there is a submit button that gets clicked, the form still submits.
The basic way to approach this is like so:
<form name="form1" onsubmit="return someFunc()">
<input type="text" name="text1" id="text1">
</form>
When the from is submitted, call someFunc(). This function must return either true or false. If it returns true, the form submits. If false, the form does nothing.
Now your JavaScript needs a slight alteration:
<script>
function someFunc() {
if (1==2) {
return true;
} else {
alert("Not submitting");
return false;
}
}
</script>
You can still have other functions called when a field is changed, but they still won't manage the form's final submission. In fact, someFunc() could call the other functions to do a final check before returning true or false to the onsubmit event.
EDIT: Documentation on implicit form submission.
EDIT 2:
This code:
$(document).ready(function(){
$("#text1").on('change', function(event){
event.preventDefault();
});
});
is stopping the default processing for the change event associated with that element. If you want to affect the submit event, then you'd do this:
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
});
});
Which would allow you to do something like this:
$(document).ready(function(){
$("#form1").submit(function(event){
if ( $('#text1').val() !== "foo" ) {
alert("Error");
event.preventDefault();
}
});
});
var form = document.getElementById("Your Form ID");
form.addEventListener("submit", function (e) {
if ("Your Desired Conditions.") {
e.preventDefault();
}
});
use the following code it will work perfectly fine
<form onsubmit="return false;" >
Related
I am trying to check if all form fields are filled on click a button & if valid then i am trying to add a check an alert using jquery.
jQuery("button#btn_place_order").click(function(event){
jQuery("form").validate({
submitHandler: function(form) {
alert('ok');
}
});
});
This is what i have tried but its not working, i just want to check if all fields are ok valid & filled & there is no form related error then just console or alert to check. Webpage has two or more html forms. Is their any way we can check using jquery ?
Thanks
First of you will have to prevent the default behavior of a form submit. Afterwards add a event listener to your button and check for validation of each input. (whatever that means for you). Is this what you wanted?
var el = document.getElementById("form");
el.addEventListener("submit", function(event) {
event.preventDefault();
}, true);
document.getElementById("btn").addEventListener("click", validate);
function validate(){
let valid = true;
[...document.getElementById("form").elements].forEach((input) => {
if(input.value.length == 0){
valid = false;
}
});
if(valid) alert("valid");
}
<form id="form">
<input type="text" name="TEST" id="test">
</form>
<button class="button" name="Send" value="Send" id="btn">Check</button>
This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.
I am checking the textbox value in javascript. and saving to database. where as my save is of submit type. I want if textbox value is greater than 100 then it should alert. and after alert , page should not submit.
Firstly, bind the click event of that button to a function. Secondly, use event.prevent default to stop that button from submitting the form. Thirdly, validate the value you want. If validated, use form id to submit the form. Something like this:
$("#ButtonId").on("click", function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
if ($("#InputBoxID").val() < 100) {
$("#FormId").submit();
}
else {
alert("your message");
}
});
Above code is in jQuery, so do not forget to add the reference to jQuery.
I think you're looking for something like:
<form id="myForm" onsubmit="return validateForm();">
<input type="text" id="textfield"/>
<button type="submit">submit</button>
</form>
<script>
function validateForm(){
var value=parseInt(document.getElementById('textfield').value);
if(value>100){
alert('value is no good. larger then 100');
return false;
}
}
</script>
If you can show me your code I'd be happy to help you implementing such a feature.
Here you have an example of how to do it. I used a limit of 10 characters to make the test easier: Try if yourself
HTML:
<input type="text" id="myTextBox" onkeyup="checkValue(this)" maxlength="10"></input>
<input id="sendButton" type="submit" value="SEND"></inpu
JAVASCRIPT:
function checkValue(textbox) {
if (textbox.value.length > 10) {
alert("TEXT TOO LONG");
document.getElementById("sendButton").disabled = true;
}
else
document.getElementById("sendButton").disabled = false;
}
I'm sure I must have missed something really obvious, but can't for the life of me see what it is.
I have the below javascript, that (in theory) looks at the form when I click submit, and tells me if I have left the 'RefNo' field blank (in the final form there will be various fields to check, so I have used class='required' to identify them all). But so far, when I click submit, nothing happens (except the form is submitted with the missing data).
I've tried various options that I have found on the internet, and this seemed the most promising.
If anyone can see what I have done wrong it would be really appreciated.
<html>
<head>
<script language="JavaScript" src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function submitForm()
{
$("#Form1").submit(function()
{
$('.required input').each(function()
{
if ($(this).val() == '')
{
$(this).addClass('highlight');
}
}
);
if ($('.required input').hasClass('highlight'))
{
alert("Please fill in a Ref Number and try again");
return false;
}
}
);
}
</script>
</head>
<body>
<form method="POST" action="test9.php" name="Form1" ID="Form1">
<input TYPE="text" ID="RefNo" NAME="RefNo" VALUE="" size="25px" class="required"></input>
</br>
<p>
<input type="submit" Name="submit" id="submitButton" value="Report History" onClick='submitForm()'></input>
</p>
</form>
</body>
Your selectors should be $('input.required'), not $('.required input').
First, I think you should use Jquery validation plugin.
Ohterwise, this code should work :
-add a onsubmit="return submitForm()" in your Form tag
<form method="POST" action="test9.php" name="Form1" ID="Form1" onsubmit="return submitForm();">
-get rid of the onclick on the submit button
-and here is the submitForm function :
function submitForm() {
var valid = true;
$('input[class="required"]').each(function() {
if ($(this).val() === '') {
alert("One field is empty and try again");
valid = false;
}
});
return valid;
}
But I really recommend jquery.validate.js
Your selector appears to be a bit off:
It should be $('.required')
The way you have it tries to select an input nested inside a Required class.
Instead of doing it on form submit, remove the submit input type from the button and just have it be a regular button.
With that in mind, your javascript should be:
<script>
$('#submitButton').click(function () {
$('input.required').each(function() {
if ($(this).val() == '') {
$(this).addClass('highlight');
}
});
if ($('.highlight').length > 0) {
alert("Please fill in a Ref Number and try again");
return false;
}
else {
$('#Form1').submit();
}
});
</script>
Otherwise, the way that you're doing it, you would have to cancel the event until you run your check for missing data, and then submit the form anyway. This way keeps you from having to cancel the action, as older IE browsers do that differently than the other browsers, and even newer versions of IE. So it makes your code more readable.
The selector should be either $('input.required') or $('#RefNo').
$('#RefNo') is more faster since it uses native getElementById method.
I'm using the HTML5 form tag for the client side validator built into it, but I don't want it to submit a thing as I've just got a Javascript function to run instead.
How can i stop the Post method of the form.
Cheers - Caius
add a return false after the function call, like so:
<input .... onclick="function();return false;" />
or you could just return true/false from the function like so:
<input .... onclick="return function()" />
If you use jQuery you can do:
$('#your_form_id').submit(function(e){
e.preventDefault();
// do your staff
});
You can also do it without a framework:
document.getElementById('your_form_id').addEventListener('submit' function() {
// do your staff
return false;
});
In the "// do your staff" you can write your ajax code.
I tend to prefer leaving my functions as they are and add a return false to the onsubmit handler, ex:
<form onsubmit="aFunction(); return false;">
Add a onsubmit handler to your form, e.g.
<form method="POST" onsubmit="return sendForm();">
Then define the function and add false as return value:
function sendForm() {
//do your ajax request...
return false;
}
Add the onsubmit property to your form tag:
<form onsubmit="return myfunction()">
ensure you return a bool for your function
function myfunction() {
// do your validation
if (validation.passes) { // you will need to change this line !!!
return true; // to submit
} else {
return false; // to prevent submit
}
}
I've try all your solution but it still to reload the page after the ajax process :
<form id="form2" method="POST" onsubmit='sent(); return false;' >
function sent(){
$.ajax({
...
});
}