I have
var body = {username:"ali", password:"p"};
this.http.post('http://localhost:27017/user/auth', body).subscribe(data =>
{console.log(data);});
How can I load up the variable body with some data-binding from a form? I'm just making a login - I have two fields, username and password that the user enters, and then that will go into the second .post() parameter.
html code
<input type="text" id="username" required [(ngModel)]="user.username">
<input type="password" id="password" required [(ngModel)]="user.password">
<button (click)="submit()">submit</button>
ts code
user={username:"", password:""};
submit(){
const body = this.user;
this.http.post('http://localhost:27017/user/auth', body).subscribe(data =>
{console.log(data);});
}
EDIT: You need of course to add test for the form for more information https://angular.io/guide/forms
Related
I'm new to javascript and I need to fill in this form and then click the button to login. Hope someone could guide me into the right direction of why it's not working.
On practically any other site I've tested, it works fine (basically just switching out the "Id's") - but not on this particular site.
The site is not available for public so I can't provide the URL for it.
The problem is if I manually fill username and password and then from the web console use the .click event below, the login works fine.
When I use the .value event to fill username and password, I can see both fields gets filled but when .click event happens, it triggers the login and it seems to work but after a few seconds, it just says invalid username and password, like if I typed the wrong username and password.
Since I can't see the password in clear text from the form, I don't know if it's right or not but if I use the console from the web browser, I can see both username and password returns the correct values.
I'm using the following code:
function doStuff(){
document.getElementById('loginUsername').value = "username#email.com";
document.getElementById('password').value = "password123"
document.getElementsByClassName('button ok')[0].click();
}
doStuff();
<form data-v-d9a0abfc="" data-v-48366e1e="" role="form" class="form loginForm">
<h2 data-v-d9a0abfc="" role="region" class="visuallyhidden">Login form</h2>
<label data-v-d9a0abfc="" for="loginUsername" class="loginLabel">Username</label>
<input data-v-d9a0abfc="" spellcheck="false" type="text" id="loginUsername" name="loginUsername" autofocus="autofocus" class="form-control loginField">
<label data-v-d9a0abfc="" for="password" class="loginLabel">Password</label>
<input data-v-d9a0abfc="" type="password" id="password" name="password" autofocus="autofocus" class="form-control loginField">
<div data-v-d9a0abfc="" class="">
<div data-v-304a83cb="" data-v-d9a0abfc="" role="alert" aria-relevant="additions removals" style="display: none;">
</div>
<div data-v-7224d6b7="" data-v-d9a0abfc="" class="ace-button" id="accept-button">
<button data-v-7224d6b7="" aria-describedby="11" tabindex="0" type="button" class="button ok">
Login
</button>
</div>
</div>
</form>
It's possible that the website stores the input value in memory by listening to the input onchange callback. Then when clicking on the submit button, it sends the in memory value instead of the one you set programatically. This is not triggered when you programatically update the input value.
What you could try is to programatically trigger the change Event like this:
function doStuff(){
var usernameInput = document.getElementById('loginUsername');
usernameInput.value = "username#email.com";
usernameInput.dispatchEvent(new Event("change"));
var passwordInput = document.getElementById('password');
passwordInput.value = "password123";
passwordInput.dispatchEvent(new Event("change"));
document.getElementsByClassName('button ok')[0].click();
}
As a comment pointed out already, i suspect a Framework is handling the Frontend. It could also be, that there is just an onChange Event or an onInput Event tracking the Value and already working some validation or something in the background.
I've put together an example why your code would fail.
If there is an EventListener inplace, to track the Inputs and handling the values somewhere else, you could emit the Event yourself after setting the value. This should do the trick, if there is a separate handling inplace.
let username = undefined;
let password = undefined;
document.addEventListener("DOMContentLoaded", function() {
// Code to update a variable in the background.
document.getElementById('textInput').addEventListener('change', updateUsername);
document.getElementById('passInput').addEventListener('change', updatePassword);
document.getElementById('btnSubmit').addEventListener('click', function(e) {
e.preventDefault();
e.stopImmediatePropagation();
const text = document.getElementById('textInput').value;
const pass = document.getElementById('passInput').value;
console.log(text,"|", pass);
console.log(username,"|", password);
});
// Your code, to manipulate the Inputfields.
const textInputEl = document.getElementById('textInput');
textInputEl.value = "Test value ...";
// This line triggers the change event, it could also be the 'input' event, depending which // events gets listened to. With this, if there is an event in the background listened to, to
// track the Value, it should update the variable accordingly.
// textInputEl.dispatchEvent(new Event('change'));
const passInputEl = document.getElementById('passInput');
passInputEl.value = "Test value ...";
// Same line as above
// passInputEl.dispatchEvent(new Event('change'));
});
function updateUsername(event){
username = event.target.value;
}
function updatePassword(event) {
password = event.target.value;
}
<div class="container">
<input type="text" id="textInput" />
<input type="password" id="passInput" />
<button type="submit" id="btnSubmit">Submit</button>
</div>
I am trying to change the default error message "setCustomValidity" throws on email being invalid.
I cannot access the source code. My assumption is that the source somehow invokes setCustomValidity; just because of the look of the error message. This is the source element:
<input type="email" value="" name="customer[email]" id="email" class="large" size="30">
I can only inject any change using external JavaScript/css file.
I could think of two solutions.
Solution 1: I am trying to inject inline HTML element using JS which would result in something like this.
<input type="email" value="" name="customer[email]" class="large" size="30" oninvalid="this.setCustomValidity('Please Enter valid email')" oninput="setCustomValidity('')">
I am new to JS and I am having a hard time figuring how to implement HTML in an external JS file.
Solution 2: Invoke the oninvalid and setCustomValidity DOM methods in error_message.js like so:
function emailValidity(){
var myInput = document.getElementByName("customer[email]");
myInput.oninvalid = function() {
(errorMessage)
};
function errorMessage(){
myInput.setCustomValidity("hey! the email isn't right");
}
}
But this file even after being included somehow fails to override the default message!
Any help is appreciated. Thank you in advance.
Additionally you must call the reportValidity method on the same element or nothing will happen.
HTMLObjectElement.setCustomValidity
function validate(input) {
var validityState_object = input.validity;
console.log(validityState_object)
if (validityState_object.typeMismatch) {
input.setCustomValidity('Thats not an email!');
input.reportValidity();
} else {
input.setCustomValidity('');
input.reportValidity();
}
}
document.querySelector('#email').addEventListener('blur', e =>
validate(e.target)
)
<input type="email" value="" id="email">
Just set the input and invalid event listeners in much the same way.
const input = document.querySelector('input');
input.oninput = () => input.setCustomValidity('');
input.oninvalid = () => input.setCustomValidity('Please Enter valid email');
<form>
<input type="email" value="" name="customer[email]" class="large" size="30">
</form>
Your code wasn't working because it wasn't in a form. A form needs a submit button to check the inputs and display an error message if necessary, so I added that.
Also, you have getElementByName when it should be getElementsByName, with a later on [0] indexing to select the element.
In addition to that, you were trying to set the validity every time the user tried to submit, when it only needed to be set once.
Try this:
var myInput = document.getElementsByName("customer[email]")[0];
myInput.oninvalid = function() {
myInput.setCustomValidity("Hey! the email isn't right")
};
<form>
<input type="email" name="customer[email]" id="email" class="large" size="30">
<input type="submit" onsubmit="emailValidity()">
</form>
This is how I solved it:
customAnswer.js
document.addEventListener("DOMContentLoaded", function(event) {
// Source text: "Fill out this field."
var validateElements1 = document.querySelectorAll('input#username, input#password');
if (validateElements1.length > 0) {
for (var x = 0; x < validateElements1.length; x++) {
validateElements1[x].setAttribute("oninvalid","this.setCustomValidity('Complete este campo.')");
validateElements1[x].setAttribute("oninput","this.setCustomValidity('')");
}
}
});
I currently have this code for a custom DuckDuckGo search bar:
<form action="https://duckduckgo.com/" method="get" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
</form>
It automatically opens the URL https://duckduckgo.com/?q={{SEARCH}} when you enter text in the box and press the enter key.
How could I make this bar go to a domain if one is entered? Optimally, it wouldn't validate the domain, just if it sees a string in the pattern xxxx.* with no spaces, it would open that page in a new tab.
Thank you for any help!
One way to solve it is by capturing the submit event of the form, analyze the input value and when it is a domain, open a new window with the domain and cancel the submit by returning false. In case of not being a valid domain, let the form proceed as usual by returning true.
Your html:
<form action="https://duckduckgo.com/" method="get" onsubmit="return decideWhatToDo()" id="ddg-search">
<div class="div-block-4">
<input autofocus="true" class="text-field-3 hero-search-bar w-input" data-name="q" id="field-3" maxlength="256" name="q" placeholder="Search DuckDuckGo" type="text">
</div>
<input type="submit" />
</form>
Your javascript:
function decideWhatToDo() {
let inputValue = document.getElementById('field-3').value;
if (isDomain(inputValue)) {
// the form won't be sent and a new window will open requesting the domain
if (!startsWithProtocol(inputValue)) {
inputValue = 'http://' + inputValue;
}
window.open(inputValue, '_blank');
return false;
}
// Proceed to send the form as usual
return true;
}
function startsWithProtocol(value) {
return /^((https?|ftp|smtp):\/\/)/.test(value);
}
function isDomain(value) {
return /^((https?|ftp|smtp):\/\/)?(www.)?[a-z0-9]+\.[a-z]+(\/[a-zA-Z0-9#]+\/?)*$/.test(value);
}
So one way to handle it is to use an if condition and check the string against a RegExp that recognizes domain names.
Here's a nifty one you can use:
/[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
I assume you don't need help getting the value from your text field or the actual redirection. However, if you needed more help, comment below and I'll post a more complete answer. The code below should help you get to where you want:
var domainRegExp = /[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+/
var pass = domainRegExp.test('test.com')
var fail = domainRegExp.test('test')
console.log(pass, 'pass')
console.log(fail, 'fail')
So as you can see the value inside the 'pass' variable is true, and 'fail' is false.
I did a sample code using two templates.Those are :
Login Template - Login Form along with New User Button
Registration Template - Registration Form
Initially shows Login Template.So here when ever clicks a New User! Button in Login Template page then Immediately shows to Registration template page and hiding the Login Template page.In Reregistration Template Page Clicks Registration button if successfully registered then shows to Login Template Page and Hiding the Registration Template Page.I am new to Meteor. So Please see the below code & Suggest me how to do?
HTML Code :
<head>
<title>hcare</title>
</head>
<body>
{{> login}}
</body>
<template name="login">
<form id="login-form" action="action">
<div>
<h2> Login<h2>
<input type="text" id="username" placeholder="Enetr User Name" /><br>
<input type="password" id="pwd" placeholder="Password" /><br>
<input type="submit" value="Login" id="login" />
<input type="submit" value=" New User!" id="register" />
</div>
</form>
</template>
<template name="registration">
<form id="register-form" action="action">
<div>
<h2> Create Account<h2>
<input type="text" id="username" placeholder="Enter UserName" /><br>
<input type="text" id="name" placeholder=" Enter Name" /><br>
<input type="text" id="email1" placeholder=" Enter Email" /><br>
<input type="password" id="pwd1" placeholder=" Enter Password" /><br>
<input type="submit" value="Register" id="register" />
</div>
</form>
</template>
JS Code :
if (Meteor.isClient)
{
Template.login.events
({
'submit #login-form' : function (e,t)
{
// template data, if any, is available in 'this'
console.log("You pressed the button LOGIN ");
e.preventDefault();
// retrieve the input field values
var email = t.find('#email').value
, password = t.find('#pwd').value;
console.log(email);
Meteor.loginWithPassword(email, password, function (err)
{
if (err)
{
console.log(err);
Session.set("loginError", true);
}
else
{
console.log(" Login Success ");
}
});
}
});
Template.registration.events
({
'submit #register-form' : function (e,t)
{
console.log("You pressed the button Register ");
e.preventDefault();
var username = t.find('#username').value
, name = t.find('#name').value
, email = t.find('#email1').value
, password = t.find('#pwd1').value;
console.log("password="+password);
//var email = trimInput(email);
// var isValidPassword = function(val)
// {
// console.log("isValidPassword() "+val.length);
// return val.length >= 6 ? true : false;
// }
console.log("email="+email);
var isValidPassword = function(val, field)
{
if (val.length >= 6) {
return true;
} else {
Session.set('displayMessage', 'Error & Too short.')
return false;
}
}
if (isValidPassword(password))
{
console.log(" *** isValidPassword *** ");
Accounts.createUser({email: email, password : password,username : username }, function(err)
{
if (err)
{
console.log(err);
alert(err.reason);
}
else
{
console.log("Register Successfully");
}
});
}
}
});
}
if (Meteor.isServer)
{
Meteor.startup(function ()
{
// code to run on server at startup
});
}
I would start to add the Meteor Iron-Router package:
https://github.com/EventedMind/iron-router
read the docs and my be my tutorial, too (http://manuel-schoebel.com/blog/iron-router-tutorial).
Then you can easily set up two different routes, one for login and one for register with the Iron-Router.
You can then simply create normal links to switch from /login to /register.
The Iron-Router makes it really much easier, so I would highly suggest to take some time and really understand how it works (it is not that hard).
Good choice to learn Meteor, by the way :-)
To answer your question in your comment:
First of all, you should use the Iron-Router on windows, too. But without it you could render a template depending on the Session.
<body>
{{> content}}
</body>
<template name="content">
{{renderTemplate}}
</template>
Content Helper
Template.content.helpers({
'renderTemplate': function(){
return new Handlebars.SafeString(Template[Session.get('currentTemplate')]({dataKey: 'someValue'})
}
})
Now in the content template should be the template rendered that is in your Session.get('currentTemplate').
You can then simply change the Session variable if someone clicks:
Template.login.events({
'click #register': function(evt, tpl){ Session.set('currentTemplate', 'registration');}
})
Because the Session is a reactive data source and it knows, that the renderTemplate helper method depends on this specific data, it will re run the renderTemplate function. And now the registration template will be rendered.
Also make sure that you set the currentTemplate variable in your clients startup function to 'login'. (Session.set('currentTemplate', 'login'))
Otherwise nothing will show up at first and an error would occur.
This is not tested code, but it should give you a direction... And might even work ;-P
Edit:
You also do not want your input #register button to have the type="submit", make it type="button" so that the form will not be submitted! You can also add to your 'click #register' event-handler this:
evt.preventDefault()
Just to make sure the form will not be submitted.
I was trying to add a second form to a javascript/jquery script that I wrote, however, when i implemented and began testing it, when I would try to send the firm form via a jquery post request, it would instead send a get request. I know that this has to do with the second form, because commenting the script out for the second form makes the site work again. Hopefully a pair of fresh eyes can help!(the loadpage function works as well)
The register function seems to be where the problem is:
//when the user first goes to the page
$(document).ready(function(){
var user = $("#username");
var pass = $("#password");
var submit = $("#submit");
//both of these methods work, I'm not sure if one is better than the other
//$("#submitbutton").click(function(event){
$("#loginform").on('submit', function(event){
event.preventDefault();
$('.loginerror').remove();
$.post("login.php", {username:user.val(), password:pass.val()}, function(data){
if(!data)
{
$("#login").append("<h3 class='loginerror'>Incorrect Username or Password</h3>");
}
else
{
loadpage();
}
}, "json");
});
//if the user clicks the username prompt him with the login div
$("#registerbutton").click(function(event){
register();
});
});
function register()
{
$("#login").hide("slow");
$("#registerdiv").css("display", "block");
//initiate some variables
var regusername = $("#regusername");
var reg1password = $("#reg1password");
var reg2password = $("#reg2password");
var regemail = $("#regemail");
var regfirstname = $("#regfirstname");
var reglastname = $("#reglastname");
//TODO: check to make sure form is filled out properly
$("#registerform").on('submit', function(event){
event.preventDefault();
//send post request
$.post("register.php", {regusername:regusername.val(), password1:reg1password.val(), password2:reg2password.val(), email:regemail.val(), firstname:regfirstname.val(), lastname:reglastname.val()}, function(data){
if(!data)
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
else
$("#registerdiv").hide("slow");
$("#loginiv").slidedown("slow");
}, "json");
}
And here's the HTML with the two forms:
<body>
<Div id="welcome"> Welcome </div>
<Div id="login">
<br><br><h2>Welcome to QuotesLib</h2>
<br><br><br><form id="loginform"> Username:
<input type = "text" name = "username" id ="username"> <br> Password:
<input type = "password" name = "password" id = "password"> <br>
<input type = "submit" name="submitbutton" id="submitbutton" class = "bluebutton">
</form>
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
</Div>
<Div id="registerdiv">
<br><br><h2>Sign Up For QuotesLib</h2>
<br><form id="registerform"> Username:
<input type ="text" id="regusername"> <br> Password:
<input type ="password" id="reg1password"> <br> Repeat Password:
<input type ="password" id="reg2password"> <br> First Name:
<input type ="text" id="regfirstname"> <br> Last Name:
<input type ="text" id="reglastname"> <br> email:
<input type ="text" id="regEmail"> <br>
<input type ="submit" id ="registersubmitbutton">
<br> </form>
</Div>
It would be super helpful if someone could give me an answer to this question!
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
should be
$("#registerdiv").append("<h3 class='loginerror'>Server error, retry</h3>");
see the difference:
<h3>... and <h3 ...
The code has some mistakes,
first,
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
You are having a form open tag but not a close tag, the form tag even not needed for this button, and that was the main reason for the problem
second, the end of the JS code,
}, "json");
}
should be
}, "json");
});
}
I'm not sure whether you missed while copying,
Third,
The <h3> tag within the append method, though it is not the matter for the problem you are having.
It is better to use some text editors which hi-lights the code open, end tags, braces.
Here the working code