<html>
<head>
<title>Coupon test code</title>
<style>
#error{
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<form name="couponField" action="">
<span id="error"></span>
Coupon code:
<input type="coupon" id="coupon" name="coupon">
<input type="button" id="submit" value="Apply Coupon Code">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$('#submit').click(function(){
if($('#coupon').val() == 'PROMO CODE'){
$('#error').text('correct code!');
}else{
$('#error').text('wrong code!');
}
});
</script>
</body>
</html>
The above code does the following:
1. Validate if the coupon code entered is exactly equal to 'PROMO CODE'
2. Validate if the field is empty.
What we are trying to do:
1. Keep the validation for 'PROMO CODE' intact.
2. Remove the validation for the empty field.
This is a part of an order form wherein we want the users to enter the promo code. But since all the users may not have the promo code we want to give the users the option to leave the field empty. The current validation is making this field a 'required' field.
Any suggestions are much appreciated. Thanks!
$('#submit').click(function(){
var input = $('#coupon').val();
if(input === 'PROMO CODE'){
$('#error').text('correct code!');
} else if (input !== ''){
$('#error').text('wrong code!');
}
});
make sure you use === instead of == in JavaScript.
Related
Basically, I have this very simple HTML form, when I submit, it does POST to /productos and runs a JS script that validates the form, if its not correct, it displays an error, all good.
But one thing I want to do is to "cancel" the POST if the form doesn't pass that validation, is there any way to do it?
I have thought about making the POST from the javascript function instead of from the form itself, but I have no idea how to do that
html:
<form name="registro" action="/productos" method='post' onsubmit="return validacion()">
<div>titulo</div>
<input type="text", name="titulo"/>
<input type="submit">
</form>
js validation:
function validacion(){
var titulo=document.registro.titulo.value;
if (titulo == ""){
alert("error, titulo cant be empty")
} else if (titulo.length > 100){
alert("error, titulo cant be more than 100 characters long")
}
make validacion() return true or false
function validacion(){
var titulo=document.registro.titulo.value;
if (titulo == ""){
alert("error, titulo cant be empty")
return false;
} else if (titulo.length > 100){
alert("error, titulo cant be more than 100 characters long")
return false;
}
return true;
}
<!DOCTYPE html>
<html>
<body>
<form name="registro" action="/productos" method="post">
<div>titulo</div>
<input type="text", name="titulo" required="required" />
<input type="submit">
</form>
</body>
</html>
no need for javascript run abounts are needed.
Its easier to use standard html5 with xhtml compatibility method, like this, for form validation:
<!DOCTYPE html>
<html>
<body>
<form name="registro" action="/productos" method="post">
<div>titulo</div>
<input type="text", name="titulo" required="required" />
<input type="submit">
</form>
</body>
</html>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I usually code in Java, but I knew a little HTML, so I decided I would learn more. My problem is that I have a password field and a submit button. When I hit the button, it checks to see if the password is right, and then asks you what your name is. It then changes a text field to say You got it right, NAME. The thing is, when you hit submit, the code submitted is added to the URL, so if you type password as the password, ?password is added on to the URL. That is fine with me, but since the URL is changed, the page reloads, making the text field go back to normal. I am using Google Chrome. Is there anyway around this, or is it because I am running a .HTML file, not going to a website?
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<title>Ryan Club Homepage</title>
<script>
function codeEnter(){
var s = document.getElementById("in").value;
var correct = "lolliPiper5";
if(s === correct){
var name = prompt("What is your name");
document.getElementById("cde").innerHTML = "You got the password right!, " + name;
}
}
</script>
</head>
<body style="font-family:'Myriad Pro' ">
<form onsubmit="codeEnter();">
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!">
</form>
</body>
</html>
Thank you!
You need to use JavaScript / jQuery to prevent the form from submitting. I am using jQuery 2.1.1.
For password field let's assume it 123 for now.
The e.preventDefault() method stops the default action of an element from happening. Here it stops the submit button to submit the form to URL specified in form's action attribute.
$(document).ready(function(){
$("#name_container").hide();
$('#submit').on("click",function(e){
e.preventDefault();
$password = $('#password').val();
if($password == '123'){
$("#password_container").hide();
$("#name_container").show();
$("#result").html("");
}
else{
$("#result").html("Password is incorrect.");
}
$name = $("#name").val();
if($name != '' && $name != null ){
$("#form").hide();
$("#result").html("You got it right, "+$name);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="page.html" method="post" id="form">
<div id="password_container">
Password: <input type="password" id="password" />
</div>
<div id="name_container">
Name: <input type="text" id="name" />
</div>
<input type="submit" id="submit">
</form>
<div id="result">
</div>
(Updated)
Here you go:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body style="font-family:'Myriad Pro' ">
<form id="form" method="post" action="#">
Password:
<input type="password" name="code" id="in">
<br />
<input type="submit" value="Ready!" id="submit">
</form>
<div class="ps"></div>
<script>
$(document).ready(function () {
$('#submit').on("click", function (e) {
e.preventDefault();
$password = $('#in').val();
if ($password == 'lolliPiper5') {
$name = prompt("Enter your name", "ACCESS GRANTED");
$(".ps").html("Welcome to the team, " + $name);
}
});
});
</script>
</body>
</html>
In your simplified (I hope) code you need at least set
<form onsubmit="return codeEnter()">
...
// and in the script
function codeEnter(){
var s = document.getElementById("in").value;
var correct = "lolliPiper5";
if(s === correct){
var name = prompt("What is your name");
document.getElementById("cde").innerHTML = "You got the password right!, " + name;
}
else return false; //do not submit
}
In the real world if you actually wanted to submit the password, hidden from the user you would change the form code to
<form onsubmit="codeEnter();" method="post">
By default the form submits data to the server via a GET request which causes the values to show in the url, thus this is usually only used for making queries such as page numbers (?page=num) etc (all insensitive data).
However, when you set method="post" the form sends data using a POST request which is invisible to the user and in some cases encrypted before sending and therefore much safer.
An example of a for using method="POST" can be found here
hello I have a simple form to validate I want to do a client side validation lets say that my form has only one field for name I want to check if the name length is between 5 and 20 chars if yes then no problem and the data will be sent to the server and then apply a server side validation ;however, if it's not then an error message will be displayed in a span beside the input field says that it must be 5 to 20 chars.The problem is when I hit the submit button it shows the result for less than a second then it goes cause the submit button reload the page which also means if I have included my server side validation it will also be processed since the input data already sent so how can I stop the submit button from sending data to the server and reloading the page without disabling the button.
here is my example code
<!doctype html>
<html>
<head>
<title>form validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$("#submit").click(function(){
myfunction();
});
function myfunction()
{
name = $("#user").val();
nameError = $(".error").first();
myError = "";
if(name.length < 5 || name.length > 20)
myError += "length should be between 5 and 20 ";
else
myError += "ok"
nameError.html(myError);
}
});
</script>
<style>
.error
{
color : red;
text-transform: capitalize;
margin-left: 20px;
}
</style>
</head>
<body>
<form method="post" action="">
NAME : <input type="text" name="user" id="user"><span class="error"></span><br />
<input type="submit" value="Submit" id="submit">
</form>
</body>
</html>
The problem is you're not canceling form submission on finding a problem.
To do this you'll need to listen for a submission event on the form, not a click event on the button.
Try:
$("form").on('submit', myfunction); //<-- listen for form submit, not button click
function myfunction(evt) { //<-- the event object is automatically passed along;
// this is key for suppressing submission
name = $("#user").val();
nameError = $(".error").first();
myError = "";
if(name.length < 5 || name.length > 20)
myError += "length should be between 5 and 20 ";
else
myError += "ok"
if (myError) {
evt.preventDefault(); //<-- suppress submission if error found
nameError.html(myError);
}
}
You could alternatively use HTML5 validation and make your life a little easier.
Just do one thing .It is very easy.Follow my code.There is no need of javascript or jQuery.Code is tested on my Pc.Hope will enjoy.
<form method="post" action="" >
NAME : <input type="text" name="user" pattern="[A-Z a-z.]{5,20}" title="Enter your name between 5 and 20 charecters" required="required" accesskey="U"/><br />
<input type="submit" value="Submit" id="submit">
$("#submit").click(function(){
if ($('#user').text.length > 4 ){
myfunction();
}else{
// show error message
}
});
try this, do validate on click not in the function
Try this one..
<!doctype html>
<html>
<head>
<title>form validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$( document ).ready(function() {
function myfunction()
{
name = $("#user").val();
nameError = $(".error").first();
myError = "";
if(name.length < 5 || name.length > 20){
myError += "length should be between 5 and 20 ";
return false;
}
else{
myError += "ok"
nameError.html(myError);
return true;
}
}
});
</script>
<style>
.error
{
color : red;
text-transform: capitalize;
margin-left: 20px;
}
</style>
</head>
<body>
<form method="post" action="" onSubmit="return myFunction();">
NAME : <input type="text" name="user" id="user"><span class="error"></span><br />
<input type="submit" value="Submit" id="submit">
</form>
</body>
</html>
I have a form that has a textarea field for input. I want an alert to pop up if the field is empty on submit.
I copied some code that works fine on an input field; however, it does not work for the textarea (it submits with no alerts whether empty or not).
I read through some other questions posted here and made some modifications.
Now, it alerts when empty, but it also alerts when there is text and does not submit.
I am new to this. I am using asp classic.
Code:
<form method="post" action="reasonProcess.asp" name="formName" onSubmit="return Validate()">
<table >
<tr>
<td>Please enter a reason for the change:<br>
<textarea style="width:675px;height:75px" rows="12" cols="10" name="changereason" > <%=dbchangereason%> </textarea></td>
</tr>
</table><br>
<input type=button value="Approve" onClick="javascript:saveAndSubmit()" class="btn" style="float:none;font-size:.78em;">
</form>
<script>
function saveAndSubmit()
{
// Check for reason entered.
if (!document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
var queryString = "reasonProcess.asp?Approve=Yes";
document.formName.action=queryString;
document.formName.submit();
// window.close();
}
</script>
This is line of code that works properly with the input text field:
if (!document.formName.changereason.value)
I have also tried:
if (!document.formName.changereason.value.length == 0)
and get the alert without text and with text.
Thanks for any help.
UPDATED
'!' is the logical not operator in JavaScript.
The condition in your code say if the value of changereason textarea is not empty show alert() because of the ! sign that mean not, but what you want is the contrary (if field is empty then show alert), so try just to remove the sign and it will work, do the follow change :
Replace :
if (!document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
By :
if (document.formName.changereason.value == '') //removing the ! sign in this line
{
alert("Enter a reason.");
return false;
}
See Working fiddle.
If that not work take a look at External simple page with the same code that is not a fiddle and it should work also in your machine, code of external example :
<!DOCTYPE html>
<html>
<head><title></title>head>
<body>
<form method="post" action="reasonProcess.asp" name="formName" onSubmit="return Validate()">
<table >
<tr>
<td>Please enter a reason for the change:<br>
<textarea style="width:675px;height:75px" rows="12" cols="10" name="changereason" > <%=dbchangereason%> </textarea>
</td>
</tr>
</table>
<br>
<input type=button value="Approve" onClick="javascript:saveAndSubmit()" class="btn" style="float:none;font-size:.78em;">
</form>
<script>
function saveAndSubmit()
{
// Check for reason entered.
if (document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
var queryString = "reasonProcess.asp?Approve=Yes";
document.formName.action=queryString;
document.formName.submit();
// window.close();
}
</script>
</body>
</html>
If that work and not the first example then maybe you have another part of code tha caused a problem and that is not referenced in the question.
Good luck.
change
if (!document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
to
if (document.formName.changereason.value == '')
{
alert("Enter a reason.");
return false;
}
The ! means "not" - so you were saying if the value is not empty then alert.
In form tag write
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkform(this);">
This is your input field
<textarea name="reviewValue"></textarea>
Javascript Code:
<script language="JavaScript" type="text/javascript">
function checkform ( form ){
if (form.reviewValue.value == "") {
alert( "Please choice your Rating." );
form.reviewValue.focus();
return false ;
}
return true ;
}
</script>
Trying to filter out spam from an online form. I have a hidden div with an input. The idea is that if something goes into the field, the form will ID the user as a bot and reject the submission. After trying to implement this method, the bots are still getting through. I'm not very familiar with javascript (or spam-filtration, for that matter) - here's what I'm working with:
html (within the form):
<form action="#" method='post' id='vsurvey' name='defer'>
<div id="hp-div">
If you see this, leave this form field blank
and invest in CSS support.
<input type="text" name="question_20579" value="" />
</div>
<input type="submit" value="Submit Request" />
</form>
css:
#hp-div { display: none }
js:
<script type="text/javascript" charset="ISO-8859-1" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" charset="ISO-8859-1" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script type="text/javascript">
if(!String.IsNullOrEmpty(Request.Form["question_20579"]))
IgnoreComment();
</script>
<![if !IE]>
<script type="text/javascript">
$(document).ready(function(){
$("#vsurvey").validate({
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'Oops! You missed 1 field. It has been highlighted'
: 'Oops! You missed ' + errors + ' fields. They have been highlighted below';
$("div.alert span").html(message);
$("div.alert").show();
} else {
$("div.alert").hide();
}
},
errorPlacement: function(error, element) {
return true;
}
})
});
</script>
<![endif]>
In my opinion, a honeypot should consist of ALL of the below:
A field hidden by CSS
A field hidden by JavaScript
A field requiring a blank input
A field requiring a specific input
For instance:
<div class="input-field">
Please leave this blank
<input type="text" name="contact" value="" />
</div>
<div class="text-field">
Please do not change this field
<input type="text" name="email" value="your#email.com" />
</div>
Using CSS, hide the first field:
.input-field { display: none; }
Using jQuery, hide the second field:
$('.text-field').hide();
// or
$('.text-field').addClass('hide');
Then a couple of very simple checks in PHP:
if($_POST['contact'] == '' && $_POST['email'] == 'your#email.com') {
// Not a bot
}