Dynamic Loading Templates in Meteor - javascript

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.

Related

Javascript redirect to html

I've been trying to let javascript redirect to another html file using window.location but it keeps reloading. Here is the Javascript
var myStorage = window.localStorage;
let accounts = [{
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
}];
myStorage.setItem("account", accounts);
//check login account
var checkLogin = function() {
let uname = document.getElementById("Uname").value;
let pass = document.getElementById("Pass").value;
if (uname == "admin" && pass == "admin123!") {
myStorage.setItem("user", {
username: 'admin',
pass: 'admin123!',
email: 'admin#gmail.com'
});
alert("Login admin");
window.location = "../account/myaccount.html";
alert("redirect");
} else {
myStorage.setItem("user", undefined);
document.getElementById("incorrectAccount").style.color = "red";
document.getElementById("incorrectAccount").innerHTML = "Incorrect Username or Password";
}
};
<form id="login" method="post" onsubmit="return checkLogin();">
<div>
<label><b>Username:
</b>
</label>
<input type="text" name="Uname" id="Uname" placeholder="admin"><br><br>
</div>
<div>
<label><b>Password: </b></label>
<input type="Password" name="Pass" id="Pass" placeholder="admin123!"><br><br>
</div>
<div>
<input type="submit" name="log" id="log" value="Log In"></a>
<span id="incorrectAccount"></span>
<br><br>
</div>
<div>
<input type="checkbox" id="check">
<span>Remember me</span>
</div>
<div>
Forgot Password?
<br><br>
Register
</div>
</form>
After typing the same username and the password, the first alert works and then it skips the redirect link and goes straight for the 2nd alert message
Submitting a form will cause the page to load the URL specified in the action attribute, which defaults to the current URL, which gives that effect though.
You must be trigging the JS when you submit the form. The JS runs, then the form submits, and the URL being navigated to changes.
You need to prevent the default behaviour of the form submission event.
e.g.
var checkLogin = function(event){
event.preventDefault();
and
document.querySelector('form').addEventListener('submit', checkLogin);
Re edit.
This is the problem. However, you are using event binding methods from before they introduced addEventListener (which became a standard in November 2000).
If you want to use intrinsic event attributes (I don't recommend them, they have some confusing gotchas) then you need to return false from the event handler.
onsubmit="return checkLogin();"
You are currently returning the return value of checkLogin, but that doesn't have a return statement so it returns undefined. You need to return false and not any falsy value.
function myRedirect() {
location.replace("https://stackoverflow.com")
}
<button onclick="myRedirect()">Replace document</button>

angular put code from a form into a [POST]

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

Clear a field when the user starts filling a form

I have a view with a form in it:
<form asp-controller="UrlP" asp-action="RegisterInput" method="post">
Url: <input asp-for="Url" />
<br />
<button type="submit">Go!</button>
and, on the same view, I have a result from the previous submission:
#if (!string.IsNullOrEmpty(Model.Result))
{
<div class="result">The result is: #Model.Result</div>
}
How can I make the div above (class 'result') disappear as soon a the user starts typing in the form?
To give some context, the app is a single page where you provide a url and you get a result below and I would like to clear the result as soon as a new url is entered.
Since you are using ASP.net Core, it can be handled from the Action and Model State
So after the post, just clear your ModelState and return view like :
ModelState.Clear();
return View(<some View>);
Here's one way.
window.onload = function () {
// attach onkeypress event handler to all text inputs
document.querySelectorAll('form [type=text]').forEach(function (input) {
input.onkeypress = hideResult;
});
};
function hideResult () {
var result = document.querySelector('.result');
// remove result if it exist
if (result) {
result.parentNode.removeChild(result);
}
}
<div class="result">The result is: #Model.Result</div>
<form>
<input type="text" value=""><br>
<input type="text" value="">
</form>

How to store a flag in a cookie where the flag is true only if a form has been completed?

How to store a flag in a cookie where the flag is true only if a form has been completed?
I have a sidebar contains a form, which when successfully submitted fades the form and display a message using one of the user inputs.
This sidebar form is present over a number of pages on the website. In order to identify if the form has already been completed on another page I believe I can use a flag variable to define whether this is true or false and then display the form or the message depending on the stored value.
I have never used cookies as a medium to store a value and do not know the correct syntax for them. Can I simply make the cookie when the formsubmit is successful. And on every page have a script in the header that will then be read to either display the form or not.
Is this the best way to go about this? And what is the format and correct syntax to identify something like this?
HTML
<div id="sidebarf">
<form id="sidebarform" onsubmit="return false" method="post" name="myForm" autocomplete="off" >
<input type="text" name="name" id="username" placeholder="Name (eg. Rob James)" value="" required><br><br>
<input type="text" name="location" id="userlocation" placeholder="Location (eg. Wacol)" value="" required><br><br>
<input type="text" name="postcode" id="userpc" pattern="[0-9]{4}" placeholder="Postcode (eg. 4076)" maxlength="4" value="" required> <br><br>
<input type="email" name="email" id="useremail" placeholder="Email Address (eg. someone#yourdomain.com" value="" required> <br><br>
<input type="tel" name="phone" id="userphone" placeholder="Phone Number (eg. 0412345678)" maxlength="10" minlength="6" value="" required> <br><br>
<textarea rows="4" cols="20" id="usercomment" placeholder="Comment/Question" value="" required></textarea><br><br>
<input type="submit" id="sidebarformsubmit" value="Submit">
</form>
</div>
JAVASCRIPT
$("#sidebarform").on("submit", function() {
if ($("#username").val() == "") {
return false;
}
$("#sidebarform").fadeOut("slow", function(){
$("#sidebarf").html("Thankyou for your inquiry " + $("#username").val() + ". We will call or email you with further details within 3 business days." );
});
return false;
/////////////////Is this the flag?/Correct Location?//////////////
//////var completed = true
//////document.cookie=completed;
///////////
});
</script>
And then would I call something like this when the page loads?
///////////////////DOES NOT WORK/////////////////
<script>
function checkCookie()
{
var display=getCookie("completed");
if (complete!="true")
{
$("#sidebarf").html("Thankyou for your inquiry " + $("#username").val() + ". We will call or email you with further details within 3 business days." );
}
else
{
$("#sidebarf").html //(Don't know what to put here!)
}
}
I also have this for a custom validity after the above code. But this shouldn't play a role.
$(document).ready(function () {
$('#username').on({
invalid: function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter a name.");
}
},
input: function(e) {
e.target.setCustomValidity("");
}
});
As I said, I honestly have no idea about the cookie use so the code is just what I've search on the web.
If you use this jQuery cookie plugin you can simplify your code a great deal. The following code should check for the cookie when the page loads. If the cookie is found, the form is immediately hidden without animation. Otherwise when the form is submitted, the cookie is set so that at the next page load the form will be hidden.
$(function() {
var completed = $.cookie( 'completed' ),
form = $('#sidebarform'),
msg = $('#sidebarf');
if( ( completed != undefined ) && ( completed == 'done' ) ) {
form.hide();
msg.html( 'Form already completed.' );
}
form.on("submit", function( e ) {
e.preventDefault();
if ( $("#username").val() == "" ) {
return false;
}
$(this).fadeOut("slow", function() {
msg.html("Thank you for your inquiry " + $("#username").val() + ". We will call or email you with further details within 3 business days." );
form.submit();
//or submit form via ajax ---> YOUR CHOICE
$.cookie( 'completed', 'done' );
});
});
});
JS FIDDLE DEMO

HTML5 form required attribute. Set custom validation message?

I've got the following HTML form: http://jsfiddle.net/nfgfP/
<form id="form" onsubmit="return(login())">
<input name="username" placeholder="Username" required />
<input name="pass" type="password" placeholder="Password" required/>
<br/>Remember me: <input type="checkbox" name="remember" value="true" /><br/>
<input type="submit" name="submit" value="Log In"/>
Currently when I hit enter when they're both blank, a popup box appears saying "Please fill out this field". How would I change that default message to "This field cannot be left blank"?
The type password field's error message is simply *****. To recreate this give the username a value and hit submit.
Here is some code to display a custom error message:
<input type="text" id="username" required placeholder="Enter Name"
oninvalid="ths.setCustomValidity('Enter User Name Here')"
oninput="setCustomValidity('')"/>
This part is important because it hides the error message when the user inputs new data:
oninput="setCustomValidity('')"
Note: the this keyword is not required for inline event handlers, but you may want to use it anyway for consistency.
Use setCustomValidity:
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field cannot be left blank");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
I changed to vanilla JavaScript from Mootools as suggested by #itpastorn in the comments, but you should be able to work out the Mootools equivalent if necessary.
If setCustomValidity is set to anything other than the empty string it will cause the field to be considered invalid; therefore you must clear it before testing validity, you can't just set it and forget.
As pointed out in #thomasvdb's comment below, you need to clear the custom validity in some event outside of invalid otherwise there may be an extra pass through the oninvalid handler to clear it.
It's very simple to control custom messages with the help of HTML5 event oninvalid
Here is code:
<input id="UserID" type="text" required="required"
oninvalid="this.setCustomValidity('Witinnovation')"
onvalid="this.setCustomValidity('')">
This is most important:
onvalid="this.setCustomValidity('')"
Note: This no longer works in Chrome, not tested in other browsers. See edits below. This answer is being left here for historical reference.
If you feel that the validation string really should not be set by code, you can set you input element's title attribute to read "This field cannot be left blank". (Works in Chrome 10)
title="This field should not be left blank."
See http://jsfiddle.net/kaleb/nfgfP/8/
And in Firefox, you can add this attribute:
x-moz-errormessage="This field should not be left blank."
Edit
This seems to have changed since I originally wrote this answer. Now adding a title does not change the validity message, it just adds an addendum to the message. The fiddle above still applies.
Edit 2
Chrome now does nothing with the title attribute as of Chrome 51. I am not sure in which version this changed.
It's very simple to control custom messages with the help of the HTML5 oninvalid event
Here is the code:
User ID
<input id="UserID" type="text" required
oninvalid="this.setCustomValidity('User ID is a must')">
By setting and unsetting the setCustomValidity in the right time, the validation message will work flawlessly.
<input name="Username" required
oninvalid="this.setCustomValidity('Username cannot be empty.')"
onchange="this.setCustomValidity('')" type="text" />
I used onchange instead of oninput which is more general and occurs when the value is changed in any condition even through JavaScript.
I have made a small library to ease changing and translating the error messages. You can even change the texts by error type which is currently not available using title in Chrome or x-moz-errormessage in Firefox. Go check it out on GitHub, and give feedback.
It's used like:
<input type="email" required data-errormessage-value-missing="Please input something">
There's a demo available at jsFiddle.
Try this one, its better and tested:
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity('Required email address');
} else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('please enter a valid email address');
} else {
textbox.setCustomValidity('');
}
return true;
}
<form id="myform">
<input id="email"
oninvalid="InvalidMsg(this);"
oninput="InvalidMsg(this);"
name="email"
type="email"
required="required" />
<input type="submit" />
</form>
Demo:
http://jsfiddle.net/patelriki13/Sqq8e/
The easiest and cleanest way I've found is to use a data attribute to store your custom error. Test the node for validity and handle the error by using some custom html.
le javascript
if(node.validity.patternMismatch)
{
message = node.dataset.patternError;
}
and some super HTML5
<input type="text" id="city" name="city" data-pattern-error="Please use only letters for your city." pattern="[A-z ']*" required>
The solution for preventing Google Chrome error messages on input each symbol:
<p>Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.</p>
<form method="post" action="#">
<label for="text_number_1">Here you will see browser's error validation message on input:</label><br>
<input id="test_number_1" type="number" min="0" required="true"
oninput="this.setCustomValidity('')"
oninvalid="this.setCustomValidity('This is my custom message.')"/>
<input type="submit"/>
</form>
<form method="post" action="#">
<p></p>
<label for="text_number_1">Here you will see no error messages on input:</label><br>
<input id="test_number_2" type="number" min="0" required="true"
oninput="(function(e){e.setCustomValidity(''); return !e.validity.valid && e.setCustomValidity(' ')})(this)"
oninvalid="this.setCustomValidity('This is my custom message.')"/>
<input type="submit"/>
</form>
I have a simpler vanilla js only solution:
For checkboxes:
document.getElementById("id").oninvalid = function () {
this.setCustomValidity(this.checked ? '' : 'My message');
};
For inputs:
document.getElementById("id").oninvalid = function () {
this.setCustomValidity(this.value ? '' : 'My message');
};
Okay, oninvalid works well but it shows error even if user entered valid data. So I have used below to tackle it, hope it will work for you as well,
oninvalid="this.setCustomValidity('Your custom message.')" onkeyup="setCustomValidity('')"
If your error message is a single one, then try below.
<input oninvalid="this.setCustomValidity('my error message')"
oninput="this.setCustomValidity('')"> <!-- 👈 don't forget it. -->
To handle multiple errors, try below
<input oninput="this.setCustomValidity('')">
<script>
inputElem.addEventListener("invalid", ()=>{
if (inputElem.validity.patternMismatch) {
return inputElem.setCustomValidity('my error message')
}
return inputElem.setCustomValidity('') // default message
})
</script>
Example
You can test valueMissing and valueMissing.
<form>
<input pattern="[^\\/:\x22*?<>|]+"
placeholder="input file name"
oninput="this.setCustomValidity('')"
required
>
<input type="submit">
</form>
<script>
const form = document.querySelector("form")
const inputElem = document.querySelector(`input`)
inputElem.addEventListener("invalid", ()=>{
if (inputElem.validity.patternMismatch) {
return inputElem.setCustomValidity('Illegal Filename Characters \\/:\x22?<>|')
}
return inputElem.setCustomValidity('') // return default message according inputElem.validity.{badInput, customError, tooLong, valueMissing ...}
})
form.onsubmit = () => {
return false
}
</script>
ValidityState
const username= document.querySelector('#username');
const submit=document.querySelector('#submit');
submit.addEventListener('click',()=>{
if(username.validity.typeMismatch){
username.setCustomValidity('Please enter User Name');
}else{
username.setCustomValidity('');
}
if(pass.validity.typeMismatch){
pass.setCustomValidity('Please enter Password');
}else{
pass.setCustomValidity('');
}
})
Adapting Salar's answer to JSX and React, I noticed that React Select doesn't behave just like an <input/> field regarding validation. Apparently, several workarounds are needed to show only the custom message and to keep it from showing at inconvenient times.
I've raised an issue here, if it helps anything. Here is a CodeSandbox with a working example, and the most important code there is reproduced here:
Hello.js
import React, { Component } from "react";
import SelectValid from "./SelectValid";
export default class Hello extends Component {
render() {
return (
<form>
<SelectValid placeholder="this one is optional" />
<SelectValid placeholder="this one is required" required />
<input
required
defaultValue="foo"
onChange={e => e.target.setCustomValidity("")}
onInvalid={e => e.target.setCustomValidity("foo")}
/>
<button>button</button>
</form>
);
}
}
SelectValid.js
import React, { Component } from "react";
import Select from "react-select";
import "react-select/dist/react-select.css";
export default class SelectValid extends Component {
render() {
this.required = !this.props.required
? false
: this.state && this.state.value ? false : true;
let inputProps = undefined;
let onInputChange = undefined;
if (this.props.required) {
inputProps = {
onInvalid: e => e.target.setCustomValidity(this.required ? "foo" : "")
};
onInputChange = value => {
this.selectComponent.input.input.setCustomValidity(
value
? ""
: this.required
? "foo"
: this.selectComponent.props.value ? "" : "foo"
);
return value;
};
}
return (
<Select
onChange={value => {
this.required = !this.props.required ? false : value ? false : true;
let state = this && this.state ? this.state : { value: null };
state.value = value;
this.setState(state);
if (this.props.onChange) {
this.props.onChange();
}
}}
value={this && this.state ? this.state.value : null}
options={[{ label: "yes", value: 1 }, { label: "no", value: 0 }]}
placeholder={this.props.placeholder}
required={this.required}
clearable
searchable
inputProps={inputProps}
ref={input => (this.selectComponent = input)}
onInputChange={onInputChange}
/>
);
}
}
For a totaly custom check logic:
$(document).ready(function() {
$('#form').on('submit', function(e) {
if ($('#customCheck').val() != 'apple') {
$('#customCheck')[0].setCustomValidity('Custom error here! "apple" is the magic word');
$('#customCheck')[0].reportValidity();
e.preventDefault();
}
});
$('#customCheck').on('input', function() {
$('#customCheck')[0].setCustomValidity('');
});
});
input {
display: block;
margin-top: 15px;
}
input[type="text"] {
min-width: 250px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="text" placeholder="dafault check with 'required' TAG" required/>
<input type="text" placeholder="custom check for word 'apple'" id="customCheck" />
<input type="submit">
</form>
Can be easily handled by just putting 'title' with the field:
<input type="text" id="username" required title="This field can not be empty" />

Categories