I have a form and I'm doing some validation JavaScript before send it to PHP, and the JavaScript function after validation post the text the user entered in a <p> tag at the bottom of the page; However, this message displays briefly and then disappears...
How can I make the message stay in the page, and send the rest of data to a PHP script?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Contact Us</title>
<!-- Bootstrap -->
<link href="bootstrap.min.css" rel="stylesheet">
<!-- stylesheet for this form -->
<link href="contact-stylesheet.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script type="text/javascript">
function validateForm() {
var message = "";
var letters = /^[A-Za-z]+$/;
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var subject = document.forms["myForm"]["subject"].value;
var text = document.forms["myForm"]["text"].value;
var outputMsg = "";
if (name == null || name == "") {
message += "name field missing!\n";
}
if (name != "" && !name.match(letters)) {
message += "Invalid name: only letters allowed!\n";
}
if (subject == null || subject == "") {
message += "Subject field is empty!\n";
}
if (text == null || text == "") {
message += "Text field is empty!\n";
}
if (message != "" ) {
alert(message);
return false;
}
outputMsg = "Message Sent!....\n" +
"Name: " + name + "\n" +
"Email: " + email + "\n" +
"Subject: " + subject + "\n" +
"Text: " + text + "\n";
document.getElementById("msg-result").innerHTML = outputMsg;
return true;
}
</script>
</head>
<body>
<div class="row">
<div class="hero-unit" style="padding:20px 100px">
<h1>Contact Us</h1>
<p>aldkfjasdkfjaskdfasdfkasdkfjadsfjsdkfjaskfjasdkfjasjfaskdfjsdkfjsksdsdkjsd</p>
</div>
<div class="col-sm-6">
<div class="my-form">
<form class="form-horizontal" name="myForm" action="" onsubmit="validateForm()" method="post">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Name:</label>
<div class="col-sm-8">
<input type="name" name="name" class="form-control" id="inputEmail3" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Email:</label>
<div class="col-sm-8">
<input type="email" name="email" class="form-control" id="inputPassword3" placeholder="Email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Subject:</label>
<div class="col-sm-8">
<input type="text" name="subject" class="form-control" placeholder="Subject">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Text:</label>
<div class="col-sm-8">
<textarea name="text" class="form-control" rows="7" placeholder="Text"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Send</button>
</div>
</div>
</div>
</form>
</div>
<div class="col-sm-6">
<div style="width:500px;heigth:350px;border:solid 1px brown">
<h1>GOOGLE MAP HERE!</h1>
</div>
<!-- <img sytle="padding:0px 20px" src="https://maps.googleapis.com/maps/api/staticmap?center=Miami+Downtown,Miami,FL&zoom=13&size=500x350&maptype=roadmap&markers=color:red%7CMiami+Downtown,Miami,FL"> -->
</div>
</div>
<div class="col-sm-6" style="padding:10px 140px">
<p id="msg-result"></p>
<!-- display form result message here! -->
</div>
<!--
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
It's because you are updating the text in the field and then submitting to php (wiping out all of the fields since the page refreshes). You could set hidden elements to hold the values that you want to display so they post over to php and then you can just echo them where you want them to be. Another way of doing it would be to make an ajax call to a php to do your updating instead of posting back to the same page.
So with ajax you would do something like:
formSubmit()
{
//do validation
//do a jquery post to a php page
$.ajax
({
type: "POST",
//the url of the php page
url: 'test.php',
dataType: 'json',
async: false,
//json object to sent to the authentication url
data: '{"test": "info"}',
success: function (result) {
//update stuff
}
})
return false;
}
I think the form is submitted after the check. You must return the result (to cancel the submit if validateForm() is false):
onsubmit="return validateForm();"
or prevent default:
onsubmit="return validateForm(event);"
with
function validateForm(event) {
...
event.preventDefault();
Related
I am trying to add a Bootstrap validation in a form. My expected results is:
When the form is submitted, if "First name" field is empty, the "Please enter a name" message should be displayed below the field, otherwise "Looks good" should be displayed.
I tried it by adding and removing "d-none" class in the javascript, but the problem is "Looks good" is disappearing but "Please enter a name" is not displaying.
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
var invalidOptions = document.querySelectorAll(".form-control:invalid");
invalidOptions.forEach(function (element) {
element.parentNode.childNodes.forEach(function (node) {
if (node.className == 'valid-feedback') {
node.classList.add('d-none');
}
});
});
var validOptions = document.querySelectorAll(".form-control:valid");
invalidOptions.forEach(function (element) {
element.parentNode.childNodes.forEach(function (node) {
if (node.className == 'invalid-feedback') {
node.classList.remove('d-none');
}
});
});
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationServer01">First name</label>
<input type="text" class="form-control is-valid" id="validationServer01" placeholder="First name" value="Mark"
required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback d-none">Please enter a name</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</form>
</body>
</html>
Your js code is Bootstrap will manage the showing & hiding of the valid-feedback and invalid-feedback depending on whether the content is valid. By manually adding d-none to the invalid-feedback, it is affecting this behaviour. Simply remove d-none from the classes and it works:
<label for="validationServer01">First name</label>
<input type="text" class="form-control is-valid"
id="validationServer01" placeholder="First name" value="Mark"
required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter a name</div> <!-- REMOVE d-none FROM HERE -->
Now, when you submit the form, if the name is empty it will show your "Please enter a name" message.
Working Example:
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function () {
'use strict';
window.addEventListener('load', function () {
// Fetch all the forms we want to apply custom Bootstrap validation styles to
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
var invalidOptions = document.querySelectorAll(".form-control:invalid");
invalidOptions.forEach(function (element) {
element.parentNode.childNodes.forEach(function (node) {
if (node.className == 'valid-feedback') {
node.classList.add('d-none');
}
});
});
var validOptions = document.querySelectorAll(".form-control:valid");
invalidOptions.forEach(function (element) {
element.parentNode.childNodes.forEach(function (node) {
if (node.className == 'invalid-feedback') {
node.classList.remove('d-none');
}
});
});
}
form.classList.add('was-validated');
}, false);
});
}, false);
})();
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<form class="needs-validation" novalidate>
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationServer01">First name</label>
<input type="text" class="form-control is-valid" id="validationServer01" placeholder="First name" value="Mark"
required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Please enter a name</div>
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</form>
</body>
</html>
Problem
: getting an error when I try to use firebase.auth to create a new user.
Error
Uncaught TypeError: firebase.auth.createUserWithEmailAndPassword is not a function
What should happen : In my html there is a form for user sign up with email and password. On button click my script takes the input from the sign up form and passes it to firebase.auth however firebase.auth seems to not be available from an external script that is being included into the html file. The html file does have the firebase includes and I can deploy my code into firebase hosting, I already went through the firebase localhost installation process from the firebase docs.
Here is my HTML
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Sign Up</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:300,400,400i,600,700,800,900" rel="stylesheet">
<link href="dist-assets/css/themes/lite-purple.min.css" rel="stylesheet">
<!-- update the version number as needed -->
<script defer src="/__/firebase/7.12.0/firebase-app.js"></script>
<!-- include only the Firebase features as you need -->
<script defer src="/__/firebase/7.12.0/firebase-auth.js"></script>
<script defer src="/__/firebase/7.12.0/firebase-database.js"></script>
<script defer src="/__/firebase/7.12.0/firebase-messaging.js"></script>
<script defer src="/__/firebase/7.12.0/firebase-storage.js"></script>
<!-- initialize the SDK after all desired features are loaded -->
<script defer src="/__/firebase/init.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nunito:300,400,400i,600,700,800,900" rel="stylesheet">
<link href="dist-assets/css/themes/lite-purple.min.css" rel="stylesheet">
</head>
<div class="auth-layout-wrap" style="background-image: url(dist-assets/images/photo-wide-4.jpg)">
<div class="auth-content">
<div class="card o-hidden">
<div class="row">
<div class="col-md-6 text-center" style="background-size: cover;background-image: url(dist-assets/images/photo-long-3.jpg)">
<div class="pl-3 auth-right">
<div class="auth-logo text-center mt-4"><img src="dist-assets/images/car.png" alt=""></div>
<div class="flex-grow-1"></div>
<div class="w-100 mb-4"><a class="btn btn-outline-primary btn-block btn-icon-text btn-rounded" href="/"><i class="i-Mail-with-At-Sign"></i> Sign in with Email</a><a class="btn btn-outline-google btn-block btn-icon-text btn-rounded"><i class="i-Google-Plus"></i> Sign in with Google</a><a class="btn btn-outline-facebook btn-block btn-icon-text btn-rounded"><i class="i-Facebook-2"></i> Sign in with Facebook</a></div>
<div class="flex-grow-1"></div>
</div>
</div>
<div class="col-md-6">
<div class="p-4">
<h1 class="mb-3 text-18">Sign Up</h1>
<form action="">
<div class="form-group">
<label for="username">Your name</label>
<input class="form-control form-control-rounded" id="username" type="text">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input class="form-control form-control-rounded" id="email" type="email">
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control form-control-rounded" id="password" type="password">
</div>
<div class="form-group">
<label for="repassword">Retype password</label>
<input class="form-control form-control-rounded" id="repassword" type="password">
</div>
<button onclick="signUpWithEmail(event)" class="btn btn-primary btn-block btn-rounded mt-3">Sign Up</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
// // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
// // The Firebase SDK is initialized and available here!
//
// firebase.auth().onAuthStateChanged(user => { });
// firebase.database().ref('/path/to/ref').on('value', snapshot => { });
// firebase.messaging().requestPermission().then(() => { });
// firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
//
// // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
try {
let app = firebase.app();
let features = ['auth', 'database', 'messaging', 'storage'].filter(feature => typeof app[feature] === 'function');
const auth = firebase.auth();
console.log(features);
} catch (e) {
console.error(e);
}
});
</script>
<script src="dist-assets/js/app-js/app-dist.js"></script>
And Here is my js
//Sign up with email and password
function signUpWithEmail(e){
e.preventDefault();
var name = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var passwordMatch = document.getElementById("repassword").value;
//Create user
auth.createUserWithEmailAndPassword(email, password).then(cred => {
console.log(cred);
})
//Get UID
//Create New Collection identified by UID
//Create user info document
//Add user email and name to user info document
}
I was calling firebase.auth.createUserWithEmailAndPassword()
It should have been firebase.auth().createUserWithEmailAndPassword() which I did do right on my sign in method using auth()..
Yep Im kicking myself right now
I'm trying to pass form values, check them and then return the response with jquery, everything gets passed correctly, the image gets uploaded and the path gets added to the database, but instead of returning the message on the same page, it redirects to the addmember.php, doesn't even go through the checks - like the javascript file doesn't even exist and it has been bothering me for quite a while... I've tried searching but I didn't find anything relatable to me since the problem lies in the picture/image...
Uncaught TypeError: Cannot read property 'val' of null
addmember.js and the **form
$(document).ready(function() {
$("#submit").click(function() {
var membershipnumber = $("#membershipnumber").val();
var membername = $("#membername").val();
var membersurname = $("#membersurname").val();
var memberdate = $("#memberdate").val();
var memberphonenumber = $("#memberphonenumber").val();
var memberemail = $("#memberemail").val();
var memberpicture = document.getElementById("#memberpicture").val();
if ((membershipnumber == "") || (membername == "") || (membersurname == "") || (memberdate == "") || (memberphonenumber == "")) {
$("#message").html("<div class=\"alert alert-danger alert-dismissable fade in\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">×</button>Polja označena sa * ne smeju biti prazna.</div>");
} else {
$.ajax({
type: "POST",
url: "addmember.php",
data: {
"membershipnumber": membershipnumber,
"membername": membername,
"membersurname": membersurname,
"memberdate": memberdate,
"memberphonenumber": memberphonenumber,
"memberemail": memberemail,
"memberpicture": memberpicture
},
success: function(html) {
var text = $(html).text();
var response = text.substr(text.length - 4);
$("#message").html(html);
},
error: function() {
},
beforeSend: function() {
$("#message").html("<p class='text-center'><img src='images/ajax-loader.gif'></p>")
}
});
}
return false;
});
});
<form name="createnewmember" id="createnewmember" method="post" action="addmember.php" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<!-- name and surname -->
<label for="membername" class="col-xs-2 control-label">Ime i prezime:<font color="#d9534f">*</font></label>
<div class="col-xs-10">
<div class="form-inline">
<input name="membername" id="membername" type="text" class="form-control" placeholder="Ime" autofocus />
<input name="membersurname" id="membersurname" type="text" class="form-control" placeholder="Prezime" />
</div>
</div>
</div>
<!-- /name and surname -->
<div class="form-group">
<!-- date of birth -->
<label for="memberdate" class="col-xs-2 control-label">Datum rođenja:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="memberdate" id="memberdate" type="date" class="form-control" value="1990-01-01" />
</div>
</div>
<!-- /date of birth -->
<div class="form-group">
<!-- membership number (scanned with barcode scanner) -->
<label for="membershipnumber" class="col-xs-2 control-label">Članski broj:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="membershipnumber" id="membershipnumber" type="text" class="form-control" placeholder="Članski broj" data-toggle="tooltip" data-placement="right" title="Očitajte bar-kod sa nekorišćene kartice." />
</div>
</div>
<!-- /membmership number -->
<div class="form-group">
<!-- phone number -->
<label for="memberphonenumber" class="col-xs-2 control-label">Broj telefona:<font color="#d9534f">*</font></label>
<div class="col-xs-3">
<input name="memberphonenumber" id="memberphonenumber" type="text" class="form-control" placeholder="Broj telefona" />
</div>
</div>
<!-- /phone number -->
<div class="form-group">
<!-- email -->
<label for="memberemail" class="col-xs-2 control-label">Email adresa:</label>
<div class="col-xs-3">
<input name="memberemail" id="memberemail" type="text" class="form-control" placeholder="Email adresa" />
<div class="checkbox">
<label><input name="memberemailinglist" id="memberemailinglist" type="checkbox" disabled/> Prijavi na mailing listu?</label>
</div>
</div>
</div>
<!-- /email -->
<div class="form-group">
<!-- picture -->
<label for="memberpicture" class="col-xs-2 control-label">Slika:</label>
<div class="col-xs-10">
<label class="btn btn-default" for="memberpicture">
<input id="memberpicture" name="memberpicture" type="file" style="display:none;" onchange="$('#memberpicture-info').html($(this).val());" accept=".jpg,.png,.jpeg" class="form-control" />
<span class="glyphicon glyphicon-camera"></span> Traži...
</label>
<span class="label label-danger" id="memberpicture-info">Nije izabrana ni jedna slika...</span>
</div>
</div>
<!-- /picture -->
<div class="form-group">
<span class="pull-right">Polja označena sa <font color="#d9534f">*</font> su obavezna!  </span>
<!-- required fields text -->
</div>
<button name="Submit" id="submit" class="btn btn-default pull-right" type="submit">Podnesi</button>
<!-- submit button -->
</form>
<!-- /form -->
addmember.php
<?php
require 'includes/functions.php';
include_once 'config.php';
$membershipnumber = $_POST['membershipnumber'];
$membername = $_POST['membername']." ".$_POST['membersurname'];
$membersurname = $_POST['membersurname'];
$memberdate = $_POST['memberdate'];
$memberphonenumber = $_POST['memberphonenumber'];
$memberemail = $_POST['memberemail'];
$memberpicture_dir = '/images/members';
if(isset($_FILES['memberpicture'])) {
$memberpicture_temp = $_FILES['memberpicture']['tmp_name'];
$ext = pathinfo(basename($_FILES['memberpicture']['name']), PATHINFO_EXTENSION);
$memberpicture = $membershipnumber.".".$ext;
move_uploaded_file($memberpicture_temp , $_SERVER['DOCUMENT_ROOT'] . '/spartangym/images/members/' . $memberpicture);
} else {
$memberpicture = "nopicture.jpg";
}
$regdate = new DateTime();
$memberregdate = $regdate->getTimestamp();
$memberexpires = $memberregdate + 2592000;
if (strlen($memberemail) > 0 && !filter_var($memberemail, FILTER_VALIDATE_EMAIL) == true) {
echo '<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Email adresa nije validna.</div><div id="returnVal" style="display:none;">false</div>';
} else {
$a = new AddMemberForm;
$response = $a->createMember($membershipnumber, $membername, $memberdate, $memberphonenumber, $memberemail, $memberpicture, $memberregdate, $memberexpires);
if ($response == 'true') {
echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>Član '. $membername .' je uspešno dodat u bazu.</div><div id="returnVal" style="display:none;">true</div>';
} else {
mySqlErrors($response);
}
};
?>
Your problem is here
var memberpicture = document.getElementById("#memberpicture").val();
Native methods don't have val(), nor should you include the hash.
As val() is a jQuery method, you probably wanted to do
var memberpicture = $("#memberpicture").val();
The native alternative would be
var memberpicture = document.getElementById("memberpicture").value;
Your validation looks fine, but on-click you should use event.preventDefault() to keep the form from submitting and only allow the submission in the event of all fields being valid.
Usage here:
https://api.jquery.com/event.preventdefault/
at first check
before check
var membershipnumber = $("#membershipnumber").val();
after check
var membershipnumber='none object';
if(typeof($('#membershipnumber'))!="undefined")
{
membershipnumber= $('#membershipnumber').val();
}
alert(membershipnumber);
I am trying the $resource of Angularjs, but there is an error with my program, and I can't figure it out.
<!DOCTYPE html>
<html>
<!--Login form validate, send to server, get from server-->
<head>
<meta charset="utf-8">
<title></title>
<link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="bower_components/bootstrap/dist/css/bootstrap-theme.min.css" rel="stylesheet">
<link href="bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">
<script src="bower_components/angular/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div class="container" ng-controller="myController">
<div class="row">
<div>
<p style="margin: 30px"></p>
</div>
<form ng-submit="sendform()">
<div class="form-group row">
<label class="col-sm-2 col-sm-offset-2 col-sm-push-6 form-control-label" for="email">Email</label>
<div class="col-sm-6 col-sm-pull-2">
<input type="email" class="form-control" id="email" ng-model="newInfo.email">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-sm-offset-2 col-sm-push-6 form-control-label" for="password">Password</label>
<div class="col-sm-6 col-sm-pull-2">
<input type="password" class="form-control" id="password" ng-model="newInfo.password">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-sm-offset-2 col-sm-push-6 form-control-label">How do you know us</label>
<div class="col-sm-6 col-sm-pull-2">
<div class="radio" ng-repeat="source in knowSources">
<label>
<input type="radio" name="{{source}}" ng-model="newInfo.method" ng-value="source" id="{{source}}">
{{source}}
</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-sm-6 col-sm-push-2">
<button type="submit" class="btn btn-primary">Send information</button>
</div>
</div>
</form>
</div>
</div>
<script type="text/javascript">
angular.module("myApp",[])
.factory('resourceEntry',["$resource",function ($resource) {
return $resource('http://localhost:3000/contactInfo/:id');
}])
.controller("myController",["$scope","$log","resourceEntry",function ($scope,$log,resourceEntry) {
//the update object
$scope.newInfo = {email:"",password:"",method:""};
$scope.knowSources = ["Internet","Friends","Television","Others"];
//the form array
$scope.contactInfo = [];
$scope.sendform = function(){
$scope.newInfo.email = this.newInfo.email;
$log.info("newInfo.email: " + $scope.newInfo.email + "; tpye: " + typeof $scope.newInfo.email);
$scope.newInfo.password = this.newInfo.password;
$log.info("newInfo.password: " + $scope.newInfo.password + "; tpye: " + typeof $scope.newInfo.password);
$scope.newInfo.method = this.newInfo.method;
$scope.contactInfo.push($scope.newInfo);
$log.info("$scope.contactInfo(array): " + $scope.contactInfo[0]);
resourceEntry.save($scope.newInfo);
$scope.newInfo = {email:"",password:"",method:""};
}
}]);
</script>
</body>
</html>
I have a JSON file containing an empty array of contactInfo. The error shows
angular.js:13424Error: [$injector:unpr]
http://errors.angularjs.org/1.5.3/$injector/unpr?p0=%24resourceProvider%20%3C-%20%24resource%20%3C-%20resourceEntry
at Error (native)...
which means the error results from the $injector being unable to resolve a required dependency. To fix this, make sure the dependency is defined and spelled correctly.
I have checked that the dependencies for javascript should be fine, so I don't know why.
You did not include the angular-resource file. ie
Install it by bower according to the following command
bower install angular-resource --save
Then include
<script src="assets/bower_components/angular-resource/angular-resource.js"></script>
And also don't forget to inject the ngResource in your app
angular.module("myApp",['ngResource'])
.factory('resourceEntry',["$resource",function ($resource) {
return $resource('http://localhost:3000/contactInfo/:id');
}])
Working Demo
Add angular-resource.min.js
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="http://code.angularjs.org/1.0.7/angular-resource.min.js"></script>
Inject ngResource
angular.module("myApp",['ngResource'])
.factory('resourceEntry',["$resource",function ($resource) {
return $resource('http://localhost:3000/contactInfo/:id');
}])
.controller("myController",["$scope","$log","resourceEntry",function ($scope,$log,resourceEntry) {
//the update object
$scope.newInfo = {email:"",password:"",method:""};
$scope.knowSources = ["Internet","Friends","Television","Others"];
//the form array
$scope.contactInfo = [];
$scope.sendform = function(){
$scope.newInfo.email = this.newInfo.email;
$log.info("newInfo.email: " + $scope.newInfo.email + "; tpye: " + typeof $scope.newInfo.email);
$scope.newInfo.password = this.newInfo.password;
$log.info("newInfo.password: " + $scope.newInfo.password + "; tpye: " + typeof $scope.newInfo.password);
$scope.newInfo.method = this.newInfo.method;
$scope.contactInfo.push($scope.newInfo);
$log.info("$scope.contactInfo(array): " + $scope.contactInfo[0]);
resourceEntry.save($scope.newInfo);
$scope.newInfo = {email:"",password:"",method:""};
}
}]);
Hope that solve your problem.
Usually I use formName.inputName.$invalid to show error message input like this:
<input name="myInput" minlength="3" />
<span ng-show="myForm.myInput.$invalid">too short</span>
that won't be a problem.
But when I tried to validate checkbox,it seems difficult, there are the snippet at the end.
I want the effect that user should at least check one checkbox ,or you got the warning message.
How can I do that in a simple way at best?
// app.js
var formApp = angular.module('formApp', [])
.controller('formController', function($scope) {
// we will store our form data in this object
$scope.formData = {};
$scope.formData.favoriteColors = [{
'id':'1',
'name':'red'
},{
'id':'2',
'name':'green'
},{
'id':'3',
'name':'blue'
}];
$scope.cList = [];
$scope.checkList = function(index){
if($scope.myForm.favoriteColors.$pristine){
$scope.cList.push($scope.formData.favoriteColors[index]);
}
else{
angular.forEach($scope.formData.favoriteColors,function(value,key){
if(value.checked){
$scope.cList.push(value.id);
}
});
}
console.log('cList:%o',$scope.cList);
};
});
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<!-- CSS -->
<!-- load up bootstrap and add some spacing -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<link href="http://cdn.bootcss.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<style>
body { padding-top:50px; }
form { margin-bottom:50px; }
</style>
<!-- JS -->
<!-- load up angular and our custom script -->
<script src="lib/angular/angular.min.js"></script>
<script src="app.js"></script>
</head>
<!-- apply our angular app and controller -->
<body ng-app="formApp" ng-controller="formController">
<div class="col-xs-12 col-sm-10 col-sm-offset-1">
<h2>Angular Checkboxes and Radio Buttons</h2>
<form name="myForm">
<!-- NAME INPUT -->
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="formData.name">
</div>
<!-- MULTIPLE CHECKBOXES -->
<label>Favorite Colors</label>
<div class="form-group">
<label class="checkbox-inline" ng-repeat="color in formData.favoriteColors">
<input type="checkbox" name="favoriteColors" ng-model="color.checked" ng-click="checkList($index)" required>{{color.name}}
</label>
<span class="danger" ng-show="myForm.favoriteColors.$invalid">Please check one color at least</span>
</div>
<!-- SUBMIT BUTTON (DOESNT DO ANYTHING) -->
<button type="submit" class="btn btn-danger btn-lg">Send Away!</button>
</form>
<!-- SHOW OFF OUR FORMDATA OBJECT -->
<h2>Sample Form Object</h2>
<pre>
dirty:{{ myForm.favoriteColors.$dirty }}
pristine:{{ myForm.favoriteColors.$pristine }}
valid:{{ myForm.favoriteColors.$valid }}
invalid:{{ myForm.favoriteColors.$invalid }}
error:{{ myForm.favoriteColors.$error }}
</pre>
</div>
</body>
</html>
Here is the live demo:http://jsbin.com/yigujoporu/1/
I use a count funtcion to update the number of checked checkbox.
Here is the live demo:http://jsbin.com/wowipi/4/edit?js,output
You can custom validation by another way
First, in your controller
$scope.cList = [];
$scope.checked = false;
$scope.checkList = function(index){
if($scope.myForm.favoriteColors.$pristine){
$scope.cList.push($scope.formData.favoriteColors[index]);
}
else{
if($scope.formData.favoriteColors[index].checked == true){
//checked
$scope.cList.push($scope.formData.favoriteColors[index]);
}else{
//uncheck
angular.forEach($scope.cList, function(value,key){
if($scope.formData.favoriteColors[index].id == value.id){
//remove it
$scope.cList.splice(key,1);
}
}
}
console.log('cList:%o',$scope.cList);
//new change
if($scope.cList.length >0) {
$scope.checked = true;
}else{
$scope.checked = false;
}
};
In your view
<div class="form-group">
<label class="checkbox-inline" ng-repeat="color in formData.favoriteColors">
<input type="checkbox" name="favoriteColors" ng-model="formData.favoriteColors[$index].checked" ng-click="checkList($index)" required>{{color.name}}
</label>
<span class="danger" ng-show="!checked">Please check one color at least</span>
</div>