I'm having trouble with AngularJS form validation. Below is a simple two-field form with the only requirements being that data for each field is required, one of which is of "email" type.
The trouble is, no matter what I put as the value for either of the two fields, Angular's .$valid always returns the value of true and $invalid returns the value of false. It can be an empty field, a valid/invalid email address, or as long a string as I choose. The result is the same.
Therefore, the submit button is never disabled because I'm using
ng-disabled="FormLogin.$invalid"
However, if I use a variable from the controller, the submit button is disabled
ng-disabled="disableSubmit"
This suggests that Angular is working, but I haven't set up the directives correctly in the form controls. Note that ng-model directives appear to applied correctly.
I've tried many different variations of code on them, some pretty desperate, to no avail. There are other SO questions regarding this same subject, but I didn't find any that applied. Any suggestions you may have would be great. Thanks.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="formCtrl" align="center" style="width:400px;padding: 10px 10px 10px 10px;">
<table class="table table-stripe"><form name="FormLogin" ng-submit="submitForm(FormLogin.$valid)" novalidate>
<tr>
<td>User:</td>
<td>
<input type="email" name="email" class="form-control" ng-model="email" required />
</td>
</tr>
<tr>
<td>Pwd:</td>
<td><input type="password" name="password" class="form-control" ng-model="password" required /></td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit" class="form-control" style="width:200px;" ng-disabled="FormLogin.$invalid">Log In</button>
</td>
</tr></form>
</table>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.disableSubmit = true;
$scope.email = 'testUser#testDomain.com';
$scope.password = 'y!keZ';
$scope.submitForm = function(isValid) {
alert($scope.email + ':' + $scope.password + ':' + isValid);
};
});
</script>
</body>
</html>
Your issue is due to invalid html, you have nested the form directly under table which is incorrect and the browser will throw it out of the table (or whatever it decides to do) as it renders (before even angular processes the DOM) and the angular validations does not work properly.
Demo wrapping the table inside the form
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.disableSubmit = true;
$scope.email = 'testUser#testDomain.com';
$scope.password = 'y!keZ';
$scope.submitForm = function(isValid) {
console.log($scope.email + ':' + $scope.password + ':' + isValid);
};
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="formCtrl" align="center" style="width:400px;padding: 10px 10px 10px 10px;">
<form name="FormLogin" ng-submit="submitForm(FormLogin.$valid)" novalidate>
<table class="table table-stripe">
<tr>
<td>User:</td>
<td>
<input type="email" name="email" class="form-control" ng-model="email" required />
</td>
</tr>
<tr>
<td>Pwd:</td>
<td>
<input type="password" name="password" class="form-control" ng-model="password" required />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<button type="submit" class="form-control" style="width:200px;" ng-disabled="FormLogin.$invalid">Log In</button>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
Related
I am new to AngularJS and working on a small project. I want to build an editable table for courses including course Id and course Name. Users are able to click edit button and then they can edit content.
Howwever,I met a problem that when user clicks edit button, all the content just gone, like delete, but I want to keep the content editable. I try ng-value, but didn't work.
Here is my code and codepen link: http://codepen.io/marong125/pen/JRBQdo
Thank you so much!
<html>
<head>
<title>Online Learning</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script>
var app = angular.module('app', []);
app.controller('courseController', function ($scope) {
$scope.courses = [
{
courseID: "CS602",
courseName: "Web Development",
isEditing:false
},
{
courseID: "CS502",
courseName: "Foundation of Java",
isEditing:false
}
];
$scope.addCourse = ()=>{
$scope.courses.push({
courseID: $scope.createIdInput,
courseName: $scope.createCourseInput
});
$scope.createIdInput = '';
$scope.createCourseInput = '';
console.log(1);
}
$scope.onEditClick = (course)=>{
course.isEditing = true;
}
});
</script>
</head>
<body ng-app="app">
<<h1>Course Manager</h1>
<div ng-controller = "courseController">
<form name="courseForm">
<input id="c_id_input" placeholder="Add course ID" ng-model="createIdInput" />
<input id= "c_name_input" placeholder="Add course name" ng-model="createCourseInput" />
<button class="btn btn-success pull-right" ng-click="addCourse()">Add Course</button>
</form>
<table class="table table-striped table-bordered table-condensed table-hover">
<tr>
<th>Course ID</th>
<th>Course Name</th>
<th>Actions</th>
</tr>
<tr ng-repeat = "course in courses">
<td>
<span ng-if="!course.isEditing" >{{course.courseID}}</span>
<form ng-submit="updateTask(course)">
<input type="text" ng-if="course.isEditing" class="form-control"
ng-value="course.courseID" ng-model="updatedCourseId" />
</form>
</td>
<td>
<span ng-if="!course.isEditing">{{course.courseName}}</span>
<form >
<input ng-if="course.isEditing" class="form-control"
ng-value="course.courseName" ng-model="updatedCourseName" />
</form>
</td>
<td>
<button class="btn btn-info" ng-click="onEditClick(course)" >Edit</button>
<button class="btn btn-danger">Delete</button>
</td>
</tr>
</table>
</div>
</body>
</html>
This is happening because of your ng-model in the edit fields. If you look closely you will find that ng-model for your ID field in updatedCourseId and Name is updatedCourseName. However your actual values are stored in course.courseID and course.courseName. Change your ng-model and point to the correct variables.
<input type="text" ng-if="course.isEditing" class="form-control"
ng-value="course.courseID" ng-model="updatedCourseId" />
<input ng-if="course.isEditing" class="form-control"
ng-value="course.courseName" ng-model="updatedCourseName" />
Alternatively
If you don't want to mix up the updated value and the non-updated value you can do that by copying the current value to another field when the user clicks on edit. I have created a codepen to demonstrate this, you can see it here.
JavaScript (Controller)
$scope.onEditClick = (course) => {
course.isEditing = true;
course.updatedCourseId = course.courseID;
course.updatedCourseName = course.courseName;
}
HTML
<input type="text" ng-if="course.isEditing" class="form-control"
ng-model="course.updatedCourseId" />
<input ng-if="course.isEditing" class="form-control"
ng-model="course.updatedCourseName" />
I think you are misunderstanding how ng-model works. ng-model represents the variable that your data is saved in, and it's a two way binding. You don't need a separate variable to store the "updated" values.
Instead of:
<input type="text" ng-if="course.isEditing" class="form-control"
ng-value="course.courseID" ng-model="updatedCourseId" />
you should use:
<input type="text" ng-if="course.isEditing" class="form-control"
ng-model="course.courseID" />
The changes will automatically be reflected, in real time, back to the array.
I am setting up a simple php form to collect entries and insert/show them to a myphpmyAdmin db, this works fine. The little problem I'm having is when i try to put in a small bit of js to clear text and also give a popup alert, neither will work, can somebody help me please.
Here is my Javascript file:
function clear(){
document.getElementById("in1", "in2", "in3", "in4", "in5",).value= "";
}
function saved() {
alert("Well done yourself, you have saved an entry to the database.");
}
And here is my php file:
<html>
<head>
<meta charset="utf-8">
<title>CS230 Assignment 3</title>
<link rel="stylesheet" href="style1.css" type="text/css" media="all" />
<script src="myjs.js" type="text/javascript"></script>
</head>
<body>
<h3>Diary:</h3>
<form action="insert.php" method="post">
<div id="table">
<table>
<tr>
<th>When/Where</th>
<th>Event</th>
<th>Emotion</th>
<th>Automatic Thoughts</th>
<th>Rational Response</th>
</tr>
<tr>
<td><input type="text" style="height:500px;" name="in1" id="in1"></td>
<td><input type="text" style="height:500px;" name="in2" id="in2"></td>
<td><input type="text" style="height:500px;" name="in3" id="in3"></td>
<td><input type="text" style="height:500px;" name="in4" id="in4"></td>
<td><input type="text" style="height:500px;" name="in5" id="in5"></td>
</tr>
</table>
</div>
<div id="buttons">
<input type="submit" name="save" id="save" value="Save Entry" onclick="saved()">
</div>
</form>
<div id="clearButton">
<button id="clear" onClick="clear();">clear</button>
</div>
<form action="show.php" method="post">
<input type="submit" name="show" id="show" value="Show Diary">
</form>
</body>
</html>
The document.getElementById() function takes one argument. If you want to fetch a list of elements, you can use .querySelectorAll():
var elements = document.querySelectorAll("#in1, #in2, #in3, #in4, #in5");
That returns a node list, so you'll have to iterate to perform an operation on each one:
function clear(){
var elements = document.querySelectorAll("#in1, #in2, #in3, #in4, #in5");
for (var i = 0; i < elements.length; ++i)
elements[i].value = "";
}
edit — you'll probably want to use a name other than "clear" as "clear" is likely to collide with something; in-line event handlers are highly susceptible to that sort of issue. Alternatively you could explicitly reference window.clear():
<button id="clear" onClick="window.clear();">clear</button>
I am making a simple validation of required, but unable to find ng-Message working on wrong entry or on clicking submit. Can someone help me out where am I wrong?
HTML:
<html>
<head>
<!-- Script Files -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<form name="form1" id="form1" novalidate>
<input type="text" name="age" ng-minlength="3" required/>
<div ng-messages="form1.age.$error" ng-show="(form1.age.$error.required || form1.age.$error.minlength) && (form1.age.$touched || form1.$submitted) " >
<div ng-message="required">This is required</div>
<div ng-message="minlength">Length is too less</div>
</div>
<a data-ng-click="submit(form1.$invalid)">Click</a>
</form>
<script>
//module declaration
var app = angular.module('myApp', ['ngMessages']);
//controller declaration
app.controller('myCtrl', function($scope) {
var submit = function(invalid){
if(invalid) return;
}
});
</script>
</body>
</html>
Your age input has no ng-model. Validation alá minlength only works if ng-model is present:
<input type="text" name="age" ng-model="age" ng-minlength="3" required/>
This is due to how validators work. You'll notice ng-model is not set, when $valid is false. There's always a hint in the docs as well: https://docs.angularjs.org/api/ng/directive/ngMinlength
Also ng-model doesn't need to be the same as the field name.
I am trying to build a status comment type of system using angularJS. The first textbox allows the user to put the value in an array and thus display it on the page. On clicking also allows a textbox and a button to enter the comment. The value of comment however is not displaying inside the scope. The code is :
HTML
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="status.js"></script>
<body ng-app="myApp" ng-controller="userCtrl">
<div>
<h2>Status!</h2>
Post status here :<br>
<textarea rows="5" cols="50" ng-model="value"></textarea>
<button ng-click="addstatus()">Click to Add!</button>
<br><br><br>
<table>
<tr ng-repeat="add in statushow">
<td><h3>{{add.value}}</h3>
<input ng-model="commentvalue" type="text" size="40" placeholder="Enter your comment here!"></input>
<button ng-click="addcomment()">Add comment!</button>
<table>
<tr ng-repeat="comms in comments">
<td><h4>{{comms.commentvalue}}</h4></td></tr></table>
</td>
</tr>
</table>
{{commentvalue}}
</div>
STATUS.JS
var app = angular.module('myApp', [])
app.controller('userCtrl', function($scope) {
$scope.statushow = [];
$scope.comments = [];
$scope.addcomment= function(){
$scope.comments.push({
commentvalue: $scope.commentvalue
});
$scope.value="";
};
$scope.addstatus= function(){
$scope.statushow.push({
value: $scope.value
});
$scope.value="";
};
});
Try with this http://jsfiddle.net/rrfqaf9L/2/:
<div ng-app="myApp" ng-controller="userCtrl">
<h2>Status!</h2>
Post status here :
<br>
<textarea rows="5" cols="50" ng-model="value"></textarea>
<button ng-click="addstatus()">Click to Add!</button>
<br>
<br>
<br>
<table>
<tr ng-repeat="add in statushow">
<td>
<h3>{{add.value}}</h3>
<input ng-model="add.commentvalue" type="text" size="40" placeholder="Enter your comment here!"></input>
<button ng-click="addcomment(add)">Add comment!</button>
<table>
<tr ng-repeat="comms in add.comments">
<td>
<h4>{{comms.commentvalue}}</h4>
</td>
</tr>
</table>
</td>
</tr>
</table>{{commentvalue}}</div>
Javascript:
var app = angular.module('myApp', [])
app.controller('userCtrl', function($scope) {
$scope.statushow = [];
$scope.addcomment= function(add){
if (typeof add.comments == 'undefined') add.comments = [];
add.comments.push({
commentvalue: add.commentvalue
});
add.commentvalue="";
};
$scope.addstatus= function(){
$scope.statushow.push({
value: $scope.value
});
$scope.value="";
};
});
A suggestion would be not to use specific keywords such as add, value as model or variable names.
You could send the model through the function as a parameter:
<textarea rows="5" cols="50" ng-model="status"></textarea>
<button ng-click="addstatus(status)">Click to Add!</button>
<table>
<tr ng-repeat="stat in statushow">
<td><h3>{{stat.value}}</h3>
<input ng-model="commentvalue" type="text" size="40" placeholder="Enter your comment here!"></input>
<button ng-click="addcomment(commentvalue)">Add comment!</button>
<table>
<tr ng-repeat="comms in comments">
<td><h4>{{comms.commentvalue}}</h4></td></tr></table>
</td>
</tr>
</table>
{{commentvalue}}
</div>
Modify the controller as:
$scope.addcomment= function(comment){
$scope.comments.push({
commentvalue: comment
});
};
$scope.addstatus= function(status){
$scope.statushow.push({
statusvalue: status
});
};
See fiddle: http://jsfiddle.net/HB7LU/15033/
The quickest way to do it would be to change the following and add $parent. NG-Repeat creates child scopes, so the input box wasn't adding the correct scope.
<input ng-model="$parent.commentvalue" type="text" size="40" placeholder="Enter your comment here!"></input>
Here's the code pen.
http://codepen.io/shuffguy/pen/gpezOM?editors=101
Trying to get this form to validate email using the function the professor said to use. We cannot use jquery or any other way to handle this. He's very...specific...on how he wants things done. Anyway, last week of a web design course and introduces javascript without much explanation.
The function is simply validating email but I have no frickin clue on how to call the function properly (verify_email). I've found countless examples of how to do this other ways but I'm pretty sure he will take off points for not doing it his way. Frantically trying to format this on an edit... it was fine when I submitted.
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Feedback</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="media/css/webpageCSS.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery /1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function verify_email ()
{
var email_val=document.getElementById("email").value;
var regex = /^[A-Z0-9_%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if( email_val.search( regex ) == -1)
{
alert("Email is not valid");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body class="sdd">
<nav>
Home
Resume
Class List
Miscellaneous
Feedback
</nav>
<header>
<h1 class="sd">Feedback Page</h1>
</header>
<div id="wrapper">
<div id="leftcolumn2">
</div>
<div id="rightcolumn2">
<section>
<br><br>
Feedback Form:
<form name="comform" method="post" action="http://webdevfoundations.net/scripts/formdemo.asp" onsubmit="return verify_email();">
<table class="comtab">
<tr>
<td>*First Name: <input type="text" name="fname" id="fname"></td>
<td>*Last Name: <input type="text" name="lname" id="flname"></td>
</tr>
<tr>
<td id="com" colspan="2"><textarea cols="60" rows=5 name="comments" id="comments">Enter your feedback here</textarea></td>
</tr>
<tr>
<td class="alignl" colspan="2">Email (optional): <input type="text" name="email" id="email"></td>
</tr>
<tr>
<td class="alignl" colspan="2"><input type="submit" value="Submit Comment" ></td>
</tr>
</table>
</form>
</section>
<footer class="footbot">
© 2010
</footer>
</div>
</div>
try this
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Feedback</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link type="text/css" rel="stylesheet" href="media/css/webpageCSS.css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function verify_email ()
{
var email_val=document.getElementById("email").value;
var regex = /^[A-Z0-9_%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if( email_val.search( regex ) == -1)
{
alert("Email is not valid");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body class="sdd">
<nav>
Home
Resume
Class List
Miscellaneous
Feedback
</nav>
<header>
<h1 class="sd">Feedback Page</h1>
</header>
<div id="wrapper">
<div id="leftcolumn2">
</div>
<div id="rightcolumn2">
<section>
<br><br>
Feedback Form:
<form name="comform" method="post" action="http://webdevfoundations.net/scripts/formdemo.asp" onsubmit="return verify_email();">
<table class="comtab">
<tr>
<td>*First Name: <input type="text" name="fname" id="fname"></td>
<td>*Last Name: <input type="text" name="lname" id="flname"></td>
</tr>
<tr>
<td id="com" colspan="2"><textarea cols="60" rows=5 name="comments" id="comments">Enter your feedback here</textarea></td>
</tr>
<tr>
<td class="alignl" colspan="2">Email (optional): <input type="text" name="email" id="email"></td>
</tr>
<tr>
<td class="alignl" colspan="2"><input type="submit" value="Submit Comment" ></td>
</tr>
</table>
</form>
</section>
<footer class="footbot">
© 2010
</footer>
</div>
</div>
</body>
</html>
Try using
<script type="text/javascript">
function verify_email (email_val)
{
var regex = /^[A-Z0-9_%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if( email_val.search( regex ) == -1)
{
alert("Email is not valid");
return false;
}else{
return true;
}
}
</script>
In the body of your page you need to register the function with the input for the email.
<input type="text" name="email" onchange="verify_email()" />
Are you wanting to pass the string "email" to the email validation function? Or do you want to actually check whatever is in the email input? If you're just passing "email" to test, it needs to be in quotes (') for it to be passed correctly.
This might be the problem:
function verify_email(email_val)
{
var regex = /^[A-Z0-9_%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (email_val.search(regex) == -1)
{
alert("Email is not valid");
return false;
}
return true;
}
It will always return true. Also, search doesn't handle Regex. You need to run the string onto the regex. This code might work:
function verify_email(email_val)
{
var regex = /^[A-Z0-9_%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (regex.exec(email_val) == -1)
{
alert("Email is not valid");
return false;
} else {
return true;
}
}
Also, see the comment Matt Phillips posted: Homework help, what am I doing wrong here? [Javascript, validation].
Also, verify_email(email) is not defined. You should use verify_email(document.getElementById('email').value).
The javascript variable email is not defined anywhere so you are passing an undefined variable to the javascript function. call the function like
<input type="submit" value="Submit Comment" onclick="verify_email(document.getElementById('email').value);">