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>
Related
I'm trying to access the state of a checkbox that has been made into a switch using the Bootstrap Switch (http://bootstrapswitch.com/) and the Bootstrap Switch gem with Ruby on Rails. With this I'm then aiming to show / hide certain divs.
I had it working for standard radio buttons but for a checkbox that's been changed into a switch I can't work it out. Any help would be great thanks.
Using Simple Form gem for my form:
<%= f.input :legal_protection, label: "Add Legal Protection", input_html: { name: 'my-checkbox' }, checked: false %>
JS:
// Show/hide Legal Protection Details on checkbox change
jQuery(document).ready(function() {
jQuery('[name="my-checkbox"]').on('change', function() {
if (jQuery(this).val() == 'true' ) {
jQuery('.initial_quote').hide();
jQuery('.legal1').show();
jQuery('#legal2').show();
} else {
jQuery('.initial_quote').show();
jQuery('.legal1').hide();
jQuery('#legal2').hide();
}
});
});
// Show/hide Legal Protection Details on page load
$(document).ready(function() {
var $legal_pro = $('input:checkbox[id=user_legal_protection]');
if($legal_pro.is(':checked') === false) {
jQuery('#legal2').hide()
jQuery('.initial_quote').show()
jQuery('.legal1').hide()
}
});
Relevant Html output:
<div class="form-group boolean optional user_legal_protection">
<div class="checkbox">
<input value="0" name="my-checkbox" type="hidden">
<label class="boolean optional" for="user_legal_protection">
<div class="bootstrap-switch bootstrap-switch-wrapper bootstrap-switch-id-user_legal_protection bootstrap-switch-animate bootstrap-switch-off" style="width: 106px;">
<div class="bootstrap-switch-container" style="width: 156px; margin-left: -52px;">
<span class="bootstrap-switch-handle-on bootstrap-switch-primary" style="width: 52px;">ON</span>
<span class="bootstrap-switch-label" style="width: 52px;"> </span>
<span class="bootstrap-switch-handle-off bootstrap-switch-default" style="width: 52px;">OFF</span>
<input name="my-checkbox" class="boolean optional" type="checkbox" value="1" id="user_legal_protection">
</div>
</div>Add Legal Protection</label>
</div>
</div>
This line is your issue:
jQuery('[name="my-checkbox"]').on('change', function() {
^^^^^^
Using bootstrapswitch you have to use the event:
switchChange.bootstrapSwitch: Triggered on switch state change. 'this' refers to the DOM element.
A demo:
$("[name='my-checkbox']").bootstrapSwitch();
$('[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) {
console.log('checkbox state: ' + state);
if (state) {
jQuery('.initial_quote').hide();
jQuery('.legal1').show();
jQuery('#legal2').show();
} else {
jQuery('.initial_quote').show();
jQuery('.legal1').hide();
jQuery('#legal2').hide();
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet"
href="https://rawgit.com/Bttstrp/bootstrap-switch/master/dist/css/bootstrap3/bootstrap-switch.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://rawgit.com/Bttstrp/bootstrap-switch/master/dist/js/bootstrap-switch.min.js"></script>
<div class="form-group boolean optional user_legal_protection">
<label class="boolean optional" for="user_legal_protection">
<input value="0" type="checkbox" name="my-checkbox" id="user_legal_protection" type="hidden">
Add Legal Protection</label>
</div>
I am not able to see error message on clicking the submit button using angularjs.
Any lead will be appreciated
Thanks in advance :)
<form id="formbody" ng-submit="submituser(form)" name="form" novalidate>
<input type="text" ng-class="{ errorinput: submitted && form.dob.$invalid }" name="dob" ng-model="dob" placeholder="Date of Birth" required />
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
<!-- <div type="button" id="btn" style="color: red;" >Submit</div> -->
</div>
</div>
</form>
.controller('ExampleController', function($scope, $location, $scope, $stateParams) {
$scope.singleSelect = '';
$scope.goToPage = function() {
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submituser = function($scope) {
if ($scope.form.$valid) {} else {
$scope.submitted = true;
}
}
})
change ng-show of span to
<span class="e" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
please check the form name
you have used two different names
name ="form" in form tag and used as signUpForm.dob in input field.
Check your ng-model to
<form id="formbody" ng-submit="submituser(form)" name="signUpForm" novalidate>
<input type="text" ng-class="{ errorinput: submitted && signUpForm.dob.$invalid }" name="dob" ng-model="form.dob" placeholder="Date of Birth" required />
<span class="e" ng-if="submitted && signUpForm.dob.$invalid">Please provide a valid date of birth</span>
<div style="padding-left: 275px;">
<button type="submit">Submit</button>
</div>
</div>
</form>
.controller('ExampleController',function($scope,$location,$scope, $stateParams){
$scope.singleSelect='';
$scope.goToPage=function(){
console.log("selectservice");
$location.path("/selectservice");
}
$scope.submitted =false;
$scope.submituser = function(form){
// console.log(form);
if (form.$valid) {
your logic
} else {
$scope.submitted = true;
}
}
})
Try something like that
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" ng-app>
<div class="control-group" ng-class="{true: 'error'}[submitted && form.dob.$invalid]">
<label class="control-label" for="dob">Your Date of Birth</label>
<div class="controls">
<input type="text" name="dob" ng-model="dob" required />
<span class="help-inline" ng-show="submitted && form.dob.$invalid">Please provide a valid date of birth</span>
</div>
</div>
<button type="submit" class="btn btn-primary btn-large" ng-click="submitted=true">Submit</button>
</form>
You have to provide the form name but even after that you cannot refer to your form in controller unless you pass it through the submit function arguments. Also there is not signupForm() function in your controller.
The way to go is :
<form id="formbody" name="myForm" ng-submit="signupForm(myForm)" novalidate>
<!-- inputs etc -->
</form>
Then based on submituser():
$scope.signupForm = function(myForm) {
//Do whatever you want to do
if(myForm.$valid) {
//some logic
}else {
$scope.submitted = true;
}
}
On the other hand if you don't want to mess up with the controller you can always use FormController method $submitted. This would look like:
<span class="e" ng-show="myForm.$submitted && myForm.dob.$invalid">Please provide a valid date of birth</span>
So, I have this form, made using AngularJS here, which basically lets me create a purchase object to send to a server, i.e, it lets me select a store where I bought some items, set a "date of purchase" (just a text field for now), and add those items to the object I'm gonna send.
After the submit button it is shown how the model I'm going to send will look like, showing the id of the store, the "datetime", and an array of items.
My question is: Is there a way of doing this form using angular-formly only?
The question arises because I've been reading formly's docs and I haven't figured out how to make it create such a dynamic model as this form does, i.e., with a variable-length array of items of the purchase, or if it is at all possible.
Thanks in advance for any clue you can give me to answer this question :)
The code for the form is as follows:
(function(){
var app = angular.module('test', []);
})();
The html page:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.js"></script>
<script src="inab.js"></script>
<script src="PurchaseCtrl.js"></script>
</head>
<body ng-app="test">
<div ng-controller="PurchaseCtrl" class="col-md-4">
<h2>Purchase</h2>
<div class="panel panel-default">
<div class="panel-heading">Title</div>
<div class="panel-body">
<div class="form-group">
<label>Store</label>
<select class="form-control" ng-model="model.store">
<option ng-repeat="store in stores" value="{{store.id}}">{{store.name}}</option>
</select>
</div>
<div class="form-group">
<label>date-time</label>
<input class="form-control" type="text" ng-model="model.datetime"/>
</div>
<div ng-repeat="item in items">
<div class="form-group">
<div class="col-sm-2">
<label>{{item.label}}</label>
</div>
<div class="col-sm-8">
<input class="form-control" type="text" ng-model="item.nome" />
</div>
<div class="col-sm-2">
<button type="submit" class="btn btn-alert submit-button col-md-2" ng-click="removeItem()">remove item</button>
</div>
</div>
</div>
<button ng-click="addItem()">Add item</button>
</div>
</div>
<button type="submit" class="btn btn-primary submit-button" ng-click="onSubmit()">Submit</button>
<pre>{{model | json}}</pre>
</div>
</body>
</html>
The controller:
(function(){
angular.module('test').controller('PurchaseCtrl', ['$scope', function(scope){
scope.stores = [{id: 1, name:'Store 1'}, {id: 2, name: 'Store 2'}];
scope.items = [];
scope.datetime = '';
scope.store = '';
var i = 0;
scope.model = {
store: scope.store,
datetime: scope.datetime,
items: scope.items
};
scope.addItem = function(){
scope.items.push({label: 'algo' + (i++), nome:''});
}
scope.removeItem = function(){
scope.items.splice(scope.items.length - 1);
}
scope.onSubmit = function(){
console.log(scope.model);
}
}]);
})();
As #Satej commented, it was with repeated sections. Thanks :)
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();
How can i show alert box for validation in login form?
I got below output but i want alert box?
This is my index page: index.jsp
<html:form styleId="validate" action="/account_login" styleClass="account" method="post">
<div class="content controls single_advance">
<!-- <div class="form-row user-change-row">-->
<div class=form-row>
<div class=col-sm-3></div>
<div class=col-sm-4>
<bean:write name="account_bean" property="error" filter="false"/>
</div>
</div>
<div class="form-row">
<div class="col-md-12">
<div class=input-group>
<div class=input-group-addon> <span class=icon-user></span> </div>
<!--<input type=text class=form-control placeholder="Account Name"/>-->
<html:text property="name" styleClass="validate[required] form-control" styleId="Account_Name"/>
</div>
</div>
</div>
<div class=form-row>
<div class="col-md-12">
<div class=input-group>
<div class=input-group-addon> <span class=icon-key></span> </div>
<!--<input type=password class=form-control placeholder="Password"/>-->
<html:password property="password" styleClass="validate[required] form-control" styleId="Password"/>
</div>
</div>
</div>
<div class=form-row>
<div class="col-md-6 col-md-offset-3">
<input class="btn btn-default btn-block btn-clean btn-success" value="Log In" type="submit">
</div>
</div>
<!--<div class=form-row>
<div class="col-md-12"> Forgot your password? </div>
</div>-->
<div class=form-row>
<div class="col-md-12 tac"><strong>OR USE </strong></div>
</div>
<div class=form-row>
<div class="col-md-12"> <a class="btn btn-primary btn-block imeino"><span class="icon-mobile-phone"></span> IMEI NO LOGIN</a> </div>
</div>
</div>
</html:form>
This is my struts action class: account_actoin.java
if (account_name.equals(acc_name) && account_password.equals(acc_password)) {
HttpSession http_session = request.getSession(true);
http_session.setAttribute("login_name", acc_name);
ArrayList<String> name_list = new ArrayList<String>();
Query enc_password = session.createQuery("from account_dao");
List list = enc_password.list();
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
account_dao account = (account_dao) iterator.next();
System.out.println("Id : " + account.getId());
System.out.println("Account Name : " + account.getName());
System.out.println("Account Password : " + account.getPassword());
int i = 0;
name_list.add(i,account.getName());
i++;
}
request.setAttribute("namelist", name_list);
dealer_bean Bean = new dealer_bean();
Bean.setCustomerList(name_list);
System.out.println("List : "+name_list);
return mapping.findForward(SUCCESS);
} else {
fromBean.setError("<span style='color:red'><h6>Login failed.</h6></span>");
return mapping.findForward(FAILURE);
}
How can I show error (or) success message in alert box?
Append after the html:form close tag the next code and try:
<logic:present name="account_bean" property="error">
<div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
// When DOM is ready
$(function() {
$("#errorDialog").dialog({
title: "Login",
autoOpen: false,
resizable: false,
show: "clip",
hide: "clip",
modal: true,
dialogClass: "ui-state-active"
});
});
// When Window is ready
$(window).load(function() {
$("#errorDialog").dialog("open");
});
</script>
<div id="errorDialog">
<bean:write name="account_bean" property="error" filter="false"/>
</div>
</div>
</logic:present>
Simply try using struts logic tags for your purpose. Here i used jQuery ready() function,
<logic:present name="account_bean" property="error">
<script>
$(document).ready(function() {
alert('Login failed.');
});
</script>
</logic:present>
Hope this helps..
I haven't tried it and I am not even sure if this works. It was too long to be written as a comment.
Create a field in your form bean as follows:
public class MyForm{
String isUserValid;
//its getters and setters
}
And then in your account_actoin.java
if (account_name.equals(acc_name) && account_password.equals(acc_password)) {
//rest of your code
formBean.setIsUserValid("Y")//------------Add this
return mapping.findForward(SUCCESS);
else {
formBean.setIsUserValid("N")//--------And this
return mapping.findForward(FAILURE);
}
In your jsp file add a hidden input and the following script as follows:
<head>
<script type="text/javascript">
$(document).ready(function(){
var isLoggedIn = $("#isUserValid").val();
if(isLoggedIn == "N"){
alert("Log in failed");
}
});
</script>
</head>
<body>
<input type="hidden" id="isUserValid" name="isUserValid" />