** Updated with additional code **
I am redesigning a site for someone and reusing some of the php code from the previous developer. The form submits and does validation server-side on the process page. This is obviously bad from a user experience perspective. I am trying to incorporate jquery validation. I am more of a designer and have limited knowledge on php and moderate jquery.
Its a pretty straight forward form that has 2 submit options at the end. 1 button for paying with a check, 1 for paypal.
The code being used for these buttons is completely bypassing my jquery form validation. If I put a simple submit button the jquery validation kicks.
This is the code for the 2 buttons being used.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$('form').validate();
});
</script>
<form id="lx" class="form-horizontal" action="reg_process.php" method="post" name="regform">
<div class="row mbs">
<label class="control-label col-sm-4" for="firstname"><span class="font-standout">*</span> First Name: </label>
<div class="col-sm-8">
<input type="text" id="firstname" name="FirstName" class="form-control input-lg mrs mls" min="2" required />
</div>
</div>
<a href="javascript:void(0)" onclick="document.regform.Submit.value = 'PayPal'; document.regform.submit()" class="btn btn-primary">
<i class="fa fa-paypal"></i><br/>
Pay with Paypal Online
</a>
<a href="javascript:void(0)" onclick="document.regform.submit()" class="btn btn-primary" >
<i class="fa fa-check"></i><br/>
Pay By Check
</a>
The buttons are simply passing either paypal or null into the form submit process page and then redirecting after that. Is there a way I can make this pass jquery validation and then submit with those values?
You just need to add a rules object for the FirstName field and remove the attributes from the input element.
Also the following doesn't work:
// Uncaught TypeError: Cannot set property 'value' of undefined
document.regform.Submit.value = 'PayPal';
However if it did work there is a corner case, where the user clicks the paypal button but the form does not validate, the user then fixes the validation errors and submits the form with the check button. In this event the form will be submitted with Submit=PayPal.
jQuery(function($) {
var form = $('#lx'), submit = $('input[name=Submit]', form);
form.validate({
rules: {
FirstName: {
required: true,
minlength: 2
}
}
});
// lets keep JavaScript out of the DOM
$('#bypaypal, #bycheck').on('click', function(event) {
var paymentType = event.target.id === 'bypaypal' ? 'PayPal' : '';
submit.val(paymentType);
form.submit();
});
// this is just for demo purposes, you don't need it
form.on('submit', function() {
if (form.valid()) {
alert('Form is valid: Submit="' + submit.val() + '"');
}
});
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.js"></script>
<form id="lx" class="form-horizontal" action="reg_process.php" method="post" name="regform">
<div class="row mbs">
<label class="control-label col-sm-4" for="firstname">
<span class="font-standout">*</span> First Name:
</label>
<div class="col-sm-8">
<input type="text" name="FirstName" class="form-control input-lg mrs mls" />
<input type="hidden" name="Submit" value="" />
</div>
</div>
<a href="javascript:void(0);" id="bypaypal" class="btn btn-primary">
<i class="fa fa-paypal"></i>
<br/>Pay with Paypal Online
</a>
<a href="javascript:void(0);" id="bycheck" class="btn btn-primary">
<i class="fa fa-check"></i>
<br/>Pay By Check
</a>
</form>
Probably what's going on is the inline-javascript is hi-jacking the code and it never makes it to the jQuery validation. So remove it. Also, it's a good idea to add IDs to the a tag submit buttons to easily capture the click event. You also need to suppress the default action of an a tag, so use event.preventDefault (note that you must pass the event param into the .click function)
(1) Remove inline javascript.
(2) Assign IDs to your anchor tags.
(3) Then, use jQuery to test for click event.
working jsFiddle
HTML:
<form id="lx" class="form-horizontal" action="reg_process.php" method="post" name="regform">
<div class="row mbs">
<label class="control-label col-sm-4" for="firstname"><span class="font-standout">*</span> First Name:</label>
<div class="col-sm-8">
<input type="text" id="firstname" name="FirstName" class="form-control input-lg mrs mls" min="2" required />
</div>
</div>
<a id="paypal_submit" href="javascript:void(0)" class="btn btn-primary">
<i class="fa fa-paypal"></i><br/>
Pay with Paypal Online
</a>
<a id="normal_submit" href="javascript:void(0)" class="btn btn-primary">
<i class="fa fa-check"></i><br/>
Pay By Check
</a>
</form>
jQuery:
$('#paypal_submit, #normal_submit').click(function(e){
e.preventDefault; //stop a tag default action
var submit_type = this.id.split('_')[0]; //paypal or normal
var fn = $('#firstname').val();
if (fn=='' || fn.length < 4){
alert('Invalid first name');
$('#firstname').css({'background':'yellow','border':'1px solid orange'}).focus();
return false;
}else{
if (submit_type == 'paypal'){
$('#lx').val('PayPal').submit();
}else{
$('#lx').submit();
}
}
});
If you have multiple fields to check, here is another jsFiddle Demo that shows how to handle that:
http://jsfiddle.net/tyvk15cg/
Related
Is there a way to validate the following checkbox ?
<form name="rmn-form" id="rmn-form" action="send.php" enctype="multipart/form-data" method="POST">
<div class="row">
<div class="col-md-12 col-xs-12">
<div class="rmn-input-field">
<label for="gdpr" class="checkbox-container"> Accept terms and conditions
<input type="checkbox" checked="checked" id="gdpr" name="gdpr">
<span class="checkmark"></span>
</label>
</div>
</div>
</div>
<button type="submit" name="submit" id="submit-all" class="waves-effect waves-light btn submit-button pink mt-30">Send</button>
</form>
The checkbox is generated by https://www.w3schools.com/howto/howto_css_custom_checkbox.asp
I have the following JSFiddle with my code with the bootstrap library and jquery.validate.min.js:
http://jsfiddle.net/2837qdeu/
Just change your input tag to the code below
<input type="checkbox" required="required" id="gdpr" name="gdpr">
It will check before submit that this checkbox must be checked.
Fiddle
You also can take control of this yourself, as below:
$("[name=submit]").click(function(){
if ( $('#gdpr').is(':checked') ){
alert('submit will proceed - checkbox is checked') //This alert not required, only added for demo
}else{
alert('Error - submit will not proceed');
return false; //<== Here is the magic, along with checking that the box is checked
}
});
Revised jsFiddle
return false will stop the submit procedure, allowing you to display a message, or do some js wizardry, before returning control to the user.
I added the following line in the js file and it worked just fine:
$("#rmn-form").validate({
ignore: ':hidden:not(:checkbox)',
....
});
I have an Angular form inside a ng2 popup:
<popup>
Sign up for our Newsletter! <form #f="ngForm" (ngSubmit)="onSubmit()" novalidate>
</button> <input type="email"/>
<button>Submit</button>
</form>
</popup>
<button class="submit" (click)="ClickButton()">Sign up for our Newsletter </button>
here is the onClick event function:
constructor(private popup:Popup) { }
testAlert() { ClickButton(){
alert("Newsletter event works"); this.popup.options = {
widthProsentage: 15,
showButtons: false,
header: "Sign up for our Newsletter!",
}
this.popup.show(this.popup.options);
}
It works fine but I am able to submit her even if the input is blank, how can I make so that it does not submit if it is clicked empty
I tried using RegEx but it did not work
Consider adding validation.
Something like this:
<div class="form-group row">
<label class="col-md-2 col-form-label"
for="userNameId">User Name</label>
<div class="col-md-8">
<input class="form-control"
id="userNameId"
type="text"
placeholder="User Name (required)"
required
(ngModel)="userName"
name="userName"
#userNameVar="ngModel"
[ngClass]="{'is-invalid': (userNameVar.touched || userNameVar.dirty) && !userNameVar.valid }" />
<span class="invalid-feedback">
<span *ngIf="userNameVar.errors?.required">
User name is required.
</span>
</span>
</div>
</div>
You can then disable the submit button if the fields are not valid:
<button class="btn btn-primary"
type="submit"
style="width:80px;margin-right:10px"
[disabled]="!loginForm.valid">
Log In
</button>
(ngSubmit) is built-in event emitter inside of Angular ngForm and is directly related to button element which is kind of a trigger for form submission.
Therefore, as lealceldeiro said, you only need onSubmit function and button intended for submission inside of your form tag.
Please provide live demo so we can see the whole file (.ts particularly).
Setting the validation properly depends on what kind of forms you're going to use (template or ReactiveForms).
See more about proper ngForm usage in official documentation.
I am having a problem with using 'enter button' on the keyboard with an angular js login form. I know this question is asked before but I believe that my problem is a bit different because I tried almost everything written on the stackoverflow questions.
So, I just want to be able to hit enter and submit the form with only using the enter key on keyboard.
Here is login html:
<!-- BEGIN LOGIN FORM -->
<form ng-submit="loginCtrl.login()" class="login-form">
<h3 class="form-title">Sign In</h3>
<div class="alert alert-danger display-hide">
<button class="close" data-close="alert"></button>
<span>
Enter any username and password. </span>
</div>
<div class="form-group">
<!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
<label class="control-label visible-ie8 visible-ie9">Username</label>
<input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="Company/username"
ng-model="loginCtrl.username" name="username"/>
</div>
<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">Password</label>
<input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Password"
ng-model="loginCtrl.password" name="password"/>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-success uppercase" value="Login">
</div>
</form>
<!-- END LOGIN FORM -->
and here is my login:
self.login = function() {
var result = self.username.split("/");
var account = result[0];
var userId = result[1];
UserService.login(userId, self.password,account).then(function(user) {
self.userAccount = user;
$state.go('home');
}, function(err) {
alert("Authentication failure: Please check your credentials. ")
});
I get user name as "companyName/Username" so it is like:
amazon/bigboby
I'm pretty sure your problem is caused by this <button> tag:
<button class="close" data-close="alert"></button>
The answer is found in the documentation:
You can use one of the following two ways to specify what javascript method should be called when a form is submitted:
ngSubmit directive on the form element
ngClick directive on the first button or input field of type submit (input[type=submit])
Note the comment about how it looks for an ng-click handler on the first button. When you are pressing ENTER to submit the form, Angular looks at the form and sees that button. It would execute the ng-click handler on that button (if it had one).
If you include the type attribute on the button, you can prevent that and let it find the actual submit button:
<button type="button" class="close" data-close="alert"></button>
I have an Angular page with a form for adding people, and a button (outside this form) to submit the list of people.
When the user focuses on a text input in the form, and then clicks to submit the list, the validation error from the text input appears but the submit event never occurs.
An example of this issue here: http://plnkr.co/edit/6Z0UUs
<div ng-controller="MyCtrl as vm">
<form name="form1" novalidate="">
<input type="text" name="field1" ng-model="vm.name" required>
<div ng-messages="form1.field1.$error" ng-if="form1.field1.$touched">
<label ng-message="required">Name is required</label>
</div>
<!--
This form adds a person to a list. I've not included this code to keep the example simple
<input type="submit" value="Add person">
-->
</form>
<button ng-click="vm.submit()">Submit list</button>
</div>
-
angular.module('myApp',[])
.controller('MyCtrl', function() {
var vm = this;
vm.name = '';
vm.submit = function () {
alert('submitted');
};
});
To replicate:
Click on the text input but leave blank
Click submit
Current behavior: "Name is required" appears thanks to the validation. Clicking 'Submit' again displays the 'submitted' alert.
Expected behavior: "Name is required" appears thanks to the validation and the 'submitted' alert appears.
Desired behavior: The 'submitted' alert appears and I add some code to vm.submit() to hide the 'Name is required' validation message as it's not important when the list is submitted.
I've observed that removing the ng-messages block fixes the issue, but I do need to show a validation message. Using a more basic directive (ng-show) to show the validation message instead does not help.
Any insights into what I'm doing wrong, or workarounds to achieve my desired behavior, would be great!
[Modified Answer] :
Here is a working plunker : http://plnkr.co/edit/JCyRi8xp4L3FtafABblS?p=preview
vm.preventDefaultIfSubmitted = function($event){
if($event.relatedTarget.id == "submit"){
$event.stopImmediatePropagation();
}
};
The idea is to get the $event when the blur occurs and then to look at the id of the relatedTarget (which is your button in this case) and if it is then you cancel the $event, otherwise you keep it.
That way if you click anywhere your validation message appears and if you click on submit it doesnt
May this help for form validation
<form role="form" name="projectBriefFrm">
<div class="form-group">
<label for="project_title">Project Title
<sup>*</sup>
</label>
<input ng-model="project.title" ng-required="true" type="text" class="form-control" name="title" placeholder="Untitled Project"
/>
<div class="row">
<span class="errorMessage" ng-show="!isProjectModelValid && projectBriefFrm.title.$invalid">Please provide title</span>
</div>
<div class="container" id="editor-title">
<label for="project_brief">Project Brief
<sup>*</sup>
</label>
<div class="row" id="editor">
<div class="col-lg-12 nopadding">
<textarea ng-model="project.brief" name="brief" cult-editor ng-required="true"></textarea>
</div>
</div>
</div>
<div class="row">
<span class="errorMessage" ng-show="!isProjectModelValid && projectBriefFrm.brief.$invalid">Please provide project brief</span>
</div>
</div>
</form>
I have the following form:
<form class="form-horizontal" {{action "formSubmit"}}>
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
As you notice, I have two actions for this form:
When I type on the user input field and press enter, it fires the findUser action
When the form submits, the formSubmit action is called.
Now, here's the problem.
When I type something on the user text field and press enter, it fires the findUser action but also fires the formSubmit. As I know, this is how a form normally behaves. When you press enter on a text field, it submits the form.
Is there a workaround on this behavior? That when I press enter on a the user text field, I want the findUser action to be fired but not submit the form.
Please help.
One workaround is removing form itself. You can have action on button. You may have to sacrifice some form related features but still works very well. Here is the jsbin.
http://emberjs.jsbin.com/nifim/2/edit
There might be some other better way as well.
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser" bubbles=false}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button type="submit" class="btn btn-primary" {{action "formSubmit"}}>Save</button>
and javascript
App.IndexController = Ember.Controller.extend({
actions: {
findUser: function(){
console.log('Find User');
},
formSubmit: function(){
console.log('Form Submit');
}
}
});
Another workaround that allows using the form:
http://emberjs.jsbin.com/povud/1/
Just add 'onkeypress="return event.keyCode != 13;"' to the form element and place the {{action}} on the button itself:
<form class="form-horizontal" onkeypress="return event.keyCode != 13;">
<div class="form-group">
<label>User:</label>
{{input type="text" value=user action="findUser"}}
</div>
<div class="form-group">
<label>Notes:</label>
{{input type="text" value=notes}}
</div>
<button class="btn btn-primary" {{action "formSubmit"}}>Save</button>
</form>