Here is my code :
<script type="text/javascript">
function submitform() {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
as expected, the form when submitted should call the submitform function, and if the name field is blank, it should return false and give an alert.
But, it just goes through.
Any explainations?
You need to call the function with return, so that the false value prevents default action (form submission)
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to stop a little.
You can use onSubmit, but it's best to delete your input submit and put a button.
Then on button click you can do what you want and eventually submit the form
Form:
<form action="mail.php" method="post" id="mailForm">
<input type="text" id="name" name="name" placeholder="name">
<button id="submitMailForm">Submit</button>
JS:
$( document ).on( "click", "#submitMailForm", function(e) {
//My control Here
//If all ok
$("#mailForm").submit();
});
You can use jquery instead of javascript for this kind of validation is will be very easy to implement.
<form action="mail.php" method="post">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit" id="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(fucntion(e){
if($("#name").val() == ""){
alert("Name is empty");
e.preventDefault();
}
});
});
</script>
And dont forget to add jquery library before the script tag.
You need to change your onSubmit attribute as follows
onsubmit="return submitform();"
So your html look like this
<form action="mail.php" method="post" onsubmit="return submitform();">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
To cancel submission, the listener needs to return true or false. Also, if the function validates the fields, far better to name it for what it does rather than when it does it so call it something like "validateForm".
Also, giving a control a name of "name" masks the form's own name property. While that doesn't matter here, in general it's not a good idea to give any form control a name that is the same as a standard property of a form (e.g. "submit" or "reset").
So you might end up with something like:
<script>
function validateForm(form) {
if (form.personName.value == '') {
alert('Please enter a name');
return false;
}
}
</script>
<form ... onsubmit="return validateForm(this);">
<input type="text" name="personName">
<input type="submit">
</form>
<script type="text/javascript">
function submitform(event) {
if(document.getElementById('name').value=='') {
alert('Please enter a name');
event.preventDefault();
return false;
}
}
</script>
<form action="mail.php" method="post" onsubmit="submitform(event);">
<input type="text" id="name" name="name" placeholder="name">
<input type="submit" value="submit">
</form>
You need to prevent default of submit. In JS return false does not stop the propagation of the "submit" function (with frameworks can be different).
I suggest you to read:
event.preventDefault() vs. return falseenter link description here
just try this script
function submitform() {
var x = document.forms["fname"].value;
x = x.trim(); // Remove white spaces
if (x==null || x=="") {
alert("First name must be filled out");
return false;
}
}
Related
I'd like to display a message above the name field if the user submits a name with a length greater than 20. This means the form will not get submitted - in other words, the form's action won't be triggered.
I've tried almost every suggestion I could find to prevent the form action from being triggered upon form validation but nothing seems to be working.
I've hit a wall with this and can't figure out what I'm doing wrong. How can rectify this?
html:
<form method="POST" id="form" action="/post.php">
<span class="nameError"></span>
<input type="text" class="name" name="name" placeholder="Name" required/>
<input class="button" type="submit" value="Submit"/>
</form>
Here's my jquery:
let name = $('.name');
let nameError= $('.nameError');
$(document).ready(function() {
$('input[type=submit]').on('click', function(e) {
if (name.length > 20) {
e.preventDefault();
nameError.val("Too many characters!");
return false;
}
});
});
I have modified the logic for validation. Basically we need to capture the submit event for the form and use the correct jquery methods to retreive data based upon the selectors.
$(document).ready(function() {
$("#form").submit(function( event ) {
let name = $('.name').val();
let nameError= $('.nameError');
if (name.length > 20) {
nameError.text("Too many characters!");
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<form method="POST" id="form" action="/post.php">
<input type="text" class="name" name="name" placeholder="Name" required/>
<label class="nameError"></label> <br/>
<input class="button" type="submit" value="Submit"/>
</form>
I want to make a custom validity message to my form, and there are some problem.
The validity message will show after click two times.
and if I don't input correct word "text" first time, then it will not submit anymore.
what's the problem in my code.
JS:
function a(){
jQuery("#text")[0].setCustomValidity("");
if (jQuery("#text").val() == "text"){
return confirm('sure?');
}
jQuery("#text")[0].setCustomValidity("Incorrect");
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/" method="post" onsubmit="return a();">
<input type='text' id="text"/>
<input type="submit" value="submit"/>
</form>
Please try to check below solution:
$(document).on('click',"#submit_btn", function()
{
if($("#text").val() === "text")
return confirm('sure?');
else
$("#text")[0].setCustomValidity("Incorrect");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/" method="post">
<input type='text' id="text"/>
<input type="submit" value="submit" id="submit_btn"/>
</form>
I am using JavaScript to validate email. The problem is, when the email ids don't match, then one alert button will come. Once I click the button it still takes me to the other page, instead of same page to correct my mail id.
HTML:
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="validate()">
JavaScript:
function validate()
{
if(document.getElementById("email").value != document.getElementById("confirm_email").value)
alert("Email do no match");
}
You need to tell the submit button to not perform the submit
function validate()
{
if (document.getElementById("email").value!=document.getElementById("confirm_email").value) {
alert("Email do no match");
return false;
}
}
The problem is because You have taken button type=submit
Change input type='button'
<input type="button" name="submit" value="submit" class="button" onClick="validate()">
and submit form using javascript
document.getElementById("myForm").submit();
I case you want to validate only on submit then use
event.preventDefault();
and then validate but after successful validation you have to submit the form using js or jq. JS method is given above and jq method is:
$("form").submit();
You should add return false; in your if code block if you dont want the redirect.
Its the browser's default to refresh the page when the form is submitted. To prevent this refresh, add return false;.
Learn more: return | MDN
<html>
<head>
<script>
function validate(){
if(document.getElementById("email").value != document.getElementById("confirm_email").value){
alert("Email do no match");
return false;
}
}
</script>
</head>
<body>
<form action="formsubmit.php" method="post" onsubmit="return validate()">
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button">
</form>
</body>
</html>
Use the below javascript code, your html code is correct!
Well executing the JavaScript code in StackOverflow Script Runner won't run and occur erorrs. If input boxes with email and confirm_email id(s) are declared, this should work.
Hope it could help!
function validate(){
if(!document.querySelector("#email").value === document.querySelector("#confirm_email").value){
alert("Email do not match.");
}
}
/* In JavaScript, the ! keyword before the condition belongs to execute the statement if the given condition is false. */
It must prevent the form to get submitted if the validation is failed. so
return validate();
must be there. So if the validate function returns a false value then it will stop the form to be submitted. If the validate function return true then the submission will be done.
<form method='post' action='action.php'>
<label for="department">Email ID</label>
<input type="email" size="30" name="email" id="email" required />
<label for="department">Confirm Email ID</label>
<input type="email" size="30" name="cname" id="confirm_email" required />
<input type="submit" name="submit" value="submit" class="button" onClick="return validate();">
</form>
<script>
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate(){
if(!validateEmail(document.getElementById('email').value))
{
alert('Please enter a valid email');
email.focus();
return false;
}
else if(document.getElementById('email').value!=document.getElementById('confirm_email').value) {
alert('Email Mismatch');
confirm_email.focus();
return false;
}
return true;
}
</script>
Fix that and remove type=submit and use a function or use following code:
<script>
function check(){
//* Also add a id "submit" to submit button*//
document.querySelector("#submit").addEventListener("click", function(){
//* Perform your actions when that submit button will be clicked and close with this in next line*//
})</script>
I have a simple form, with one issue.
In explorer, if nothing is inserted, the placeholder is passed as input of the field.
Here is JSbin: http://jsbin.com/EvohEkO/1/
I would like to make a simple comparision, when form is submitted, to check if the value of the field is equal to "First name", and if yes make the value empty ""
Just this i need.
Someone can help me please?
<form onsubmit="return checkform()">
<input name="test" placeholder="placeholdertext" id="test" />
<input type="submit" value="submitbutton"/>
</form>
in js
you should import jquery latest version this is the link: http://code.jquery.com/jquery-1.10.2.min.js
function checkform(){
var fieldvalue = $.trim($('#test').val());
if(!fieldvalue || fieldvalue=="placeholdertext"){
alert('there is no input');
return false;
}else{
alert('enjoy your form!');
return true;
}
}
This is somewhat easier..
$(document).ready(function(){
$("#form").submit(function(){
$('#form input:text, textarea').each(function() {
if($(this).val()==$(this).attr('placeholder'))
$(this).val(" ");
});
});
});
Just put your field value in hidden type input like this :-
<input id="hdnfield" name="hdnfield" value="<Your Field Value>" />
To check the value of a form field use the val() function on the input element
var input_value = jQuery('Input Element Selector').val();
As I looked to your form, the elements do not have any id attribute, I recommend that you add one to each of them, also change the submit input to button the you have more control on the javascript. so your form will look like :
<form id="form" action="form.php" method="post">
<input id="fname" type="text" placeholder="First name" name="fname"><br>
<label for="fname" id="fnamelabel"></label>
<input id="lname"type="text" placeholder="Last name" name="lname"><br>
<textarea id="message" placeholder="Contact us!" cols="30" rows="5" name="message"></textarea><br>
<br>
<input type="button" value="Submit">
</form>
so your jQuery will look like:
jQuery(document).ready(function(){
jQuery('input[type="button"]').click(function(){
var fname = jQuery('#fname').val();
var lname = jQuery('#lname').val();
var message = jQuery('#message').val();
...... Do whatever you need & then change the input values
...... if all validation has passed the use jQuery('#form').submit(); to submit the form otherwise reset the form:
jQuery('#fname').val("");
jQuery('#lname').val("");
jQuery('#message').val("");
});
});
here is a working version:
jsfiddle working link
You can do it like the following!
<form>
<input type="text" id="first_name" name="first_name"/>
<input type="submit" id="submit" value="submit"/>
</form>
<script type="type/javascript"/>
jQuery.noConflict();
(function ($) {
$(function () {
$("#submit").click(function () {
if ($("#first_name").val() == "first name") {
$(this).val("");
}
});
});
})(jQuery);
</script>
I am trying to run a javascript code but it is not running. I don't know why?
Here is the code sample:
Javascript:
<Script Language="text/Javascript">
function validateForm()
{
var x=document.forms["form1"]["Injection"].value;
var y=document.forms["form1"]["limit"].value;
if (x==null || x=="")
{
alert("Injection must be filled out");
return false;
}
if (y==null || y=="")
{
alert("Limit must be filled out");
return false;
}
return true;
}
</Script>
HTML:
<form name="form1" method="post" action="/OT_Stock/addnewinjection.jsp" onsubmit="return validateForm()">
<input type="text" name="Injection" maxlength="100" size="20" value="" style="textfield">
<input type="text" name="limit" maxlength="100" size="20" value="" style="textfield" >
<input type="submit" value="Add Name" class="buttonmain">
Please tell me where I am going wrong?
Remove the onclick from the button
Add onsubmit="return validateForm()" to the form element.
The crucial bit is the return keyword. Without it the form will always submit. With it, when the validateForm method returns false (invalid form) the form will not submit.
Edit: OP has updated his question with the above suggestions.
forma name is " form1", instead of it should be "form1".Don't use language in the script tag instead use type='text/javascript'.