Angular how to submit and validate form with <a> - javascript

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- <link rel="stylesheet" type="text/css" href="login.css"> -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-messages.min.js"></script>
</head>
<body ng-app="loginApp">
<div class="container">
<div class="login_logo">
</div>
<div class="form_container" ng-controller="loginCtrl" >
<div class="error_msg" ng-if="form_login.username.$dirty" ng-messages="form_login.username.$error">
<div class="alertmsg" ng-message="required">Username and password are required</div>
</div>
<div class="form_left">
<form class="form_login" name="form_login" ng-submit="submitForm()" novalidate>
<div class="usr"><input id="username" name="username" ng-model="username" type="text" autofocus="autofocus" required /></div>
<div class="psw"><input id="password" name="password" ng-model="password" type="password" required /></div>
</form>
</div>
<div class="form_right">
<a class="submit" href="" ng-click="submitForm()">submit</a>
</div>
<div class="clear"></div>
</div>
</div>
<script type="text/javascript">
var app=angular.module("loginApp",["ngMessages"]);
app.controller("loginCtrl", function($scope){
$scope.username = "";
$scope.password = "";
$scope.submitForm=function(){
};
});
</script>
</body>
</html>
Now I have a login page as it shows above, I'm trying to do the validation with ngMessages
If I have to use <a> which is outside of form to submit it instead of button, how should I do?
How can I make sure error messages are displayed when username or password is empty, and only after user submit the form.
How to prevent user from resubmitting form with <a>?

To show error messages only after form submit, add a variable '$scope.submitted = true;'.
In order to prevent re-submit submit button can be disabled.
Please refer following link for detailed explanation.
https://scotch.io/tutorials/angularjs-form-validation
Hope it helps.

You can check the validation result in your controller function with:
if ($scope.form_login.$valid) {
...
}
The form in angularjs will be validated auto. For all form members you can check the doc

Related

how to make login w/ html, css and javascript

So, I have the HTML & CSS code already, but I need to make it so when you click button, it checks the contents of the input boxes and if equal to
Username = damon
Password = password
it lets you redirects to chat.html and if its wrong it does alert("wrong").
(I dont know JavaScript so I'm asking here.)
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div id="content">
<div class="login">
<h1>Login</h1>
<input placeholder="username" type="text" >
<input placeholder="password" type="password" id="password">
<button type="button" onclick="" id="enter">ENTER</button>
</div>
</div>
</body>
<script src="script/db.js"></script>
<script src="script/main.js"></script>
</html>
db.js is empty and main.js has
function clickHandler() {
if (username === 'damon' && password === 'poop'){
window.location.replace("chat.html");
} else {
alert('Wrong!')
}
}
Hardcoding or doing user login checks on client side is not recommended as anyone can read the source and find out your login credentials.
But just assume that you just wanted to learn and try it out. You may do it like this.
Inline Onclick Function Call:
//this is main.js
function clickHandler() {
if (document.getElementById("username").value === "damon" && document.getElementById("password").value === 'poop'){
console.log("redirect to chat.html");
//window.location.replace("chat.html");
} else {
alert('Wrong!');
}
}
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="style/main.css">
</head>
<body>
<div id="content">
<div class="login">
<h1>Login</h1>
<!--Added id="username" to below input-->
<input placeholder="username" id="username" type="text" >
<input placeholder="password" id="password" type="password">
<!--You may use inline onclick to call clickHandler function-->
<button type="button" onclick="clickHandler()" id="enter">ENTER</button>
</div>
</div>
</body>
<script src="script/db.js"></script>
<script src="script/main.js"></script>
</html>
Or you may do it by attaching onclick listener to the button to call function.

In Google sheets I have a form in my sidebar that is not submitting the data. What is wrong with my code?

I'm new to coding and I wanted to make data entry more uniform in my worplace. And so I have been trying to create a html form in a sidebar and submit the resulting data to a speadsheet.
I have my form and my sidebar working but no matter what I try or which tutorial I follow I can't seem to wrap my head around how to get the data from the html form to my spreadsheet.
Here is the .gs
function onOpen(){
SpreadsheetApp.getUi()
.createMenu('Menu CFC')
.addItem('Ajout','showSidebar')
.addToUi();
showSidebar();
}
function showSidebar(){
var html = HtmlService.createHtmlOutputFromFile('menuCFC')
.setTitle('Mon menu CFC')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
function formCFCSubmit(form_data){
var sheet = spreadsheetApp.getActive().getSheetByName('Feuille 1');
sheet.([form_data.nom,form_data.numéro])
}
and here is a simplified version of my html form for testing purpose.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form name="formAjoutCFC">
<div class ="block form-group">
<label for="Nom">Nom</label>
<input type="text" name="nom" id="nom" placeholder="Nom" required>
</div>
<div class ="block form-group">
<label for="Numéro">Numéro</label>
<input type="text" name="numéro" id="numéro" placeholder="Numéro" required>
</div>
<div class="block">
<button type="submit" class="action">Valider</button>
</div>
<div calss="block">
<input type="reset">
</div>
</form>
<script>
document.querySelector("#formAjoutCFC").addEventListener("submit", //not sure about the #
function(e)
{
e.preventDefault();
google.script.run.formCFCSubmit(this);
);
</script>
</body>
</html>
Any help would be welcome as I'm out of my depth at the moment ^^
You are doing all right #Lugh, very close to your goal indeed. But you need to take care of some things:
Your showSideBar function is alright too.
On your formCFCSubmit(form_data) you have errors:
The class you want to call from is SpreadsheetApp not (s)preadsheetApp.
sheet.([form_data.nom,form_data.numéro]) is not an existing method.
// For testing purposes, you can paste the data in ranges "A1" and "B1" for example:
function formCFCSubmit(form_data){
var sheet = SpreadsheetApp.getActive().getSheetByName('Feuille 1');
sheet.getRange('A1').setValue(form_data.nom);
sheet.getRange('B1').setValue(form_data.numero);
// Notice accent removed from numero!
// Putting accents in code will give you headaches sooner than later...
}
On your menuCFC.html:
Here is where most of your trouble is coming from...
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<!-- Notice 'id'! That's what the # in the query selector is referencing. Not name -->
<form id="formAjoutCFC">
<div class="block form-group">
<label for="Nom">Nom</label>
<input type="text" name="nom" id="nom" placeholder="Nom" required>
</div>
<div class="block form-group">
<label for="Numero">Numéro</label>
<input type="text" name="numero" id="numero" placeholder="Numéro" required>
</div>
<div class="block">
<button type="submit" class="action">Valider</button>
</div>
<div class="block">
<input type="reset">
</div>
</form>
<script>
document.querySelector("#formAjoutCFC")
.addEventListener(
"submit",
function(e) {
e.preventDefault();
google.script.run.formCFCSubmit(this);
}
);
</script>
</body>
</html>
Now the script in your sidebar, can get the form by id, and when submitted execute the formCFCSubmit function that does what you want it to with form_data.
Keep on coding!
Notes:
You should read official documentation now that you are into coding.
Read about the SpreadsheetsApp class from Apps Script's Spreadsheet service to find out which functions you can use to tailor to your need.

AngularJS show email field error on submit?

I have a form in Angular JS 1.5.11.
I have it set up to show an error message for empty required fields on form submit. I need to add the ability to also detect if an email is valid on submit.
So far, I can't get this to work. I tried using the "built-in" email field validation, the tried an ng-pattern. Still, no matter what you type in the field, it shows no error. Only the empty field show an error.
<div class="row">
<div class="col-md-12">
<div class="form-group" ng-class="{ 'has-error' : abc.myForm.$submitted && abc.myForm.email.$error.required && abc.myForm.email.$error.pattern }">
<label>Email</label>
<input type="email" name="email" class="form-control" ng-model="abc.user.email" ng-pattern="emailFormat" required>
<p class="help-block error-block">Enter a valid email address.</p>
</div>
</div>
</div>
See the whole form at https://plnkr.co/edit/3lAMOM3agSMGC9AAr2IT?p=preview
Update
To clarify, I am using novalidate because I don't want to use the HTML5 built-in error message. If I remove that, I get
instead of
First of all, sorry for misinterpreting the question. For getting the state of any input feild inside a form, You could use $valid state for that. Like for your form, you could call like {{abc.myForm.email.$valid}} inside your form and this would return true or false.
See, type email is HTML5 property and if you put no validate in form, default validation of HTML5 will not work. Remove novalidate from form and use it.
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="bootstrap#3.3.7" data-semver="3.3.7" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.10/angular.min.js" data-semver="1.5.10"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl as abc">
<p>Hello {{abc.name}}!</p>
<form name="abc.myForm" ng-submit="abc.save(abc.user)" >
<div class="row">
<div class="col-md-12">
<div class="form-group" ng-class="{ 'has-error' : abc.myForm.$submitted && (abc.myForm.email.$error.required || abc.myForm.email.$error.pattern) }">
<label>Email</label>
<input ng-pattern = '/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i' type="email" name="email" class="form-control" ng-model="abc.user.email" required="" />
<p class="help-block error-block">Enter a valid email address.</p>
</div>
</div>
</div>
<p ng-show="abc.myForm.email.$error.pattern">
Not valid email!
</p>
<input type="submit" class="btn btn-primary">
</form>
</body>
</html>

Submit button not working on login form, using PHP and JavaScript

I am trying to code a simple login page using JavaScript and PHP to help validate the user input values with the values in a database.
However, my submit button doesn't seem to do anything... it just clears the fields.
Here is my code. There are probably MANY errors in it and I apologize for that... the PHP code I wrote is from a collection of other login pages I found on the web and I only started learning JavaScript a couple days ago...
EDIT: I have updated the code based on the mistakes that you guys pointed out. The log in button now no longer refreshes but instead doesn't do anything. I will try to figure it out or start from scratch since there is so much code that I don't understand, haha.
login.html:
`<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<title>Login</title>
</head>
<body>
<div class="header">
<div class="container">
<h1>Login</h1>
</div>
</div>
<div class="form">
<form class="form-horizontal">
<div class="form-group">
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUsername3" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class=" col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox">Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input id="submit" type="submit" class="btn btn-default" value="Log in">
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="js/vendor/jQuery.md5.js"></script>
<script src="login.js"></script>
</div>
</body>
</html>'
login.js
$(document).ready(function(){
$("form").on("submit", function(e){
e.preventDefault();{
var username = $('#inputUsername3').val();
var password = $('#inputPassword3').val();
var newPw = $.md5(password);
if (username != "" && password !="") {
$.ajax ({
url: "doLogin.php",
type: "POST",
async: false,
data: "$username="+username+"&password="+newPw,
success: function(result) {
window.open(success.html);
}
});
} else {
alert("Please enter a username and password.");
}
return false;
});
});
doLogin.php:
<?php
$host="localhost";
&username="";
$password="";
$db_name="atasgtsar";
$tbl_name="members";
$connection =
mysqli_connect("$host", "$username", "$password")or die("Unable to connect.");
mysqli_select_db("$db_name");
$myUsername=$_POST['username'];
$myPassword=$_POST['password'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysqli_real_escape_string($myusername);
$mypassword = mysqli_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysqli_query($sql);
$count=mysqli_num_rows($result);
if ($count == 1) {
session_register("myusername");
session_register("mypassword");
}
else {
echo "Wrong username or password.";
}
mysqli_close($connection);
?>
Your fields are cleared as the submit button reloads the page.
Use preventDefault(); to stop the submit from happening as you want to submit the data yourself using ajax.
$("form").on("submit", function(e){
e.preventDefault();
//...
Please do not store passwords as plain text in databases, use password_hash() and password_verify().
The MySQL Version you use is deprecated, please use MySQLi or PDO.
There is no type='username', use 'text'.
You call "check(this.form)" from the submit button, but you already bind the jQuery handler to the submit event using js.
If you want to select elements by there ID in jQuery, instead of input[id=username], use #username
Also, there sure are more mistakes in these codes.
I would always recommend to start with an extremely basic layout, print out all information (in js using console.log or alert and in php using echo) and then go n small steps, until you got your working code.
You read out the wrong input fields in your JS and remove the $ in your data string which will send via post.
Here is the correct version.
$(document).ready(function(){
$("#submit").click(function(){
var username = $('input[id=inputUsername3]').val();
var password = $('input[id=inputPassword3]').val();
var newPw = $.md5(password);
if (username != "" && password !="") {
$.ajax ({
url: "doLogin.php",
type: "POST",
async: false,
data: "username="+username+"&password="+newPw,
success: function(result) {
alert(result)
}
});
}
else {
alert("Please enter a username and password.");
}
return false;
});
});
You have also forget the " on the end of the ID.
<div class="col-sm-10">
<input type="username" class="form-control" id="inputUsername3" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
You have done too many mistakes in HTML and Javascript coding:
<html>
<head>
<link href='https://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="bootstrap.min.css">
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<title>Login</title>
</head>
<body>
<div class="header">
<div class="container">
<h1>Login</h1>
</div>
</div>
<div class="form">
<form class="form-horizontal">
<div class="form-group">
<div class="col-sm-10">
<input type="text" class="form-control" id="inputUsername3" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class=" col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox">Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<input id="submit" type="submit" class="btn btn-default" value="Log in">
</div>
</div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="js/vendor/jQuery.md5.js"></script>
<script src="login.js"></script>
</div>
</body>
</html>
Than in your javascript code:
$(document).ready(function(){
$("#submit").click(function(){
var username = $('#inputUsername3').val();
var password = $('#inputUsername3').val();
var newPw = $.md5(password);
if (username != "" && password !="") {
$.ajax ({
url: "doLogin.php",
type: "POST",
async: false,
data: "$username="+username+"&password="+newPw,
success: function(result) {
alert(result)
}
});
}
else {
alert("Please enter a username and password.");
}
return false;
});
});
In the HTML the "tpye" attribute of the input with name "username" should be "text" and you've forgot to close the quotes after the "id" attribute:
<input type="text" class="form-control" id="inputUsername3" name="username" placeholder="Username">
In your Javascript it seems like you use jQuery but I dont see where you include the library.
The javascript selectors for IDs should be defined like this:
var username = $('#inputUsername3').val();
var password = $('#inputPassword3').val();
Keep in mind that there could be more things that I haven't notice.
The browser automatically posts your data when you click in an submit button that is inside your form, what you have to do is to prevent this default behaviour so that it actually uses your JS code.
change
$("#submit").click(function(){
for
$("form").on("submit", function(e){
e.preventDefault();
Your fields are beeing cleared because your button is a submit button and because you are not redirecting the client to any other page, it refreshes it. From what I see you want to use AJAX, try to use just a simple button with a onclick event (type="button").

how to access form data in servlet using angular js

I am new to angular js. please help me with the below issue
I have a form with a controller loginController. I have two text boxes user.email and user.password.
I want to post the data to servlet onclick of the Log in button.
I have written the following code, but when i click Log in, the data is not getting posted on to the server. Also there is no error message.
Below is my JSP file
`
<html ng-app="practiceApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel ="stylesheet" type="text/css" href="bootstrap.min.css"/>
</head>
<body>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="practice.js"></script>
<form name='login' ng-controller='loginController' ng-submit="login()">
<div>
{{hello}}
<label>Email</label>
<input type="email" name="email" ng-model="user.email" required/>
<span ng-show='login.email.$dirty && login.email.$error.required'>Required</span>
<span ng-show='login.email.$dirty && login.email.$error.email'>Not a valid email</span>
<label>Password</label>
<input type="password" name="password" ng-model="user.password" required/><br/>
<span ng-show='login.password.$dirty && login.password.$error.required'>Required</span>
<button ng-disabled="login.$invalid">Log in</button>
</div>
</form>
</body>
</html>
`
JavaScript File
`
var app = angular.module('practiceApp',[]);
app.controller('loginController',function($scope,$http){
$scope.login = function(){
$http({
method: 'POST',
url:'/login',
headers:{'Content-Type':'application/json'},
data:$scope.user
}).success(function(data){
$scope.status=data;
});
}
});
`
I have tried all the solutions that are available but couldn't find any result.. Kindly help on this
Your <button> does not cause the form to submit. Change to <input type="submit" ng-disabled="login.$invalid">Log in</button> or remove ng-submit from the form and add ng-click="login()" to the <button>.

Categories