AngularJS hiding input field - html

I am writing a login page with register and login options using AngularJS. There are three input fields: username, password and name. I want name field to appear when I click to register button and disappear when I click to login button. Therefore I want to change input field's class to 'hidden' on click and let css handle the job. How can I do it using AngularJS? Is there a better way to hide the name input field?
HTML:
<h2>Welcome to Mail Service</h2>
<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>
<!-- NAME INPUT FIELD -->
<div class="textField-hidden">
<label><b>Name</b></label><br>
<input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>
<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>
</div>
</form>
AngularJS Controller:
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.login = function()
{
var loginRequest = $resource('/api/login');
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
var registerRequest = $resource('/api/register');
loginRequest.save($scope.user, function(response)
{
});
};
}]);

You need to use ng-hide or ng-show directive (based on your context), and provide it with appropriate condition value like this:
$scope.showName = false;
$scope.login = function() {
// Your code
$scope.showName = false;
}
$scope.register = function() {
// Your code
$scope.showName = false;
}
Change your HTML accordingly:
<input ng-show="showName" type="{{type}}" placeholder="Enter Name" ng-model="user.name">
In this way, the input box will be shown only if the expression of ng-show evaluates to true. Alternatively, ng-if can be used similar to ng-show, but it works a bit different.

just populate a variable as true when you click register and set that variable as false when you click login.
<h2>Welcome to Mail Service</h2>
<form action="/action_page.php">
<div class="imgcontainer">
<img src="images/img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label><br>
<input type="text" placeholder="Enter Username" name="uname" required ng-model="user.username"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="Enter Password" name="psw" required ng-model="user.password"><br>
<!-- NAME INPUT FIELD -->
<div class="textField-hidden" ng-show="register">
<label><b>Name</b></label><br>
<input type="text" placeholder="Enter Name" ng-model="user.name">
</div><br>
<button type="submit" ng-click="login()">Login</button><br>
<button type="submit" ng-click="register()">Register</button>
now populate $scope.register as true when you click register
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.register=false;
$scope.login = function()
{
var loginRequest = $resource('/api/login');
$scope.register=false;
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
var registerRequest = $resource('/api/register');
$scope.register=true;
loginRequest.save($scope.user, function(response)
{
});
};
}]);

You can use a variable for input fields type and hide it
HTML:
<input type="{{type}}" placeholder="Enter Name" ng-model="user.name">
JS:
app.controller('LoginCtrl', ['$scope', '$resource', '$location',
function($scope, $resource, $location)
{
$scope.login = function()
{
$scope.type="hidden";
var loginRequest = $resource('/api/login');
loginRequest.save($scope.user, function(response)
{
});
};
$scope.register = function()
{
$scope.type="text";
var registerRequest = $resource('/api/register');
loginRequest.save($scope.user, function(response)
{
});
};
}]);
An alternative will be to use ng-if or ng-hide/ng-show defined on a $scope variable and trigger a boolean value for this variable according to your needs.

Related

Why is my axios get request is not working (login)

I´m currently working on a login-page for a school-prohect. I´m using vue.js and tried to use axios to run my get-request. My problem is, that I don´t even get into .then() --> alert(TEST1) is the last thing showed.
I don´t get any error
Does anyone know why I have this problem and how to solve it?
Thanks!
CODE:
<template>
....
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6" id="formsCSS">
<form id="login" method="get">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Username" required maxlength="50">
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" id="password" placeholder="Password" required>
</div>
<button #click="login" type="submit" name="login_button" class="block">Login</button>
</form>
....
</div>
</template>
<script>
//import axios from './node_modules/axios/index.js';
import axios from 'axios';
export default {
methods: {
login() {
var usrn = document.getElementById("username").value;
var passwd = document.getElementById("password").value;
var usesGranted = 50;
alert("TEST0");
this.doGetRequest(usrn, passwd, usesGranted, false);
},
doGetRequest(passwd, usrn, usesGranted, logedIn) {
alert("TEST1");
axios.get('https://moray.xyz/trawaapi/token/obtainToken.php', {
data: {
auth: {
username: usrn,
password: passwd
},
uses: usesGranted
}
})
.then((response) => {
//Informationen die für Requests benötigt werden in der sessionStorage abspeichern
alert("TEST2");
console.log(response);
sessionStorage.setItem("token", response);
sessionStorage.setItem("password", passwd);
sessionStorage.setItem("username", usrn);
sessionStorage.setItem("uses", usesGranted)
})
.catch((error) => {
//Neuen Token anfordern
if (error == 401) {
if (logedIn == true)
alert("....");
}
console.error(error);
});
}
}
};
</script>
You have to prevent form from being sent. Change remove onclick from button and add another event to the form tag:
<form #submit.prevent="yourFunction" id="login">
As we prevent Email sending and just running yourFunction - we do not need to use method attribute.

HTML form validation not appearing

New to all this but essentially I'm trying to use HTML form validation via browser defaults. The form uses a JQuery script to submit the form. I've trawled through similar posts and updated my code but still no luck. If I click the Subscribe button with nothing entered, then there's no prompts presented.
HTML
<form class="form-inline" id="sub-form">
<div class="flex-fill mr-2">
<div class="mc-form-group-FNAME" style="display: inline">
<input type="name" class="form-control required" name="FNAME" id="mce-FNAME" value="" placeholder="First name" required />
</div>
<div class="mc-form-group-EMAIL" style="display: inline">
<input type="email" class="form-control required email" name="EMAIL" id="mce-EMAIL" value="" placeholder="Email address" required />
</div>
<button type="submit" class="btn btn-primary" id="subscribe-btn" onclick="submitForm()">Subscribe</button>
</div>
<div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_8a28f24e93a8a23b993145f05_2d6480ea6a" tabindex="-1" value=""></div>
</form>
JQuery/JS
//Mail Chimp form submission
$('#sub-form').MailChimpForm({
url: 'https://-.us19.list-manage.com/subscribe/post?u=8a28f24e93a8a23b993145f05&id=2d6480ea6a',
fields: '0:FNAME,1:EMAIL',
submitSelector: '#subscribe-btn',
customMessages: {
E001: 'This field can not be empty',
E003: 'Please enter a valid email address',
},
onFail: (message) => {
if ((message.indexOf("already") >= 0) || (message.indexOf("recent")) >=0) {
alert('This email address is already subscribed. Stay tuned for our newsletter!')
}
},
onOk: function() {
$('#subscribe-ok').modal('show');
$('#sub-form').each(function() {
this.reset();
});
}
});
UPDATE
So upon more testing the HTML validation works if I remove all the JQuery. As soon as I add it back in its gone. Any reason why my JS would break HTML validation?
Thanks everyone for the responses. In the end I opted for JQuery entirely and implemented ToolTipster and JQuery Validate. Final code below.
$("#sub-form").validate({
errorPlacement: function(error, element) {
var ele = $(element),
err = $(error),
msg = err.text();
if (msg != null && msg !== "") {
ele.tooltipster('content', msg);
ele.tooltipster('open'); //open only if the error message is not blank. By default jquery-validate will return a label with no actual text in it so we have to check the innerHTML.
console.log("form validation attempted")
}
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass).tooltipster('close');
},
rules: {
field1: {
required: true,
email: false
},
field2: {
required: true,
email: true
}
},
submitHandler: function(form) { // for demo
alert('valid form');
return false;
}
});
//Run validation on form for subscribe attempt
$('#subscribe-btn').click(function () {
if ($("#sub-form").valid()) {
console.log('hello - valid form');
} else {
console.log('uh oh invalid form');
}
});

Unable to clear form fields after Submit in Angular

I am new to angular. I have looked up a lot of answers on clearing form fields after submitting but none seems to work.
Here's my HTML code:
<form name="myForm" ng-submit="formSubmit()" class="form-horizontal">
<div class="form-group">
<input type="text" class="form-control" ng-model="user.FullName" placeholder="Full Name" required=""/>
</div>
<div class="form-group">
<input type="text" class="form-control" ng-model="user.Address" placeholder="Address" required=""/>
</div>
<button type="submit" class="btn btn-primary" style="background-color: purple;">Submit</button>
</form>
Here's my JS code:
var myApp = angular.module('myApp', ['ui.router']);
myApp.controller("RegisterCtrl", function ($window,$scope,$http) {
$scope.user={}
$scope.formSubmit=function(){
$http({
method:'POST',
url:'myurl',
data:$scope.user,
headers:{'Content-Type':'application/json'}
}).then(function(res){
console.log(res);
$scope.myForm.$setPristine();
$scope.myForm.$setPristine(true);
$scope.myForm='';
})
}
});
I have tried setPristine as well as setUntouched but none working.
I don't see something strange in your code, i make plnkr based on your code, the modifications i do are below. also put the plnkr sample
CONTROLLER
var myApp = angular.module('myApp', ['ui.router']);
myApp.controller("RegisterCtrl", function ($window,$scope,$http) {
$scope.user={}
$scope.formSubmit=function(){
$http({
method:'POST',
url:'myurl',
data:$scope.user,
headers:{'Content-Type':'application/json'}
}).then(function(res){
$scope.myForm.$setPristine();
$scope.user = {};
}, function(rej){ //error});
}
});
you should try
var myApp = angular.module('myApp', ['ui.router']);
myApp.controller("RegisterCtrl", function ($window,$scope,$http) {
$scope.user={}
$scope.formSubmit=function(){
$http({
method:'POST',
url:'myurl',
data:$scope.user,
headers:{'Content-Type':'application/json'}
}).then(function(res){
$scope.$broadcast('show-errors-reset');
$scope.forms.user = {};
$scope.forms.userFrom.$setPristine = true;
}, function(rej){ //error});
}
});

How can i move value from angular form to server nodejs

- This is the html:
<body ng-controller="stripeController">
<form action="/stripe" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="from-row">
<lebel>
<span>Price:{{getTotal}}$</span>
<input type="hidden" data-stripe="number">
</lebel>
</div>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="number" size="20" data-stripe="number">
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YY)</span>
<input type="text" size="2" data-stripe="exp_month">
</label>
<span> / </span>
<input type="text" size="2" data-stripe="exp_year">
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc">
</label>
</div>
<input type="submit" class="submit" value="Submit Payment">
</form>
</body>
This is the controller code:
app.controller('stripeController', function($scope, $http) {
$http.get('/api/me').success(function (response) {
$scope.userInfo = response;
$scope.isCartEmpty = true;
$scope.userCart = [];
if($scope.userInfo.cart.length>0){
$scope.isCartEmpty= false;
}
console.log($scope.isCartEmpty);
for(var i=0;i<$scope.userInfo.cart.length;i++){
$scope.userCart[i] = $scope.userInfo.cart[i].productId
}
var y = 0;
$scope.getTotal =0;
for(i=0;i<$scope.userCart.length;i++) {
$http.get('/api/product/' + $scope.userCart[i]).success(function
(response) {
$scope.userInfo.cart[y].name = response.name;
$scope.userInfo.cart[y].price = response.price;
$scope.getTotal+= response.price;
y++;
});
}
});
});
This is the node.js post function :
router.post('/stripe', function(req, res){
//Need to check if the cart empty than re-direct to catalog.
var stripe = require("stripe")(
"sk_test_mypass"
);
stripe.charges.create({
amount: ????? * 100,
currency: "usd",
source: req.body.stripeToken, // obtained with Stripe.js
description: "Test Charge"
}, function(err, charge) {
if(err){
console.log("Error");
}
console.log("Successfully bought product!");
});
});
-I have 1 questions:
In the node.js function where I put "?????" how can I get data from the
html form. When I type req.body.getTotal I don't get the data...
You'll want to send it in a hidden field, but it would be better to calculate the total from the product IDs and quantities in the Cart on the server side so there's no opportunity for the amount to be changed client side.

Trying to send the values from HTML to controller

I am trying to send the values from html to controller but is not goes to controller. What is the problem with this code value is show undefined at controller and factory. I hope this code is easy understood:
var mymodal = angular.module('mymodal', []);
mymodal.controller('MainCtrl', function($scope, loginfactory) {
$scope.showModal = false;
$scope.toggleModal = function() {
$scope.showModal = !$scope.showModal;
};
$scope.doLogin = function() {
var promise = loginfactory.logincheck($scope.userid, $scope.pwd);
}
});
mymodal.factory("loginfactory", function($http, $q) {
return {
"logincheck": function(userid, pwd) {
console.log(userid);
console.log(pwd);
return Object;
}
};
});
mymodal.directive('modal', function() {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="">×</button>' +
'<h4 class="modal-title">{{ title }}</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude=""></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace: true,
scope: true,
link: function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value) {
if (value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = false;
});
});
}
};
});
My view:
<div ng-controller="MainCtrl" class="container">
<h1>Modal example</h1>
<button ng-click="toggleModal()" class="btn btn-default">Open modal</button>
<modal title="Login form" visible="showModal">
<form role="form">
<div class="form-group">
<label for="email">Email address</label>
<input type="text" class="form-control" ng-model="userid" placeholder="Enter email" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" ng-model="pwd" placeholder="Password" />
</div>
<button type="submit" ng-click="doLogin()" class="btn btn-default">Submit</button>
</form>
</modal>
</div>
Here is what I mean see Plunker;
In your directive you used: scope: true, this mean what is change in the directive will not reflect on the parent scope Look at this so to get it works you have to do like this. in the submit btton: (angular best practice passing scope from view)
<button ng-click="doLogin(userid,pwd)" class="btn btn-default">submit</button>
in your controler:
$scope.doLogin = function(userid,pwd) {
var promise = loginfactory.logincheck(userid, pwd);
}
you see I don't pass $scope.userid and $scope.pwd in your loginfactory but pass the value from view because of scope: true, make your code won't work.
one last suggest, you can use UI bootstrap for angular so you don't have to mix with jquery bootstrap. UI Bootstrap