I have an HTML form, which should be completed by the user. After completing the form, the introduced data is checked, in order to see whether the introduced username was introduced before or not. If the username is unique, then the input data is valid. If the username has already been used by someone else, I want to reload the sign up page, which is called signUp.html, but I also want to modify the values and placeholders of those fields contained by that HTML form. Excepting the Username and Password fields, I want every other field to contain the data, which was introduced by the user before. For sample, if the First Name field contained the value Toma, then I want, after reloading the page, the First Name field to have the value of Toma. On the other hand, I want to change the message of the placeholder of the Username field, which would be something like: Sorry, this username is invalid.... I tried to use the jsdom package, in order to acces the HTML file: signUp.html, which is to be found in public/views. The code of the HTML form is:
<form method="POST" action="signUp" style="margin-left: 5%; margin-right: 5%; margin-top: 5%" class="was-validated">
<div class="form-group">
<label style="color: #ffffff"> First Name </label>
<input type="text" name="firstName" class="form-control" placeholder="e.g.: Toma" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Second Name </label>
<input type="text" name="secondName" class="form-control" placeholder="e.g.: Alex" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Email </label>
<input type="email" name="email" class="form-control" placeholder="e.g.: somename#somedomain.com" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Username </label>
<input type="text" name="username" class="form-control" placeholder="e.g.: miauMiau23 (this is the name your friends will identify you with)" required>
</div>
<div class="form-group">
<label style="color: #ffffff"> Password </label>
<input type="password" name="password" class="form-control" placeholder="please, use a solid password, having a minimum of 6 characters, small and capital letters, as well as numbers and symbols!" required>
</div>
<button type="submit" class="btn btn-primary" style="width: 100%"> Submit </button>
</form>
The code found in server.js, which tried to achieve what I've described before:
app.post('/signUp', urlencodedParser, function(req, res){
console.log("sorry... this username is invalid!");
res.render('signUp');
var { document } = (new JSDOM('public/views/signUp.html')).window;
var firstNameField = document.getElementsByName('firstName');
var secondNameField = document.getElementsByName('secondName');
var emailField = document.getElementsByName('email');
var usernameField = document.getElementsByName('username');
var passwordField = document.getElementsByName('password');
console.log(firstNameField.placeholder);
firstNameField.value = req.body.firstName;
secondNameField.value = req.body.secondName;
emailField.value = req.body.email;
usernameField.value = "";
usernameField.placeholder = "'" + req.body.username + "' is an invalid username...";
passwordField.value = "";
}
After reloading, the page loses all of the introduced data.
The reason is not working is because res.render will render the page on the server and then send it to the client. What you're doing after that is simply loading the HTML again into the server's memory with JSDOM and modifying it, at the end of the request that is just thrown away and doesn't effect what has already been sent to the client by res.render.
The correct way to do this would be to use a templating language (there are many to choose from) with your express.js server to dynamically render the page and inject the values you want in the right place. You can then simply pass the variables to the res.render to be available when rendering your template:
app.post('/signUp', urlencodedParser, function(req, res) {
console.log("sorry... this username is invalid!");
res.render('signUp', {
firstName: req.body.firstName,
secondName: req.body.secondName,
email: req.body.email,
error: "'" + req.body.username + "' is an invalid username...",
});
});
For example, if you went with Pug.js as a templating engine your sign-up page could look something like this (I've not included all formatting which should go into CSS):
form(method='POST' action='/signUp')
div.form-group
label(for='firstName') First Name
input#firstName.form-control(type='text', name='firstName', value=firstName, required)
div.form-group
label(for='secondName') Second Name
input#secondName.form-control(type='text', name='secondName', value=secondName, required)
div.form-group
label(for='email') Email:
input#email.form-control(type='email', name='email', value=email, required)
div.form-group
label(for='username') Username
if error:
input#username.form-control(type='text', name='username', placeholder=error)
else:
input#username.form-control(type='text', name='username', placeholder='e.g.: miauMiau23 (this is the name your friends will identify you with')
div.form-group
label(for='password') Password:
input#passwordw.form-control(type='password' name='password')
button.btn.btn-primary(type='submit') Submit
Related
I am trying to handle some JavaScript work, which I don't have much experience with. I have a 2 part form where a user enters their personal info, and then company info. I am trying to set some of the company fields to what they already entered in their personal info.
I don't want the user to have to retype address, email, etc.
for example, I have...
<div class="form-group">
<label for="email">Email<span>*</span></label>
<input name="email" type="text" class="form-control required" id="email"placeholder="Email" value=".
{{email}}">
<span id="span_email" class="error-msg"></span>
And...
<div class="form-group">
<label for="comp_email">Company Email<span>*</span></label>
<input name="comp_email" type="text" class="form-control required" id="comp_email"placeholder="Email"
value="{{comp_email}}">
<span id="span_email" class="error-msg"></span>
How would I be able to set that second comp_email field to initially have the email info, so the user doesn't have to retype, unless they actually wanted to change the comp_email to another email address?
EDIT
It is all in one form, just separated by divs. Initially, when the page is loaded, the account section div is displayed, when the user hits next, it triggers the display of the business info.
<input type="button" onclick="nextFormPage(); window.scrollTo(0, 100)"
class="btn btn-danger btn-block" value="Next">
The nextFormPage() function just hides the first div and displays the second div.
You have tagged both javascript and jQuery so I'm not sure which you are using. But you can do this with a single line either way:
Javascript::
document.getElementById("comp_email").value = document.getElementById("email").value;
document.getElementById("email").value gets the value from the email input and we set the value of the document.getElementById("comp_email") by setting its value attribute:
jQuery:
$("#comp_email").val( $("#email").val() );
$("#email").val() get the value from the email input and $("#comp_email").val( ... ); sets the text passed in as the input value.
Javascript Working Example
function nextFormPage(){
document.getElementById("comp_email").value = document.getElementById("email").value;
}
<div class="form-group">
<label for="email">Email<span>*</span></label>
<input name="email" type="text" class="form-control required" id="email" placeholder="Email" value="">
<span id="span_email" class="error-msg"></span>
<div class="form-group">
<label for="comp_email">Company Email<span>*</span></label>
<input name="comp_email" type="text" class="form-control required" id="comp_email" placeholder="Email"
value="">
<span id="span_email" class="error-msg"></span>
<input type="button" onclick="nextFormPage(); window.scrollTo(0, 100)"
class="btn btn-danger btn-block" value="Next">
If your user is logged in, you should pass all of their information to the form, including their email. For example:
const logIn = () => {
... some code to get the user ...
... pass the user to the form, probably through an event listener...
let button = document.createElement("button")
button.textContent = "Edit"
button.addEventListener('click', () => {editYourStuff(user)}
}
const editYourStuff = user => {
... grab whatever your form is called ...
editForm.email.value = user.email
}
This should pre populate your form with the email
I have an application with add friend feature, in that feature, user must fill their friend's username in the textbox. this is the html code:
<div content-for="title">
<span>Add Friend</span>
</div>
<form class="form-inline" role="form">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">User ID</label>
<input type="text" class="form-control" data-ng-model="add.email" id="exampleInputEmail2" placeholder="User ID">
</div>
<button type="submit" class="btn btn-default" data-ng-click="addfriends()">Add</button>
the interface will be like this
and this is the js code:
// addfriend
$scope.add = {};
$scope.addfriends = function(){
$scope.messages = {
email : $scope.add.email,
userid : $scope.datauser['data']['_id']
};
//event add friend
socket.emit('addfriend',$scope.messages,function(callback){
if(!callback['error']){
$scope.datauser['data']['penddingrequest'].push(callback['data']);
//push pendding request to localstorage user
localStorageService.remove('user');
localStorageService.add('user', $scope.datauser);
$scope.add['email'] = '';
alert('Successfully added friend');
}else{
var msg = callback['error'];
navigator.notification.alert(msg,'','Error Report','Ok');
}
});
};
I want to change this feature little bit, I want to make this textbox showing some suggestion based on the input, like if user input 'a', the textbox will show all user id that start with 'a'. something like twitter's searchbox or instagram searchbox. these user ids is from database.
example searchbox of web instagram
my question is how to change this textbox to be autocomplete but still work like before? thanks very much
There are many ways to do this.
First is this one: You basically create Angular directive for your input.
http://jsfiddle.net/sebmade/swfjT/
Another way to do is to attach onKeyUp event to your input:
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">User ID</label>
<input type="text" class="form-control" data-ng-model="add.email" id="exampleInputEmail2" placeholder="User ID" ng-keyup="searchFriends()">
<div ng-model="searchFriendsResult" />
</div>
And then, in your controller, you create a searchFriends function that will:
Search your database
Display the result in the view.
Something like this (not a complete code):
$scope.searchFriends = function(value){
// Make Ajax call
var userRes = $resource('/user/:username', {username: '#username'});
userRes.get({username:value})
.$promise.then(function(users) {
$scope.searchFriendsResult = users;
});
};
Use Bootstrap Typeahead
<input type="text" ng-model="asyncSelected"
placeholder="Locations loaded via $http"
uib-typeahead="address for address in getLocation($viewValue)"
typeahead-loading="loadingLocations"
typeahead-no-results="noResults"
class="form-control"/>
I have a problem to perform a rest post request for saving data in a database .
I created a form register.html and a RegisterCtrl.js controller to add the user account in the database .
The url to create a user is register : http://localhost:8100/#/register
I use the framework Ionic and AngularJS
Unfortunately, no post application works .
Can you help me.
Thank you.
Template register.html
<ion-modal-view ng-controller="RegisterCtrl">
<ion-content>
<form ng-controller="RegisterCtrl">
<div class="register listRegister">
<label class="register item item-input">
<span class="spanLogin icon-left ion-person"></span>
<input type="text" class="form-control" ng-model="user.username" placeholder="Username" />
</label>
<label class="register item item-input">
<span class="spanLogin icon-left ion-email"></span>
<input type="email" class="form-control" ng-model="user.email" placeholder="Email" />
</label>
<label class="register item item-input">
<span class="spanLogin icon-left ion-key"></span>
<input type="password" class="form-control" ng-model="user.password" placeholder="Password" />
</label>
</div>
<div class="registerButton">
<button class="validLogin button button-block button-assertive" type="submit">Registration
</button>
Back
</div>
</div>
</form>
</ion-content>
</ion-modal-view>
Controller registerCtrl.js
'use strict'
angular.module('djoro.controllers',['restangular']);
.controller('RegisterCtrl', function($scope, restangular) {
var userRegister = {
"username": user.username,
"email": user.email,
"password": user.password
};
Restangular.all('register').post(userRegister).then(
function (data) {
$scope.register = data;
});
});
Api rest by python Django
class UserRegistration(viewsets.ViewSet):
"""
Called with the URL r'^register/*$'. It allows POST requests.\n
POST requests allow to create a new user. The parameters to post are 'username','email','password'.\n
It raises an HTTP 400 error if the POST request is invalid and an HTTP 401 error if an user with the username or email specified already exists.
"""
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
email=request.data.get('email')
try :
user=register(username, email, password)
user.backend='django.contrib.auth.backends.ModelBackend'
user.save()
login(request, user)
return HttpResponseRedirect("/me/")
except AttributeError:
return Response({"detail": "User with this email or username already exists"}, status=HTTP_401_UNAUTHORIZED)
var name = document.getElementById('contact-name'),
email = document.getElementById('contact-email'),
phone = document.getElementById('contact-phone'),
message = document.getElementById('contact-message');
function checkForm() {
if (name.value == '') {
alert('test');
}
}
I was simply trying to make sure everything was working before I began learning actual client-side validation.
Here is the HTML
<form role='form' name='contactForm' action='#' method="POST" id='contact-form'>
<div class="form-group">
<label for="contact-name">First and Last Name</label>
<input type="text" class="form-control" id="contact-name" name="contactName" placeholder="Enter your name.." pattern="[A-Za-z]+\s[A-Za-z]+">
</div>
<div class="form-group">
<label for="contact-email">Email address</label>
<input type="email" class="form-control" id="contactEmail" name="contactEmail" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contact-phone">Phone Number</label>
<input type="number" class="form-control" id="contactPhone" name="contactPhone" placeholder="Enter Phone Number" required'>
</div>
<div class="form-group">
<label for='contactMessage'>Your Message</label>
<textarea class="form-control" rows="5" placeholder="Enter a brief message" name='contactMessage' id='contact-message' required></textarea>
</div>
<input type="submit" class="btn btn-default" value='Submit' onclick='checkForm()'>
</fieldset>
</form>
I took the required attribute off, and if I leave the name field empty it goes right to the other one when i click submit. To check whether javascript was working at all, i did an basic onclick function that worked.
Maybe someone can explain to me what is wrong with the checkForm function. Thanks in advance.
P.S The form-group and form-control classes belong to bootstrap
Change your javascript to this:
var contactName = document.getElementById('contact-name'),
email = document.getElementById('contact-email'),
phone = document.getElementById('contact-phone'),
message = document.getElementById('contact-message');
function checkForm() {
if (contactName.value === '') {
alert('test');
}
}
Okay, Hobbes, thank you for editing your question, now I can understand your problem.
Your code faces three two issues.
Your control flow. If you want to validate your field, you have to obtain its value upon validation. You instead populate variable name when the page loads, but the user will enter the text only after that. Hence you need to add var someVariableName = document.getElementById(...); to the beginning of the checkForm() function.
global variables. Please do not use them like that, it is a good design to avoid global variables as much as possible, otherwise you bring upon yourself the danger of introducing side effects (or suffering their impact, which happens in your situation). The global context window already contains a variable name and you cannot override that. See window.name in your console. You can of course use var name = ... inside the function or a block.
Even if you fix the above, you will still submit the form. You can prevent the form submission if you end your checkForm() function with return false;
For clarity I append the partial javascript that should work for you:
function checkForm() {
var name = document.getElementById('contact-name');
if (name.value == '') {
alert('test');
return false;
}
}
EDIT: As Eman Z pointed out, the part 1 of the problem does not really prevent the code from working as there's being retrieved an address of an object (thanks, Eman Z!),
I'm using a Kendo edit box that a user can enter the different parts of a SQL connection string (server name, database, user name and password). I also have a text box that will show the user the entire connection string as they type.
My question is how can I data-bind each of the four text boxes (server, database, user and password) to one text box as the user enters data into each one.
Also, the user requested seperate fields.
Thanks in advance,
Dan Plocica
Doing it using Kendo UI would be:
HTML:
<div id="form">
<label>Server : <input type="text" class="k-textbox" data-bind="value: server"></label><br/>
<label>Database : <input type="text" class="k-textbox" data-bind="value: db"></label><br/>
<label>User : <input type="text" class="k-textbox" data-bind="value: user"></label><br/>
<label>Password : <input type="password" class="k-textbox" data-bind="value: password"></label><br/>
<div id="connections" data-bind="text: connection"></div>
</div>
JavaScript:
$(document).ready(function () {
var model = kendo.observable({
server : "localhost:1521",
db : "database",
user : "scott",
password : "tiger",
connection: function () {
return this.get("user") + "/" +
this.get("password") + "#" +
this.get("server") + ":" +
this.get("db");
}
});
kendo.bind($("#form"), model);
});
In the HTML there are two parts:
The input files where I define each input to what field it is bound in my model.
A div where I found its text to connection function in my model that creates a string from the different values.
This is automatically updated and you can freely edit each input.
You might decorate the input as I did setting it's CSS class to k-textbox, that's optional. The only important thing is the data-bind="value : ...".
The JavaScript, is just create and Observable object with the fields and methods that we want.
Running example here: http://jsfiddle.net/OnaBai/xjNMf/
I will write solution using jQuery JavaScript library, and you should use jQuery because its much easier and easier to read and also to avoid errors in different browsers.
**HTML**
Server: <input type="text" id="server"/><br/>
Database: <input type="text" id="database"/><br/>
Username: <input type="text" id="username"/><br/>
Password: <input type="text" id="password"/><br/>
<br/>
Full CS: <input type="text" id="solution"/><br/>
JS
<script type="text/javascript">
var _template = 'Data Source=%server%;Initial Catalog=%db%;Persist Security Info=True;User ID=%user%;Password=%pass%';
$(document).ready(function(){
$('#server,#database,#username,#password').keyup(function(){ updateSolution();});
});
function updateSolution(){
var _t = _template.replace('%server%', $('#server').val()).replace('%db%', $('#database').val()).replace('%username%', $('#username').val()).replace('%pass%', $('#password').val());
$('#solution').val(_t);
};
</script>