I am new in javascript and currently I am creating an enrolment form where it will validate the cellphone where it only accepts 11 characters and numbers. the only problem is that everytime I click on submit, instead of the message popping up, it completely refreshes my tab. Is there any way to fix this?
Form Code:
<!doctype html>
<html lang="en">
<head>
<nav class="navbar navbar-expand-lg navbar-light">
<a class="navbar-brand" href="Homepage.html"><img src="USTLogo.png" width="30" height="30" alt="">School</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="Homepage.html">HOME<span class="sr-only">(current)</span></a>
</li>
</ul>
</div>
</nav>
<title>Enrollment Form</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- CSS -->
<link href = "design.css" rel = "stylesheet" type="text/css"/>
<script src="JAVASCRIPT.js" type="text/jsx"></script>
</head>
<body>
<h1 class="display-1">Enrollment Form</h1>
<div class="container">
<div class="row">
<!-- empty space on the left side -->
<div class="col-lg-3"></div>
<!-- Main Content -->
<div class="col-lg-6">
<div id ="ui">
<form id = "form" class="form-group">
<div class="row">
<div class="col-lg-8">
<label >Cellphone Number</label>
<input id = "Cp_Number" type="text" class="form-control" placeholder="Enter Cellphone Number..." required>
</div>
<div class="col-lg-4">
<label >Age</label>
<input id = "Age" type="text" class="form-control" placeholder="Enter your age..." required>
</div>
<br>
<div class="row">
<div class="col-lg-6">
<button type="submit" class="btn btn-primary btn-block">Submit</button>
</div>
<div class="col-lg-6">
Cancel
</div>
</div >
</form>
</div>
</div>
<!-- empty space on the right side -->
<div class="col-lg-3"></div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Note: I will be removing most of the content in the form and will only include the fields where it needs validation
JS code:
const Cp_num = documet.getElementById('Cp_Number')
const age = document.getElementById('Age')
const form = document.getElementById('form')
form.addEventListener('submit', (e) =>{
var isValid = true;
e.preventDefault();
if(isNaN(Cp_num) || Cp_num.value == null || Cp_num.value == ''){
alert ("Your Cellphone number is invalid!")
isValid == false;
}
if (Cp_num >=12){
alert ("Your Cellphone number is invalid!")
isValid == false;
}
if(isNaN(age) || age.value == null || age.value == ''){
alert ("Your Age is invalid!")
isValid == false;
}
if (isValid == true){
popUp();
}
})
Stop using your custom javascript in the head tag. Because, of this the scripts loads before the contents and doesn't find the form element in the DOM before initialization. So, use any custom javascript inside the body tag and below all the html elements. But remember to include any other dependencies before your custom scripts. Hope it solves the problem.
What's happening here is that your script tag is in your head:
<script src="JAVASCRIPT.js" type="text/jsx"></script>
And for that reason, your HTML hasn't been loaded completely, so a "form" element with the id of "form" does not exist, thus, you get an error (check your console in your browser).
This is why your e.preventDefault() method doesn't work. Because again, your HTML hasn't been loaded yet.
You have two options:
Put the script tag at the bottom of your body:
Very self-explanatory, put the script tag at the end of your body, so your whole HTML loads first, and then your JavaScript file.
Use the "defer" attribute in your script tag:
I won't explain what the defer does in depth here, but if you want some quick answer, it basically waits for your HTML to fully load before using any of the JavaScript code.
So you can try this:
<script src="JAVASCRIPT.js" type="text/jsx" defer></script>
(By the way, this method does not require you to move the script tag out of your HTML head)
You can learn more about defer here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer
(EDIT): By further inspection of the code, I found that you were using the "type" parameter in your script tag. You don't need this, and this is causing you the problem of your script tag not being used:
So from:
<script src="JAVASCRIPT.js" type="text/jsx"></script>
do:
<script src="JAVASCRIPT.js" defer></script>
(Another gotcha) You have a typo on the first "document" that you were selecting:
const Cp_num = documet.getElementById('Cp_Number')
"documet" is not defined, you have to change it to:
const Cp_num = document.getElementById('Cp_Number')
Related
I have created a login page that allows you to log in using username and password. However, it is currently so that you are always redirected to the "profile" page and there is then checked by PHP whether the login data are correct, because the data are on the DB.
Therefore I have the idea with a validate function directly on the loginpage to check if the data is correct and then I just create a session.
Does anyone have an idea how I can do this?
Here is the code:
<?php session_start();?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Login</title>
<link href="bootstrap_style.css" rel="stylesheet" id="bootstrap-css"> <!-- maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <!-- //maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js or bootstrap.js-->
<script src="jquery.js"></script> <!-- //cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js -->
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="wrapper fadeInDown">
<div id="formContent">
<!-- Tabs Titles -->
<!-- Icon -->
<div class="fadeIn first">
<img src="default_logo2.png" id="icon" alt="User Icon" onclick="window.open('url', '_blank');"/>
</div>
<!-- Login Form -->
<form action="searchpage.php" method="post" onsubmit="validateForm(event);">
<input type="text" id="login" class="fadeIn second" name="username" placeholder="username">
<input type="password" id="password" class="fadeIn third" name="password" placeholder="password">
<input type="submit" class="fadeIn fourth" value="Log In">
</form>
<!-- Remind Passowrd -->
<div id="formFooter">
<a class="underlineHover" style="color:red" id="warning"></a>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
function validateForm(event) {
var input_username = document.getElementById("login");
var input_password = document.getElementById("password");
if (input_username.value == '' || input_username.value.charAt(0) == ' ' || input_password.value == '') {
event.preventDefault();
document.getElementById("warning").innerHTML = "Fill empty fields!";
}
else {
return true;
}
}
</script>
with this I reach the DB:
$pdo = new PDO('mysql:host=localhost;dbname=ausleihe', 'root', '');
and that is the SELECT:
$login_session = "SELECT * FROM login WHERE username = '".$hereshouldbetheusernamefromform."' AND password = '".herethepasswordfromform."'";
If you need more code or have questions, ask me!
Thx
Client-side JavaScript cannot directly access a Host-side PHP program except through AJAX calls. Only the Host-side software has access to Host-side databases.
$(function(){ $.get("header.html", function(data){
$("#header").html(data); }); });
So I am eventually going to have to do this in java but for now I just want to do this in the javascript extension known as jquery but any format that makes this work will please me.
I have 2 files:
header.html
<!-- Header -->
<div class="row navigationBar">
<!-- Company Logo -->
<div class="col-2">
<img src="images/GCB.png" alt="GCB-logo" class="gcb-logo">
</div>
<!-- Top Bar -->
<div class="col-md-10">
<div class="top-navigationBar">
<nav class="navbar navbar-expand-md quick-help">
<!-- Collapse Button -->
<button class="navbar-toggler navbar-light" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Quick Help -->
<div class="collapse navbar-collapse" id="navbarTogglerDemo01">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link black-font blue-line" href="">CONSULTATION</a>
</li>
<li class="nav-item">
<a class="nav-link black-font blue-line" href="">CUSTOMER SUPPORT</a>
</li>
<li class="nav-item">
<a class="nav-link black-font blue-line" href="">TIẾNG VIỆT</a>
</li>
</ul>
</div>
</nav>
</div>
<!-- Bottom Bar -->
<div>
<nav class="navbar navbar-expand-md bottom-navigationBar">
<div class="row bottom-navigationBar">
<!-- Quick Navigation -->
<div class="col-4">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<button type="button" class="btn btn-primary btn-sm thick-font button-flat-bottom">Checking</button>
</li>
<li class="nav-item">
<button type="button" class="btn btn-outline-secondary btn-sm thick-font button-flat-bottom">Savings</button>
</li>
<li class="nav-item">
<button type="button" class="btn btn-outline-secondary btn-sm thick-font button-flat-bottom">Loans</button>
</li>
</ul>
</div>
<!-- Bank Name -->
<div class="col-md-4">
<h1 class="bank-name">Go<span class="orange-text">Com</span>Bank</h1>
</div>
<!-- Login Form -->
<div class="login-container">
<form action="/action_page.php">
<input type="text" placeholder="Username" name="username">
<input type="text" placeholder="Password" name="psw">
<button type="button" class="btn btn-primary btn-sm">Login</button>
</form>
</div>
</div>
</nav>
</div>
</div>
</div>
<!-- Header End -->
and the webpage
webpage.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="header"></div>
</body>
</html>
I am trying to load header.html and set it into the id=("header") of webpage.html
Currently the only code that works is $("#header").html("")
Using this format I can set things like
<p>Hello World</p>
but it doesn't work when I want to add the loaded header.html items.
--NEW CONTENT WITH ANSWER IN PROGRESS--
So none of the answers have even come close to being correct but I have came up with my own solution that should in theory work but I have been unable to implement it myself.
Before the res.send(/*HTML Code Here*/);
I propose this solution::
A: load the HTML file into a var
B: load the insertion code into another var
C: A.replace("ReplaceKeyword", B);
D: res.send(A);
This method has worked for me when I use java and it sometimes works with jQuery but I can't seem to find the appropriate syntax to do this inside of javascript.
If you can provide the code to implement this then I can mark your response as the answer.
Note
A is something like
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!--InsertionPoint-->
</body>
</html>
B is something like
<p>Hello World</p>
Replace keyword in this instance would be ""
The End result that is sent in the res.send() is
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>Hello World</p>
</body>
</html>
=====================================
try this
<script>
document.getElementById("header").innerHTML='<object type="text/html" data="header.html"></object>';
</script>
Edited for new method
i found this on w3school. I already try it and i think this can solve your problem
https://www.w3schools.com/howto/howto_html_include.asp
<script>
includeHTML();
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
elmnt.innerHTML = this.responseText;
}
if (this.status == 404) {
elmnt.innerHTML = "Page not found.";
}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
on your body tag add something like this
<div w3-include-html="header.html"></div>
as long as you add w3-include-html attribute it will work, and you can add your stylesheet at the top of webpage.html
I crated a small login form where I check the username in a external php file. After that I give back an error message or redirect to another site.
My problem is to show the error message. I want a short message above the login form if the username != „test“. In my script, the errormessage appears above the login form, but the login form jumps one row deeper.
Question 1:
How can a create a placeholder above the login form? So that the login form is fix?
Question 2:
Is it the right way to fill a JavaScrpt Variable in PHP as in my Code?
Thanks for your help!
< script >
var error_login;
if (error_login == 1) {
$('#errorText').show();
} else {
$('#errorText').hide();
} <
/script>
<?php
//debug
error_reporting(-1);
ini_set('display_errors', true);
session_start();
session_unset();
session_destroy();
?>
<!doctype html>
<html lang="de">
<head>
<title>Hello World</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
</head>
<body>
<?php include ("login.php"); ?>
<div class="container">
<div id="errorText" class="row justify-content-center">
Login failed!
<!-- This should be a placeholder -->
</div>
<!-- Formular Beginn -->
<div class="row justify-content-center">
<div class="col-md-6">
<form class="form" role="form" method="post" action="?login=1" accept-charset="UTF-8" id="login">
<div class="input-group" id="frmGrpBenutzer">
<input type="password" class="form-control input-lg" id="user" name="user" placeholder="Username" required autofocus>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary btn-custom btn-lg" title="login" id="loginbtn"><span>Go</span></button>
</span>
</div>
</form>
</div>
</div>
</div>
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>
</html>
Here the login.php file:
<?php
session_start();
if(isset($_GET['login'])) {
$user = $_POST['user'];
if ($user == "test") {
$_SESSION['username'] = $user;
header('Location: site2.php');
} else {
echo "<script>
var error_login = 1;
</script>";
}
}
There are a few possibilities. The easiest would be to set your div with an opacity:0 or visibility:hidden this will make it still take space in the document flow.
Another option, could be to set it's position:absolute this will prevent it to take space inside your login form. Doing this will make it overlap tough, so there would need to be a padding or margin to offset the content of the form.
As for setting your javascript variable with PHP, that's one way to do it yes, but your script already defines error_login... Another way to do it, is use a holder HTML element, give it an id, and a data-* attribute. This will make it very easy to read the information from code:
$('button').click(function() {
console.log($('#login_status').data('login-error'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="login_status" data-login-error="1"></div>
<button>Click me to get result</button>
You could also add all the data you want into a JSON string as the div's content, and parse it once the page loaded.
I am trying to make a simplistic HTML editor for part of my website without things like Ace or TinyMCE. The problem is that when I'm using local storage, the save function appears to work, but the view function is not changing the notes to the saved notes.
I made a JSFiddle for all of you, at this URL.
Here is my HTML code:
<html>
<head>
<!-- Begin Section 1: Metas -->
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<!-- End Section 1: Metas -->
<!-- Begin Section 2: Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/nprogress/0.1.3/nprogress.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdn.mxpnl.com/libs/mixpanel-2.2.min.js" type="text/javascript"></script>
<script src="https://secure.quantserve.com/quant.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ladda-bootstrap/0.1.0/ladda.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ladda-bootstrap/0.1.0/spin.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.2/modernizr.min.js" type="text/javascript"></script>
<script src="scripts/app/app.js" type="text/javascript"></script>
<!-- End Section 2: Scripts -->
<!-- Begin Section 3: Stylesheets and Links -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/nprogress/0.1.3/nprogress.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Pacifico|Open+Sans|Roboto|Roboto+Slab" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/ladda-bootstrap/0.1.0/ladda.min.css" rel="stylesheet" type="text/css">
<link href="stylesheets/app/app.css" rel="stylesheet" type="text/css">
<!-- End Section 3: Stylesheets and Links -->
<!-- Start Section 4: Required Elements -->
<title>Superpad Editor</title>
<!-- End Section 4: Required Elements -->
</head>
<body>
<div class="container animated bounce">
<div class="errors"></div>
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-brand-centered">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="navbar-brand navbar-brand-centered"><span class="brand-logo">Superpad</span></div>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-brand-centered">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="btn-group">
<button type="button" class="btn btn-primary" id="save">Save Notes</button>
<button type="button" class="btn btn-success" id="view">View Saved Notes</button>
</div>
<div contenteditable class="content-editable normal editor"></div>
</div>
</body>
</html>
Here is my JavaScript (it uses jQuery):
NProgress.start();
mixpanel.init("<CENSORED FOR SECURITY>");
mixpanel.track("Page Loads");
NProgress.done();
$(document).ready(function(){
if (Modernizr.localstorage) {
console.log("L.S.W.");
} else {
$(".errors").append("<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×<\/span><span class="sr-only">Close<\/span><\/button><strong>Oh snap!<\/strong> Local Storage doesn't work on your browser. Saving won't work, so you might want to keep this open if you want to keep your notes.<\/div>");
NProgress.done();
};
$("#save").click(function() {
localStorage["note"] = JSON.stringify($(".editor").html());
});
$("#view").click(function() {
if (localStorage["note"] != null) {
var contentsOfOldDiv = JSON.parse(localStorage["note"]);
$(".editor").
$("div.fifth").replaceWith(contentsOfOldDiv);
} else {
$(".errors").append("<div class=alert alert-info alert-dismissible> role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×<\/span><span class="sr-only">Close<\/span><\/button><strong>Heads up!<\/strong> No save was detected. Did you save before?<\/div>");
};
});
});
So what am I doing wrong (I got the JSON parsing idea from another Stack Overflow subject!)?
You have several syntax issues. For example the lines below:
$(".errors").append("<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×<\/span><span class="sr-only">Close<\/span><\/button><strong>Oh snap!<\/strong> Local Storage doesn't work on your browser. Saving won't work, so you might want to keep this open if you want to keep your notes.<\/div>");
and
$(".errors").append("<div class=alert alert-info alert-dismissible> role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×<\/span><span class="sr-only">Close<\/span><\/button><strong>Heads up!<\/strong> No save was detected. Did you save before?<\/div>");
You need to escape the " character or use a single quote. That might not solve your issue, but it's a start. Your code is failing when execution reaches that line, and it can't continue, which might explain why you aren't getting the expected result.
Try using your browser developer tools to find any errors in your code. This page has some information on finding and using the dev tools in your browser. The error in the JSFiddle is shown as:
Uncaught SyntaxError: Unexpected identifier
If you fix the quotation issues, you then get the error:
Uncaught ReferenceError: mixpanel is not defined
Keep going through the errors in your console and see if you can narrow down the issue that way.
I'm trying to switch a "sign in" form for a "sign up" form whenever the user clicks on the "Sign Up" button in my angular app, but at the moment nothing is happening when the button is clicked; The sign in form remains on the screen and there are no console errors. Can anyone tell me where I'm going wrong?
I'm attempting to do this purely in html, is this even possible to achieve?
EDIT: I included a signup function in my UserCtrl which takes care of signing in/ out. Now when I click on sign up the alert is trigger but I get a console error saying TypeError: boolean is not a function.
$scope.signup = function() {
alert('signup function hit');
$scope.signup = true;
}
EDIT 2:
<!DOCTYPE html>
<html ng-app="myApp" >
<head>
<title> My App</title>
<link rel="stylesheet" type="text/css" href="css/app.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" type="text/css" href="css/signin.css">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet"/>
</head>
<body ng-controller="MainCtrl">
<div ng-switch on="view.name">
<div ng-switch-default ng-controller="UserCtrl">
<div ng-show="!isAuthenticated">
<form class = "form-signin">
<div class="control-group">
<img src="img/logo.png">
<br />
<div class="controls">
<br />
<input type="text" ng-model="username" placeholder = "Email Address" >
</div>
<br />
<div class="controls">
<input type="password" ng-model="password" placeholder = "Password" >
</div>
<div class="controls">
<button class = "btn btn-default" ng-click="signIn()">Sign In</button>
<button class = "btn btn-primary" ng-click="view.name = 'signup'">Register</button>
</div>
</div>
</form>
</div>
<div ng-switch-when="signup" ng-controller = "UserNewCtrl" >
<label>
This is where my form should be when my signup button is clicked.
</label>
</div>
//This part of index.html is only shown when a user has been authenticated
<div ng-show="isAuthenticated">
<div class="col-md-2">
//MenuBar code is here
</div>
//Other templates get loaded here
<div class="col-md-10">
<div ng-view></div>
</div>
</div>
</div>
<script src="js/vendor.js"></script>
<script src="js/app.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/transition.js"></script>
<script src="js/ui-utils.js"></script>
</div>
</body>
</html>
MainCtrl.js:
angular.module('myApp.controllers')
.controller('MainCtrl', function($scope) {
$scope.view={
name: ''
};
})
To achieve your requirement you need a wrapper controller that hold ng-switch on model because ngSwitch creates child scope.
You can design your view like
<body ng-controller="mainCtrl">
<div ng-switch on="view.name">
<div ng-switch-default ng-controller="signInCtrl">
<h1>this is sign in page</h1>
sign in
<br>
go to sign up page
</div>
<div ng-switch-when="signup" ng-controller="signUpCtrl">
<h1>this is sign up page</h1>
sign up
<br>
go to sign in page
</div>
</div>
</body>
Here mainCtrl holds view.name and by default ng-switch-default works means your sign in page, then when you click
go to sign up page
view.name model changed and your sign-up page appear.
Check the Demo
move the app controller to the html tag, then the directive in your body tag should read if you want to match an expression
<html ng-app="myApp">
<body ng-switch="signup">
see here
where signup is a boolean in your myApp scope, that will presumably be changed when the signIn criteria is satisfactory
$rootScope.signup = true;
you can also achieve similar with the ng-show and ng-hide directives