I've created a form that goes something like this:
<form action="#" class="header_form clearfix">
<input type="text" placeholder="Enter Your Address" id="autocomplete">
Enter Your Address
</form>
I want to place a Javascript condition to check if the text input has text in it before the button would have the onclick parameters. If it has no text on keyup, the onclick is not on button. How to do so?
If you are using jQuery, you could do something like this:
$('.btn').on('click', function() {
var email = $.trim( $('#autocomplete').val() );
if(email.length) {
window.location = '/address?address='+email;
} else {
alert('Enter your email first');
}
});
$.trim is there to at least prevent empty spaces triggering a valid submit.
In any case you'd better go with an EMAIL regex pattern: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
This will disable the link if its not a valid email address too
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
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);
}
$( document ).ready(function() {
$('#autocomplete').bind('input', function() {
if ($(this).val().trim().length === 0) {
document.getElementById('myButton').removeAttribute('href');
} else {
if (validateEmail(document.getElementById("autocomplete").value) === true) {
document.getElementById('myButton').setAttribute("href",'/address?address=' + document.getElementById("autocomplete").value);
} else {
document.getElementById('myButton').removeAttribute('href');
}
}
});
document.getElementById('myButton').removeAttribute('href');
});
</script>
<form action="#" class="header_form clearfix">
<input type="text" placeholder="Enter Your Address" id="autocomplete" />
Enter Your Address
</form>
</body>
</html>
Related
I'm trying to validate a login form but I cannot understand the reason why when I give a wrong input the message from setCustomValidation doesn't show up the first time I click on the submit button (actually input). However when I click on the same button a second time the error message appears as it should. Why is that?
Here's the code.
function validate(){
console.log("check validate()")
var email = document.getElementById("email");
var psw = document.getElementById("psw");
const patt = /^(([^<>()[\]\\.,;:\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,}))$/;
if (email.value=="" && psw.value==""){
email.setCustomValidity("You need to insert email and password!");
return false;
}
else if ( email.value==""){
email.setCustomValidity("Insert your email address");
return false;
}
else if (psw.value==""){
psw.setCustomValidity("Insert password");
return false;
}
else if ( !patt.test(email.value) ){
email.setCustomValidity("This is not an email!");
console.log("Subcase works");
return false;
}
}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Game</h1>
<div>
<form onsubmit="return validate()" method="POST" action="login.php">
<input id="email" type="text" placeholder="email">
<input id="psw" type="password" placeholder="password">
<input type="submit" id="login-btn" value="Accedi">
</form>
</div>
</body>
</html>
Firstly, according to the documentation for setCustomValidity:
You must call the reportValidity method on the same element or nothing will happen.
The reason it works the second time is because when the custom validity message is set, when the "submit" button is clicked again, the browser's built-in form validation takes over and blocks the submit. That is why you do not see the "check validate()" message in the console log on subsequent submits.
Therefore, merely adding something like email.reportValidity() after your email.setCustomValidity is not a solution because on subsequent submits, the submit event handler will not get called, because the form never gets submitted due to the non-null custom validity message. If you try this, you will see that you get the same error message even after filling out the email and password fields. To fix this, you can either add novalidate to the form to bypass the browser validation, or you can clear the custom validity message when the input changes using the input's onchange event.
Here is a working example by adding novalidate to the form and using reportValidity().
function validate(){
console.log("check validate()")
var email = document.getElementById("email");
var psw = document.getElementById("psw");
const patt = /^(([^<>()[\]\\.,;:\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,}))$/;
if (email.value=="" && psw.value==""){
email.setCustomValidity("You need to insert email and password!");
email.reportValidity();
return false;
}
else if ( email.value==""){
email.setCustomValidity("Insert your email address");
email.reportValidity();
return false;
}
else if (psw.value==""){
psw.setCustomValidity("Insert password");
psw.reportValidity();
return false;
}
else if ( !patt.test(email.value) ){
email.setCustomValidity("This is not an email!");
email.reportValidity();
console.log("Subcase works");
return false;
}
}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Game</h1>
<div>
<form onsubmit="return validate()" method="POST" action="login.php" novalidate>
<input id="email" type="text" placeholder="email">
<input id="psw" type="password" placeholder="password">
<input type="submit" id="login-btn" value="Accedi">
</form>
</div>
</body>
</html>
Here is a working example using the onchange event on the input fields and using reportValidity(). Notice in this case, the onsubmit handler is only called after the validity message has been cleared and not every time you click the submit button.
function validate(){
console.log("check validate()")
var email = document.getElementById("email");
var psw = document.getElementById("psw");
const patt = /^(([^<>()[\]\\.,;:\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,}))$/;
if (email.value=="" && psw.value==""){
email.setCustomValidity("You need to insert email and password!");
email.reportValidity();
return false;
}
else if ( email.value==""){
email.setCustomValidity("Insert your email address");
email.reportValidity();
return false;
}
else if (psw.value==""){
psw.setCustomValidity("Insert password");
psw.reportValidity();
return false;
}
else if ( !patt.test(email.value) ){
email.setCustomValidity("This is not an email!");
email.reportValidity();
console.log("Subcase works");
return false;
}
}
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Game</h1>
<div>
<form onsubmit="return validate()" method="POST" action="login.php">
<input id="email" type="text" placeholder="email" onchange="event.target.setCustomValidity('')">
<input id="psw" type="password" placeholder="password" onchange="event.target.setCustomValidity('')">
<input type="submit" id="login-btn" value="Accedi">
</form>
</div>
</body>
</html>
I have a problem. There is something wrong with the code as even when the input like abc56, it still alert "Enter your name". Or when the input is abc, it should be displayed "Perfect" instead of "Enter your name". The input only allows characters not number and I think the regex is correct, the only wrong is the logic. Can you guys help me?
var check=document.forms["check"]["name"].value;
var reg=/^[a-zA-Z]+$/;
function ipt(){
if(check !== ""){
if(check.match(reg)===false){
alert("Only enter character please");
}
else{
alert("Perfect");
}
}
else{
alert("Enter your name");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
<script src="./check.js" defer></script>
</head>
<body>
<form name="check" onsubmit="ipt()">
<label for="name">Name</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
</body>
</html>
you get the value of document.forms["check"]["name"] on page load.
not the value onsubmit event
and your regex usage is wrong, use RegExp.prototype.test()
it return a boolean value ( true or false)
do
const name_elm = document.forms.check.name
, reg = /^[a-zA-Z]+$/
;
function ipt() {
if (!!name_elm.value) // or if (name_elm.value !== '')
{
if (reg.test(name_elm.value))
{ alert('Perfect') }
else
{ alert('Only enter character please') }
}
else {
alert('Enter your name');
} }
You can clean up the if statement by using an else if.
When you check for a value in a form, use value when you need to see what the current value is.
var check = document.forms["check"]["name"];
var reg = /^[a-zA-Z]+$/;
function ipt(){
// check if its empty
if (check.value === "") {
alert("Enter your name");
// check if it matches the pattern
} else if (!check.value.match(reg)) {
alert("Only enter character please");
} else {
// Success!
alert("Perfect");
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Check</title>
<script src="./check.js" defer></script>
</head>
<body>
<form name="check" onSubmit="return ipt()">
<label for="name">Name</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
</body>
</html>
Wondering, is there a way to make a form execute default operation after preventingDefault and validating form fields.
$('#form').submit(function (e) {
e.preventDefault();
var isValid = true;
var name = $('#name').val();
if (empty(name)) {
isValid = false;
}
$(this).submit() // This will cause a stack overflow :)
});
After I complete the form validation I want to proceed as normal,
I thought of using onClick on the submit button, but users can trigger submit by hitting on the enter key, which I want to allow. Reason why I want to do this is so that the server can perform its operations like redirecting.
I am writing you a small example.
$(document).ready(function(){
$("#control_form").on("keyup", function(event){
post_control();
});
});
var post_control = function(){
var user_name = $("#user_name").val();
if ( user_name==null || user_name=="" || user_name.length < 4 )
$('.error').html("Username can not be less than 4 characters!");
else
{
$('.error').empty();
$('#control_form').removeAttr('onsubmit');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="users_form">
<form name="form" id="control_form" action="post_form" method="post" onsubmit="return false;">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name">
<input type="submit" value="Save">
</form>
<div class="error"></div>
</div>
Instead of using preventDefault, you can return true at the end of the function.
If you want to prevent the submission, you can return false.
Here's an example using your code. If you try to submit the form with an empty field, it won't submit. If you fill the field, it will:
$("#form").submit(function() {
var name = $("#name").val();
if (!name) {
$(".form-group").addClass("has-danger");
alert("Field is blank. Submit will be prevented.");
return false; // no submission
}
alert("Field is filled. The form will submit.");
return true; // form submits
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='form'>
<div class="form-group">
<label class="form-control-label" for="name">Name</label>
<input type="text" class="form-control" id="name">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
CodePen Demo
check this it works.I tested it.
$(document).ready(function(){
$('#form1').submit(function (e) {
if($('#name').val() == ''){
alert('Name is empty');
return false;
}
$(this).submit();
});
});
I have been reading through many articles relating to this but they only show how to prevent anything happening not only the page refresh.
But I need to have it so when enter key is pressed the text field is submitted via a ajax request without the page refresh, like how I can use the input type button with a onclick event.
iv added a very basic mock up below to help explain what I mean.
<html>
<head>
<title>Demo</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.2/jquery.min.js'></script>
</head>
<body>
<form id="someForm" action="" method="post">
<!--
below is an example of the text field
id like to submit but without the
page refreshing when "Enter" is pressed
-->
<input type="text" id="demoText"/>
<button type="button" id="postBtn" onclick="postText()">Post</button>
</form>
<script>
function postText() {
alert("Random Function...");
}
</script>
</body>
</html>
You can do something like this to capture the keypress event of a control - say an input box.
$(function() {
$('#demoText').keypress(function (e) {
var key = e.which;
if(key == 13) // enter pressed
{
postText();
}
});
});
There are more examples here
To post using Ajax, do something like this:
var postText = function() {
var stuff = $.post("serverpage.php", function() {
alert( "success" );
}).fail(function() {
alert("error");
}
)};
No need for any script, the browser will do it for you if you have a submit button ( not type="button") and bind your function to submit event of the form
<form id="someForm" action="" method="post" onsubmit="postText();return false">
<input type="text" id="demoText" />
<button type="submit" id="postBtn">Post</button>
</form>
DEMO
After the advise given here this is what i came up with and it is fully functional, so thought id add it here as an answer so anyone else with a similar question can view my solution.
<html>
<head>
<title>Demo</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
</head>
<body>
<form id="form">
<input type="text" class="input" id="chatTxt" placeholder="Chat post..."/>
<input type="button" id="submit" value="Submit"/>
</form>
<script type="text/javascript">
$('form').keypress( function( e ) {
var code = e.keyCode || e.which;
if( code === 13 ) {
e.preventDefault();
$( "#submit" ).click();
};
})
$(document).ready(function(){
$("#submit").click(function(){
var ChatText = $("#chatTxt").val();
if(ChatText ==''){
alert("Chat text is empty!");
}
else{
$.post("demo.php",{ ChatText1: ChatText },
function(data) {
alert(data);
$('#form')[0].reset();
});
}
});
});
</script>
</body>
</html>
I want, If balance field is <0, If Recharge amount filed >0 then form not submit, Can you give me Java script or php code please. Here is my editing code but not working I dont understand. Please give me solutions
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
form.onsubmit = function(e){
if(document.getElementById("bal").value==30){
e.preventDefault();
alert("Value must not be equal to 30");
}
if(document.getElementById("bal").value<0){
e.preventDefault();
alert("error msg");
return false;
}
if(document.getElementById("amount").value>0){
e.preventDefault();
alert("error msg");
return false;
}
};
</script>
</head>
<body>
<form action = '' method='post' name="recharge">
<input type="text" id="bal" name="bal" value="">Balance</><br>
<input type="text" id=="number" name="number" value="">Rehcarge number</><br>
<input type="text" id="amount" name="amount" value="">Amount</><br>
<input type="submit" name="submit" value="SUBMIT">
</form>
</body>
</html>
Try:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery("input[name='button']").click(function(e){
//getting your balance amount
bal = jQuery("input[name='balance']").val();
//if balance is lesser than 0, form will be submitted
if(bal<0){
jQuery('form').submit();
}
});
});
</script>
Make sure your input fields are enclosed inside <form></form> tags.
You can check the submitted balance value like
$balance = $_REQUEST['balance']; if($balance <=30){ echo "cant submit form"; header("location: your form path ") ; }
Or you can user jQuery to check the value and show alert message to user
You can do this via javascript or using any of the js libraries, check on form submit as below:
Try
var form = document.getElementById("fr");
form.onsubmit = function(e){
if(document.getElementById("bal").value==30){
e.preventDefault();
alert("Value must not be equal to 30");
}
return true
};
See demo here
do in jquery like this
$("input[type=submit]").click(function(e){
if($("input[name=amount]").val() == "30")
{
alert("you have entered amount as 30. Form not submitted");
return false;
}
else if($("input[name=amount]").val() > $("input[name=balance]").val())
{
alert("you dont have enough balance");
return false;
}
});
And Add this
<script type="text/javascript" src="code.jquery.com/jquery-1.10.2.min.js"></script>
to head of html
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($)
{
jQuery("input[name='submit']").click(function(e)
{
balance = jQuery("input[name='balance']").val();
amount = jQuery("input[name='amount']").val();
if(balance < 0 && amount > 0)
{
alert('Balance is less than 0 and amount is greater than 0 : So not submitting');
jQuery('form').submit();
}
else
{
alert('Balance is greater than 0 : So not submitting');
}
});
});
</script>
<form action = '' method='post'>
<input type="text" name="balance" value="">Balance</><br>
<input type="text" name="number" value="">Rehcarge number</><br>
<input type="text" name="amount" value="">Amount</><br>
<input type="submit" name="submit" value="SUBMIT">
</form>