I only want to perform this function if the other two fields are not empty, not sure how to do it.
ng-click="saveToList($event)"
HTML
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" class="form-control" placeholder="" ng-model="mvName" />
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="text" id="urlLink" class="form-control" placeholder="" ng-model="mvUrl" />
</div>
<div class="col-xs-2">
Post
</div>
app.js
$scope.saveToList = function(event) {
var mvName = $scope.mvName.trim();
var mvUrl = $scope.mvUrl.trim();
if (mvName.length > 0) {
$scope.favUrls.$add({
name: mvName,
title: mvUrl
});
urlName.value = ''; //urlName is the ID of input box - Angular rocks!
urlLink.value = ''; //urlName is the ID of input box - Angular rocks!
}
}
I get this error when they are empty:
Error: $scope.mvName is undefined
The problem isn't anything to do with Angular: .trim() doesn't work against undefined values. Check to see if the variable is defined before trying to trim it, for example:
var mvName = ($scope.mvName) ? $scope.mvName.trim() : '' ;
You should initialize $scope.mvName in your controller! As it is empty, you are getting an error at line var mvName = $scope.mvName.trim();
EDIT
Post
You can add ng-disabled directive to your a tag. Something like this:
<a href ng-disabled="!mvName || !mvUrl" ng-click="saveToList($event)" class="btn btn-block post">Post</a>
or check that vars in your js:
$scope.saveToList = function(event) {
if(!$scope.mvName || !$scope.mvUrl)
return;
var mvName = $scope.mvName.trim();
var mvUrl = $scope.mvUrl.trim();
...
You could do it like this:
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" class="form-control" placeholder="" ng-model="mvName" />
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="text" id="urlLink" class="form-control" placeholder="" ng-model="mvUrl" />
</div>
<div class="col-xs-2">
<a href="javascript:"
ng-click="(mvName != '' && mvUrl != '') && saveToList($event)" class="btn btn-block post">Post</a>
</div>
Or use ng-disabled="mvName === '' && mvUrl === ''"
Other options would be to not render the button: ng-if or ng-show.
How about performing a simple check to see if the fields are empty or not, before you perform any comparisons using the value. That should solve the issue I believe.
<form name="myForm">
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" required class="form-control" placeholder="" ng-model="mvName" />
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="text" id="urlLink" required class="form-control" placeholder="" ng-model="mvUrl" />
</div>
<div class="col-xs-2">
Post
</div>
</form>
Try using the angular validation.
Related
i'm trying to learn Javascript and some basic HTML with bootstrap v5.
I created a Sign-in form and now i'm try to do some validation for the required field.
I follow the Bootstrap documentations and i managed to get validation for all my input field except for the password, i want to verify if the password are the same or if they are empty field...but i'm stuck.. not familiar with javascript.
my attempt in javascript:
let forms = document.querySelectorAll(".needs-validations");
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
Array.prototype.slice.call(forms).forEach( function (form){
form.addEventListener("submit",function (ev) {
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.className = 'form-control is-invalid'
pass2.className = 'form-control is-invalid'
}
if (!form.checkValidity()){
ev.preventDefault()
ev.stopPropagation()
}
form.classList.add("was-validated")
})
})
but here the result:
As you can see password is always valid and i don't understand why.
my html:
<body class="body">
<div class="center">
<h4 class="title">Sign Up New User</h4>
<form name="signin-form" method="post" class="needs-validations" novalidate id="forms">
<div class="container">
<div class="row mt-3">
<div class="col">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" required>
<div class="invalid-feedback">
Name can't be empty
</div>
</div>
<div class="col">
<label for="surname" class="form-label">Surname</label>
<input type="text" class="form-control" id="surname" placeholder="Surname" required>
<div class="invalid-feedback">
Surname can't be empty
</div>
</div>
</div>
<div class="row mt-3">
<div class="col">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" required>
<div class="invalid-feedback">
invalid email
</div>
</div>
<div class="col-4 text-end">
<label for="email" class="form-label">Role</label>
<select class="form-select" id="validationCustom04" required>
<option selected disabled value="">Choose...</option>
<option>Captain</option>
<option>First Officer</option>
</select>
<div class="invalid-feedback">
Please select role
</div>
</div>
</div>
<div class="row mt-3 ">
<div class="col">
<label for="password1" class="form-label ">Password</label>
<input type="password" class="form-control" id="password1" placeholder="Password">
</div>
<div class="col">
<label for="password2" class="form-label ">Confirm Password</label>
<input type="password" class="form-control" id="password2" placeholder="Password">
<div class="invalid-feedback">
Password not match
</div>
</div>
</div>
<div class="row-cols-2 mt-3">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</form>
</div>
<script src="/validation.js"></script>
<script src="/js/bootstrap.bundle.min.js" ></script>
</body>
What I don't understand is, that your password fields seem to be having a valid class in your posted screenshot. But I can't find it anywhere in your code (neither HTML nor JS).
I'd do it like this:
(Note: I didn't test this code, but it should work. If it works and you want to learn from it, I recommend to read through it step by step and apply it to your logic instead of just copy pasta.)
let form = document.querySelector("form.needs-validations");
// or, to be more specific:
// let form = document.querySelector("form[name='signing-form']")
form.addEventListener("submit",function (ev) {
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.classList.add('is-invalid');
pass2.classList.add('is-invalid');
}
if (!form.checkValidity()){
ev.preventDefault();
ev.stopPropagation();
}
form.classList.add("was-validated");
})
Note: the functionality to validate the content of your password-fields will only be triggered once you hit the submit button.
I have this form and I tried to make a "onsubmit" that when I click submit it checks if the "email" is = to "cemail" and if username was taken before or not i got this so far
<form class="form-horizontal" action="#" method="post" onsubmit="return ValidationEvent()">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
Javascript code:
<script>
function ValidationEvent() {
var email = document.getElementById("email").value;
var username = document.getElementById("username").value;
var cemail = document.getElementById("cemail").value;
// Conditions
if (email.match != cemail.match) {
alert("Your email doesn't match!");
}
if(mysqli_num_rows($result) != 0)
{
alert("Username already taken!");
}
else {
alert("Thank you");
}
}
</script>
Am I approaching the function in the wrong way is there another easier way and is it okay i put an sql statement in my java script ?
First, don't use inline HTML event handling attributes (like "onsubmit") as they create "spaghetti code", anonymous global event handling wrapper functions and don't conform to the modern W3C DOM Event handling standard.
Second, your .php results have to be gotten from somewhere. You'll need to put a call into that file for its results before you can use them.
Next, you were using the .match() string method incorrectly to compare the emails against each other. All you really need to do is compare the values entered into the email fields (it's also a good idea to call .trim() on form values to strip out any leading or trailing spaces that might have been inadvertently added).
Once you restructure your code to use standards, the JavaScript will change as follows (FYI: This won't work in the Stack Overflow snippet environment because form submissions are blocked, so you can see a working version here):
// When the DOM is loaded:
window.addEventListener("DOMContentLoaded", function(){
// Get references to the DOM elements you will need:
var frm = document.getElementById("frm");
// Don't set variables to the values of DOM elements,
// set them to the DOM elements themselves so you can
// go back and get whatever properties you like without
// having to scan the DOM for them again
var email = document.getElementById("email");
var username = document.getElementById("username");
var cemail = document.getElementById("cemail");
// Set up a submit event handler for the form
frm.addEventListener("submit", validationEvent);
// All DOM event handling funcitons receive an argument
// that references the event they are responding to.
// We need that reference if we want to cancel the event
function validationEvent(evt) {
// Conditions
if (email.value.trim() !== cemail.value.trim()) {
alert("Your email doesn't match!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
return;
}
// You need to have already gotten the "mysqli_num_rows($result)" value
// from your .php file and saved it to a variable that you can then check
// here against "!=0"
if(mysqli_num_rows($result) != 0) {
alert("Username already taken!");
// Cancel the form submit event
evt.preventDefault();
evt.stopPropagation();
} else {
alert("Thank you");
}
}
});
<form class="form-horizontal" id="frm" action="#" method="post">
<fieldset>
<legend>SIGN UP! <i class="fa fa-pencil pull-right"></i></legend>
<div class="form-group">
<div class="col-sm-6">
<input type="text" id="firstName" placeholder="First Name" class="form-control" name="firstname" autofocus required>
</div>
<div class="col-sm-6">
<input type="text" id="lastname" placeholder="Last Name" class="form-control" name="lastname" autofocus required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="username" placeholder=" Username" name="username" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="password" id="password" placeholder="Password" name="password" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" id="datepicker" placeholder= "DOB" name="birthday" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-1"></label>
<div class="col-sm-8">
<div class="row">
<label class="radio-inline">
<input type="radio" id="radio" value="Female" name= "gender" required>Female
</label>
<label class="radio-inline">
<input type="radio" id="radio" value="Male" name= "gender">Male
</label>
</div>
</div>
</div> <!-- /.form-group -->
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<button type="submit" class="btn btn-primary btn-block">Register</button>
</div>
</div>
</form>
For checking the emails with email & cemail use
email.localeCompare(cemail)
This will check the string comparison betwwen two emails
And for mysqli_num_rows , is not defined any where in javascript, so we will get the undefined error in console, so need to write a different funnction with that name.
First give a name and an action to your form
<form class="form-horizontal" id="myform" action="chkValues.php" method="post" >
....
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="email" placeholder="Email" name="email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input type="email" id="cemail" placeholder=" Re-enter Email" name="cemail" class="form-control" required>
</div>
</div>
....
</form>
Then put this script at the bottom
<script>
$('#myForm').on("sumbit", function(){
// cancel the original sending
event.preventDefault();
$.ajax({
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.serialize();
})
.done: function(data) // is called wehn the call was okay
{
if( data.substr(0, 5) == "Error"){
alert(data); // sent the sting of the "error message" begining with "Error"
}else{
top.location.href = data; // sent the sting of the "success page" when all was okay and data are saved in the database
}
}
.fail(function() {
alert( "Error: Getting data from Server" );
})
});
</script>
in the php file check the values an return an error if something went wrong.
<?php
if(!isset($_POST['email']) || !isset($_POST['cemail'])){
die("Error: Please fill out both email fields.");
if($_POST['email'] != $_POST['cemail'] ){
die("Error: The Email adresses do not match.");
}
here do what you want to do with the data.
when finish just send the new url
echo "success.html";
}
?>
I have the following code and it works fine to check if the input field "inputURL" has a valid URL, if it has the anchor link a.btn shows fine but I also only want it to show if both have been filled in. How can I add to the ng-show in the anchor to do this?
<form name="myForm" class="row inputs">
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" id="urlName" class="form-control" placeholder="" ng-model="mvName" >
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="url" name="inputURL" id="urlLink" class="form-control" placeholder="" ng-model="mvUrl" >
</div>
<div class="col-xs-2">
Post
</div>
</form>
You can check if both have been filled with the model like this:
ng-show="myForm.inputURL.$valid && mvName && nvUrl"
or with the view value of the input
ng-show="myForm.inputURL.$valid && myForm.inputURL.$viewValue && myForm.urlName.$viewValue"
You can use the required HTML5 special attribute to check if the input is not empy.
<form name="myForm" class="row inputs">
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a Title/Description</label>
<input type="text" name="mvName id="urlName" class="form-control" placeholder="" ng-model="mvName" required>
</div>
<div class="col-xs-5">
<label for="exampleInputPassword1">Enter a URL</label>
<input type="url" name="inputURL" id="urlLink" class="form-control" placeholder="" ng-model="mvUrl" required>
</div>
<div class="col-xs-2">
Post
</div>
</form>
However, to clean the view a little bit, I would suggest using a controller. Expose a function which returns true or false if the form is valid. And simply use ng-show="isValid()".
consider I have such a structure(a group of fields which repeat);
<div class="form-group Row"> <!-- first row-->
<div class="col-sm-3">
<input type="text" class="form-control User" name="user" value="$users" placeholder="Username" />
</div>
<div class="col-sm-3">
<input type="password" class="form-control" name="pw" value="$passwords" placeholder="Password" />
</div>
<a class="delete" onclick='//do something'><img src="delete.png"></a>
</div>
<div class="form-group Row"><!-- second row-->
<div class="col-sm-3">
<input type="text" class="form-control User" name="user" value="$user" placeholder="Username" />
</div>
<div class="col-sm-3">
<input type="password" class="form-control" name="pw" value="$passwords" placeholder="Password" />
</div>
<a class="delete" onclick='//do something'><img src="delete.png"></a>
</div>
when I click on the delete-image of any Row, I want to get the value of the input field with class name "User" of this specific Row.
How can I do this in javascript?
If you use jQuery you don't need use inline events, you can add events with .on function, and get value like in example
$('.delete').on('click', function () {
var value = $(this).parent().find('.User').val();
console.log(value)
});
Example
Try as follows:
$('.delete').on('click', function(){
var value = $(this).closest('.row').find('.User').val();
//Do something with value;
});
In vanilla JS your "do something" will be like this:
alert( this.parentNode.getElementsByClassName("user")[0].value; )
I'm having trouble resetting form fields after submitting in AngularJS (v1.1.3). Here's a snippet of what I'm trying to do:
HTML
<form name="addMemberForm">
<input name="name" type="text" placeholder="Jon Doe" ng-model="member.name" required/></td>
<a class="btn btn-primary" ng-click="createMember(member)" ng-disabled="addMemberForm.$invalid"><i class="icon-plus"></i></a>
</form>
JS
$scope.createMember = function(member) {
var membersService = new Members(member);
membersService.$create(function(member) {
$scope.members.push(member);
$scope.addMemberForm.reset(); //TypeError: Object #<FormController> has no method 'reset'
});
};
Is there another way to reset form elements?
Figured it out thanks to #tschiela's comment. I had to do this:
$scope.createMember = function(member) {
var membersService = new Members(member);
membersService.$create(function(member) {
$scope.members.push(member);
$scope.member = '';
});
};
Just Take default value of the form .
HTML form
<form novalidate id="paperForm" class="form-horizontal" name="formPaper">
<div class="form-group">
<label class="col-sm-3 control-label" for="name">
Name
</label>
<div class="col-sm-8">
<input type="text" id="name" placeholder="Please Enter Name" class="form-control" ng-model="paper.name" ng-name="name" required>
</div>
<label class="col-sm-3 control-label" for="name">
Department
</label>
<div class="col-sm-8">
<input type="text" id="department" placeholder="Please Enter Department" class="form-control" ng-model="paper.department" ng-name="department" required>
</div>
</div>
<button type="button" class="btn btn-default" ng-click="reset(paper)">Reset</button>
</form>
set reset code inside controller
var deafualtForm = {
name : '',
department : ''
}
$scope.reset= function(paper) {
$scope.paper = angular.copy(deafualtForm);
}