i'm on my web site project and it seems that my jquery function doesn't work
.i have to validate this:if the user enters <<nom de famille du pere>>,<<prenom du pere>> has to be entered too.This is my html code:
<div class="form-group">
<div class="col-md-6">
<label class="col-md-4 control-label" for="father">Nom de famille du père </label>
<input id="father" name="father" type="text" class="form-control input-md" >
</div>
</div><br/><br/><br/>
<div class="form-group">
<div class="col-md-6">
<label class="col-md-4 control-label" for="ffather">Prénom du père</label>
<input id="ffather" name="ffather" type="text" class="form-control input-md">
</div>
</div><br/><br/><br/>
and this is my jquery function :
$(document).ready(function() {
$('#father').submit(function() {
if ($(this)).is(':empty')) {
$('#ffather').prop('required',false);
}
else{
$('#ffather').prop('required',true);
}} }
DEMO: http://jsfiddle.net/Lfnrrdfu/1/
you have a few mistakes in your code:
$('#father').on('keyup', function () {
if (!$(this).val()) {
$('#ffather').prop('required',false);
}
else{
$('#ffather').prop('required',true);
}
console.log($('#ffather').prop('required'));
});
You can't use submit event with an input, submit is for a form, you could use the form but then you have to prevent default then check the value of the input.
You are trying to set the attributes upon form submission, which is not the right way to do it. You should only check if the fields satisfy the requirements on submit. Defining the constrains should be on the markup. If you are not using any custom form validator, you can use HTML constrain validation. Examples can be found here
http://www.w3schools.com/js/js_validation.asp
Again, the jQuery submit event can ONLY be attached to form elements. Review here https://api.jquery.com/submit/
Related
I have been battling with what is wrong on this code since. It so happens that the form is not submitting on this button. The button is of type button and not in the form tag.
$("#step1Btn").click(function () {
var userForm = $("form[name='step1Form']");
if (userForm.valid()) {
userForm.submit(function () {
console.log('submitted o!')
$("#spin1").show();
$("form[name='step1Form'] > span").remove();
$('input[name="emailInput"]').prop('name', "id")
$('input[name="fullNameInput"]').prop('name', "full-name")
$('input[name="phoneInput"]').prop('name', "phone-number")
$.ajax({
type: 'POST',
url: "api/v1/user?" + $(this).serialize(),
success: (result) => {
localStorage.setItem('user', JSON.stringify(result))
localStorage.setItem('authToken', result.authToken);
$("form[name='step1Form'] > span").remove()
$('#step1, #step2').toggle();
$('#step1Title, #step2Title').toggle();
},
error: function (request, exception, errorThrown) {
$("form[name='step1Form'] > span").remove();
$("form[name='step1Form']").prepend('<span class=\'error\'><p>' + request.responseJSON.message + '</p></span>')
},
})
});
} else {
return false;
}
});
Below is the complete form
<div id="step1" class="col-12 col-md-6">
<form name="step1Form">
<div class="home-icon d-flex justify-content-center align-items-center flex-column">
<img src="images/new-icons/user.png" alt="User Registration logo" height="80" />
<p class="my-3">User Registration</p>
</div>
<div class="form-group">
<label for="fullNameInput">Contact full name</label>
<input name="fullNameInput" class="form-control custom-input" placeholder="First name Last name" id="fullNameInput">
</div>
<div class="form-group">
<label for="emailInput">Contact email address</label>
<input name="emailInput" type="email" placeholder="example#email.com" class="form-control custom-input" id="emailInput">
</div>
<div class="form-group">
<label for="confirmEmailInput">Confirm contact email address</label>
<input name="confirmEmailInput" type="email" placeholder="example#email.com" class="form-control custom-input"
id="confirmEmailInput">
</div>
<div class="form-group">
<label for="phone">Contact phone number</label>
<input name="phoneInput" placeholder="08012345678" class="form-control custom-input" id="phone">
</div>
</form>
<button type="button" class="btn red-btn user-btn custom-btn" id="step1Btn">Next<i id="spin1" class="fa fa-spinner fa-spin"></i></button>
</div>
So I would like to see where I went wrong. I am able to log and see output whenever i place a console.log in between the if(userForm.valid) and the userForm.submit().
But as soon as i place it in the userform.submit() I do not get any value back. Like, the form is totally not submitting. I dont know if its because of how I made my Ajax call.. Please Help
You're putting Ajax inside of a submit....
$("#step1Btn").click(function () {
....
if (userForm.valid()) {
userForm.submit(function () {
....
$.ajax({ ....
Which makes no sense since Ajax replaces the actual submit. By doing this you are effectively sending it through validation again; I can't see the .validate() method, but suspect that you are simply using the default option, which would be yet another regular submit... you're probably stuck in a loop going nowhere.
The best place for your Ajax would be inside the submitHandler of the .validate() method.
If your button is outside of the form, you capture the click and manually trigger a submit, which then lets the validation plugin take over the rest.
$("#step1Btn").click(function () { // click of external button
$("form[name='step1Form']").submit(); // trigger validation & submission
});
$("form[name='step1Form']").validate({ // initialize plugin
submitHandler: function(form) { // fires when valid
// YOUR AJAX GOES INSIDE HERE
return false;
},
// other options, rules, etc.
});
Read the documentation for the submitHandler.
I had a input field in my form that have the following class:
class="form-group field-sale-first_name required"
and after client side validation it can have one of two different classes added to it.
class="form-group field-sale-first_name required has-success"
or
class="form-group field-sale-first_name required has-error"
I'm trying to catch when this class has success of error status with jQuery method hasClass() but always getting True even when the .has-error or the has-success are not there.
<form id="checkout-form" action="/site/checkout" method="post">
<div class="form-group field-sale-first_name required">
<input type="text" id="sale-first_name" class="form-control" name="Sale[first_name]" placeholder="First Name">
and the script:
clientValidationStatus = (function() {
if ($("form-group.field-sale-first_name.required").hasClass(".has-success)) {
alert("Success");
}
})();
Could someone give a hint of how to get this change?
Thanks in advance.
You are missing hasClass syntax hasClass("has-success") and for form-group
clientValidationStatus = (function() {
if ($(".form-group.field-sale-first_name.required").hasClass("has-success")) {
alert("Success");
}
})();
I want my input always has value so that focus is fixed to it until the values are typed and the cursor also can't escape the input.
I know the focus() function is existed but how can i deal with it? It is just an event isn't it? Is there any solution?
This is the html code which include the input.
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
This is the script where the input is bound the events.
<script>
jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function(){
if (!$(this).val()) {
var message = "no id";
error(this.id, message); // ** TODO : SET FOCUS HERE !!
} else {
id_form_validation(this.id);
}
});
Could you guys see the **TODO in code above? I want to add function that the focus is fixed until the value is written.
Please could guys give me some idea. Thank you.
=========================================================================
I want to focus my input depends on situation. For example, I want to focus it when the value isn't existed or the validation doesn't correct. However it has to focus out when the value is existed or the validation is true.
I can set focus it finally but how can i unfocus it? I mean i want to untrigger the focus event.
jQuery('#inputID').on('blur',function(){
if (!$(this).val()) {
var message = "아이디를 입력해 주세요";
error(this.id, message);
$(this).focus();
} else {
//$(this).focus();
if (!id_form_validation(this.id)) {
$(this).focus(); // TODO : FOCUS
}else {
$(this).off('focus'); // TODO : FOCUS OUT
$(this).off('blur');
}
}
});
You can use this code to do the same... I have used blur
//jQuery('#inputID').keyup(blank_special_char_validation);
jQuery('#inputID').focusout(function() {
if (!$(this).val()) {
$(this).focus();
var message = "no id";
error(this.id, message);
}else {
id_form_validation(this.id);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-xs-3 vcenter from-group" id="info">
<div class="form-group">
<label class="control-label" for="inputID">아이디</label><p style="display:inline; padding-left:60px; color:red; font-size: 12px">* 적어도 하나의 대문자, 소문자, 숫자를 포함한 6자~16자</p>
<div class="controls">
<input type="text" class="form-control" name="inputID" id="inputID" placeholder="내용을 입력해 주세요" required autofocus>
</div>
</div>
Use $(this).focus() to focus your input.
focus() with no arguments will trigger that event on an element.
I have a form that may only be one page or may be two pages depending on whether it is a single individual or two people applying. What I am doing right now is enabling a link that allows the user to get to the next group of form elements for their co-applicant via an onchange event that shows the link that will slideToggle the first users inputs and show the inputs for the additional users. It's a pretty lengthy form so I cut it down to a few elements so I could fiddle it out:
Das Fiddle is here
<form method="POST" id="refiLoanForm" action="mailto:i#i.com">
<!--START PRIMARY APPLICANT -->
<div id="primary-applicant">
<label>
Application Type
<select name="applicationType" id="applicationType" class="wider" required>
<option value="individual">Individual</option>
<option value="joint">Joint</option>
</select>
</label>
<br>
<label for="loan-amount" id="loan-amount-label">Requested Finance Amount
<input type="text" id="loan-amount" name="loanAmount" required/></label>
<br>
<label for="remaining-term">Current Loan Remaining Term
<input type="text" id="remaining-term" name="remainingTerm" max="3" size="3" required class="override"/>
</label>
<br>
CONTINUE TO CO-APPLICANT
</div>
<!--END PRIMARY APPLICANT -->
<!--START CO_APPLICANT -->
<div id="co-applicant" style="display: none">
Back to Primary Applicant
<br>
<label for="co-first-name">First Name
<input type="text" id="co-first-name" name="coApplicantGivenName" maxlength="32" required/>
</label>
<br>
<label for="co-last-name">Last Name
<input type="text" id="co-last-name" name="coApplicantFamilyName" maxlength="32" required/>
</label>
</div>
JS:
$('#refiLoanForm').validate({
onkeyup: false,
ignore: ":disabled",
submitHandler: function (form) { // for demo
alert('valid form');
return false;
}
});
$("#singleSubmitBtnLoan").bind('click', function () {
$('#refiLoanForm').valid();
});
//Handle the content being shown
$("#singleSubmitBtnLink2").on('click', function () {
$("#primary-applicant").slideToggle("slow");
$("#co-applicant").slideToggle("slow");
});
$("#backToPrimary").on('click', function () {
$("#primary-applicant").slideToggle("slow");
$("#co-applicant").slideToggle("slow");
});
$('#applicationType').on('change', function() {
if ($(this).val() === 'joint') {
$('.primaryApplicantSwitch').slideToggle("slow");
$('.jointApplicantSwitch').slideToggle("slow");
} else {
$('.primaryApplicantSwitch').slideToggle("slow");
$('.jointApplicantSwitch').slideToggle("slow");
}
});
So in theory, the user can enter the fields and hit submit and the form is either valid or throws some errors. Or, the user can add a co-applicant, and validate the form on the link click before toggling to the next group of inputs.
Any ideas on how I would bind all of this to the one button and get it to play nice with jquery.validate?
You cannot dynamically "toggle" the rules of input fields.
However, you can use the .rules() method to dynamically add/change/remove rules, which essentially mimics the behavior of a toggle.
Also, since you're talking about fields that are hidden, you'll need to disable the option that makes validation ignore all hidden fields.
ignore: []
I'm dealing with a standard "change your password" form where you have two fields: password1 and password2. Those two fields are just to validate that the user enter the right password and they need to contain the same text.
I added a directive to validate password but now I want that, if both fields are not equal between each other, make both fields become invalid and not just the one I'm typing in. Can I do that?
I try to call the $setValidity on both ngmodels but I'm not finding the way to call from one ctrl.$parsers.unshift or directive link function the $setValidity or the other field I'm not currently validating. I'm really lost..
Thanks a lot!
My directive is:
myApp.directive('validatepassword', function () {
return {
require: 'ngModel',
restrict: 'A', // only activate on element attribute
link: function (scope, elm, attrs, ngModel) {
ngModel.$parsers.unshift(function (viewValue) {
var valPasswordValue = attrs.validatepassword;
var otherPassword = $('#' + valPasswordValue)[0].value;
var valido = scope.validatePassword(viewValue, otherPassword);
ngModel.$setValidity('password', valido);
return viewValue;
});
}
};
});
and I'm using in this way in the code:
<div class="control-group">
<label class="control-label" for="inputPassword1">Password</label>
<div class="controls">
<input id="inputPassword1" name="inputPassword1" type="password" ng-model="context.Password" required validatepassword="inputPassword2"/>
<span class="alert-danger invalid-form" ng-show="!addEditForm.inputPassword1.$valid">(*)</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword2">Repeat Password</label>
<div class="controls">
<input id="inputPassword2" name="inputPassword2" type="password" ng-model="context.Password2" required validatepassword="inputPassword1"/>
<span class="alert-danger invalid-form" ng-show="!addEditForm.inputPassword2.$valid">(*)</span>
</div>
</div>
Any ideas about how can I validate both fields as soon as one of them change?
Thanks a lot!
To trigger the validation method from one field in another field I had to manually set the value of the other field. You can do that inside of a ng-change:
ng-change="addEditForm.inputPassword2.$setViewValue(addEditForm.inputPassword2.$viewValue)"
When you do that it should trigger the validation in both password fields.
You could also access the fields inside of your directive like so:
scope.addEditForm.inputPassword1
So you could get rid of the jQuery access inside of your directive.
Here is the HTML-partial that worked for password validation on both fields:
<div class="control-group">
<label class="control-label" for="inputPassword1">Password</label>
<div class="controls">
<input id="inputPassword1" name="inputPassword1" type="password" ng-model="context.Password" required
validatepassword="inputPassword2" ng-change="addEditForm.inputPassword2.$setViewValue(addEditForm.inputPassword2.$viewValue)"/>
<span class="alert-danger invalid-form" ng-show="!addEditForm.inputPassword1.$valid">(*)</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword2">Repeat Password</label>
<div class="controls">
<input id="inputPassword2" name="inputPassword2" type="password" ng-model="context.Password2" required
validatepassword="inputPassword1" ng-change="addEditForm.inputPassword1.$setViewValue(addEditForm.inputPassword1.$viewValue)"/>
<span class="alert-danger invalid-form" ng-show="!addEditForm.inputPassword2.$valid">(*)</span>
</div>
</div>
Angular-UI has a built-in validator which you can use in various purpose, there is a exact example of password and confirm password which you can check:
https://github.com/angular-ui/ui-utils/blob/master/modules/validate/demo/index.html#L29
Please check this fiddle
http://jsfiddle.net/vigneshvdm/Dnt7w/5/
you can do something like this
var password=$("#telephone").val();
var reenteredpassword=$("#mobile").val();
if(password==reenteredpassword)
{
$("#required").html("Passwords Match");
}
else
{
$("#required").html("Passwords do not Match");
}