This question already has an answer here:
AngularJS update input manually does not trigger change in the model
(1 answer)
Closed 3 years ago.
Here is the following code;
<div class="col-xs-12 col-sm-9">
<input id="Shipping_FirstName" name="firstname" ng-model="userOrder.Shipping.FirstName" type="text" class="form-control nsg-form--input ng-pristine ng-untouched ng-invalid ng-invalid-required ng-valid-maxlength" ng-class="{'is-invalid': shipping_subform.$submitted && shipping_subform.firstname.$invalid}" required="" maxlength="35" tooltip="Please enter your first name" tooltip-toggle="shipping_subform.$submitted===true && shipping_subform.firstname.$invalid===true" esw-google-analytics-blur=""> <!-- ngIf: shipping_subform.$submitted && shipping_subform.firstname.$invalid -->
</div>
I have tried the following which writes the text to the input field;
document.getElementById("Shipping_FirstName").value = "test"
document.querySelector("input[id='Shipping_FirstName']").value = "test";
However, when I press the submit button, it says "Please enter your first name" as if the code above actually didn't write the text.
How can I fix this?
Thanks for any help, it's all appreciated.
Thanks to epascarello, the answer is;
var e = document.getElementById("Shipping_FirstName");
e.value = "test";
var $e = angular.element(e);
$e.triggerHandler('input');
Related
I am working on a reactive form in angular. Facing this problem where a field that is not required should have some validations when it is dirty or touched but as soon as the user is out of this textbox/field, the validation message should just go away. I have tried using ng-invalid but it is not working as the field when loaded for the first time is having ng-invalid class. The following is the code -
<div class="form-group">
<label>Street Name</label>
<input type="text" class="form-control" formControlName="streetName">
<span class="text-danger"
*ngIf="registerForm.get('streetName').touched || registerFormControl.get('streetName').dirty" class="Required">
<span *ngIf="registerForm.get('streetName').error?.pattern || registerForm.get('streetName').error?.minLength">
Pattern & Minlength error
</span>
<span class="text-danger"
*ngIf="registerForm.get('streetName').error?.monthError || registerForm.get('streetName').error?.otherError">
Month and Other Error
</span>
</span>
</div>
FormGroup Validation -
streetName:['',{
Validators: [
Validators.pattern(0-9),
Validators.minLength(9),
this.customValidations.streetValid
],
updateOn: 'blur'
}]
How do I get this validation dissappear?
You can use the focus and blur events to track if and when a user is in an input field or not.
<input (focus)="onFocus()" (blur)="onBlur()">
In this code example onFocus() is called when the user clicks/is-in the input box. onBlur() is called when the user clicks out of the input box.
We can use this to better distinguish if we should display the error message or not.
Let's say you have two inputs: Street Name and Street Address. We will create an onFocus() function that handles which item is focused and an onBlur() function that will clear the focused selection.
// Class variables
public selectedField = "";
function onFocus(identifier : string) {
selectedField = identifier; // set the field
}
function onBlur() {
selectedField = ""; // clear the field
}
Now, on our inputs:
<input (focus)="onFocus('streetName')" (blur)="onBlur()" type="text" class="form-control" formControlName="streetName">
<input (focus)="onFocus('streetAddress')" (blur)="onBlur()" type="text" class="form-control" formControlName="streetAddress">
Finally, we can handle if we should display the error message or not. All we need to do is add one more condition to the *ngIf of the error span.
<!--Example Street Name Error Span -->
<span class="text-danger" *ngIf="selectedField == 'streetName' && . . . ">
Invalid Street Name
</span
<!--Example Street Address Error Span -->
<span class="text-danger" *ngIf="selectedField == 'streetAddress' && . . . ">
Invalid Street Address
</span
If you'd like a better understanding on how focus works, you can find it here.
This question already has answers here:
Angular 5 FormGroup reset doesn't reset validators
(14 answers)
Closed 3 years ago.
I am new in angular 6 and working on a angular project.I am facing a problem while reset the form after submission of the form.Here is code:
<form [formGroup]="commentForm">
<div class="col-md-8 " [ngClass]="{ 'is-invalid': submitted && f.comment.errors }">
<textarea class="form-control" [(ngModel)]="commentsData.comment" [ngClass]="{ 'is-invalid': submitted && f.comment.errors }" formControlName="comment" placeholder="Add a Comment..." rows="5" cols="8"> </textarea>
</div>
</form>
in components.ts file i am using this for reset the form
this.commentForm.reset();
Form values are cleared successfully,but only problem is after reset form field border is in red color. I am trying
this.commentForm.markAsPristine();
But nothing helps
You can setErrors to null for your form after reset.
for( let i in this.commentForm.controls ) {
this.commentForm.controls[i].setErrors(null);
}
This question already has an answer here:
Why doesn't my equality comparison using = (a single equals) work correctly? [duplicate]
(1 answer)
Closed 5 years ago.
I'm trying to build a form that will check (live) to see whether a person has mismatched a string when entered into text fields. The practice is a user entering data into a password form.
HTML Below:
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" value="" placeholder="Password" onKeyUp="checkPasswordStrength();">
</div>
<div class="form-group">
<input type="password" name="vPass" id="cpassword" class="form-control" value="" placeholder="Password">
<span id="output"></span>
</div>
And below is the jQuery used:
<script type ="text/javascript">
$("#cpassword").blur(function checkPassMatch(){
var originEmpt = $("#password").text(""); // Checking if input is empty
var origin = $("#password").text(); // Password
var conf = $("#cpassword").text(); // Confirm password
if (origin != conf){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Whoops, your passwords don't match!</div>"); //Styling from bootstrap
} else {
$("#output").html("");
}
if (originEmpt){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Please enter a password!</div>");
} else{
$("#output").html("");
}
})
</script>
Through debugging, if I totally remove the first if else statement from the jQuery, I can receive the $("output").html(); as desired.
I have tried for both input fields:
$("#password").text() / .val(); / .html(); / .innerHTML();
But the code still fails to check whether one input field matches another. Any ideas why?
Cause your second checks output overrides the first one. You need to nest it:
if (origin != conf){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Whoops, your passwords don't match!</div>"); //Styling from bootstrap
} else if (!originEmpt){
$("#output").html("<br /><div class=\"alert alert-danger\" role=\"alert\">Please enter a password!</div>");
} else{
$("#output").html("");
}
helo guys I am writing ajava Script that have an input box to allow the user enter a value and I want to show him again what he enterd with in that page to ensure that he will see what he is enterd for example
<input id="userName" class="form-control col-md-7 col-xs-12" type="text" name="userName">
I have these input box and I want get this value and display it again in alabel bellow
<label id="user_label" class="control-label col-md-3 col-sm-3 col-xs-12"></label>
and I write the following JS
user_Name=getElementById('userName');
document.getElementById('user_label').innerHTML=user_Name;
and these displays the string userName not the string value init what can I do
Just grab the value from the HTML element instead...
var user_Name = document.getElementById('userName').value;
document.getElementById('user_label').innerHTML = user_Name;
What you need to do is call your code whenever the input field is changed.
<input id="userName" type="text" name="userName" onKeyUp="update()">
And in JS:
function update() {
var user_Name=document.getElementById('userName').value;
document.getElementById('user_label').innerHTML=user_Name;
}
Also you need to refer to the .value of the input element to get its value.
Here is a Pen:
http://codepen.io/calvinclaus/pen/EKBvBz?editors=1011
Try:
var user_Name=getElementById('userName');
document.getElementById('user_label').innerHTML=user_Name.value;
I am using jQuery Mobile and am attempting to use HTML5 form field validation to perform inline form field validation. I am doing this because I really like the way that the browser reports issues in the bubble and I don't think it is very user friendly to wait until someone has completed filling out a form and then tell them what is wrong. Here is my HTML:
<form id="frmMain" action="#">
<input type="checkbox" data-enhance="false" value="1" id="cbxFB" />
<label for="cbxFB">
<span class="formsubtext">Check this box to use Facebook information to help fill out this registration. Once registered you will be able to use the Facebook login button.</span>
</label>
<label for="tbEmail">*Email</label><input type="email" id="tbEmail" required autofocus placeholder="example#address.com" />
<label for="tbPassword">*Password</label><input type="password" id="tbPassword" required />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">Minimum of 6 characters, one capital character, and one lower case character.</div>
<label for="tbPasswordConfirm">*Password Confirm</label><input type="password" id="tbPasswordConfirm" required />
<label for="tbPin">*Account Pin</label><input type="password" pattern="[0-9]{4}" id="tbPin" required placeholder="####" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:10px">A four digit number that you will remember. This value will be needed to perform sensitive tasks within the application.</div>
<label for="tbFName">*First Name</label><input type="text" id="tbFName" required />
<label for="tbLName">*Last Name</label><input type="text" id="tbLName" required />
<label for="tbPhone">Phone Number</label><input type="tel" id="tbPhone" pattern="\d{3}[\-]\d{3}[\-]\d{4}" placeholder="###-###-####" style="margin-bottom:1px; padding-bottom:0px;" />
<div class="formsubtext" style="margin-top:1px; padding-top:0px; margin-bottom:20px;">Used at your option when you schedule an appointment with a service provider</div>
<div style="display:none;"><label for="tbfbID">Facebook ID</label><input type="text" id="tbfbID" /></div>
<input type="submit" id="btnMainNext" data-icon="arrow-r" data-iconpos="right" value="Next" data-theme="c" class="ui-btn-c ui-btn ui-corner-all" />
</form>
For the confirm password form field I have the following event defined:
$("#tbPasswordConfirm").on("change", function (event) {
var password = $("#tbPassword").val();
var passwordconfirm = $("#tbPasswordConfirm").val();
if (password != passwordconfirm) {
$("#tbPasswordConfirm")[0].setCustomValidity("The value entered does not match the previous password entered.");
$("#btnMainNext").click();
}
else {
$("#tbPasswordConfirm")[0].setCustomValidity("");
}
$(this).focus().select();
})
My problem is that when the user enters something into the field and moves to the next field the HTML form validation shows the error message for the next field (which is required). I want it to show the message for the field they just left. How do I stop the focus from moving to the next field so that the bubble message that shows up is from the field they just entered the data into? As you can see I have tried setting the focus but that does not work. Any help would be greatly appreciated.
You can stop focus from moving to the next field but you can't trigger native validation UI or error message unless you click submit button.
To stop focus from moving next field, after you set the custom validity on the field, you can use:
$('#tbPasswordConfirm').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The blur() function will check the validity on blur and if it would be invalid, the corresponding function in bind() would set the focus back to that element.
Solved it
Fiddle
$(function() {
$("#tbPasswordConfirm").on("input", function(event) {
var thisField = $("#tbPasswordConfirm")[0],
theForm = $("#frmMain")[0],
password = $("#tbPassword").val(),
passwordconfirm = $(this).val(),
custom = password === passwordconfirm ? "" : "The value entered does not match the previous password entered.";
thisField.setCustomValidity(custom);
if (!theForm.checkValidity()) theForm.reportValidity();
});
});
You can use html tabindex attr to manipulate which element will get the focus when you click tab character. See docs to how to use it.
For example, if you make your password confirm input as tabindex="5", you can add tabindex="6" to the <label for="tbPin"> element to prevent next input from focusing right after.