I am trying to disable the form Submit button until the required fields are filled. However my code does not seem to be looping properly through the condition as any input enables the submit button. https://codepen.io/ldanneman/pen/MWyGJMx?editors=0010
<form>
<div class="form-box">
<label for="fname">First Name<span>*</span></label>
<input type="text" id="fname" name="First Name" placeholder="First Name" required><br>
<label for="lname">Last Name</label>
<input type="text" id="lname" name="Last Name" placeholder="Last Name"><br>
<label for="email">Email<span>*</span></label>
<input type="email" id="email" name="Email" placeholder="abc#client.com" required><br>
<label for="phone">Phone<span>*</span></label>
<input type="tel" id="phone" name="Phone" placeholder="111-222-3333" required><br>
<label for="comments">Comments<span>*</span></label>
<textarea id="comments" name="comments" placeholder="Comments" required></textarea><br>
<button class="submit" type="submit">Submit</button>
</div>
</form>
</div>
JavaScript:
let requiredInputs = document.querySelectorAll("[required]");
let submitButton = document.querySelector(".submit");
submitButton.disabled = true;
for(let i = 0; i < requiredInputs.length; i++){
requiredInputs[i].addEventListener("input", buttonState)
};
function buttonState() {
if (requiredInputs.value === "") {
submitButton.disabled = true;
} else {
submitButton.disabled = false;
}
}
You're close, but the code in your callback, buttonState() is insufficient to accomplish what you want. It is checking for the value of requiredInputs which is a collection of HTML Input elements. What you want to do is loop through each item in that collection and check if their value is set:
function buttonState() {
submitButton.disabled = Array.from(requiredInputs).some(x => x.value === '');
}
The code above will use some() which will returns true if any callback results in true, in the case if the value of an input is an empty string.
Related
I have some inputs in the following div
cy.get("div[data-test-letterinputcontainer='0']")
One of them have a value, but it is not known which. It could for example look like this
<div data-test-letterinputcontainer="0">
<input value="" type="text">
<input value="" type="text">
<input value="f" type="text">
<input value="" type="text">
<input value="" type="text">
<input value="" type="text">
</div>
or this
<div data-test-letterinputcontainer="0">
<input value="g" type="text">
<input value="" type="text">
<input value="" type="text">
<input value="" type="text">
<input value="" type="text">
<input value="" type="text">
</div>
How can I check that
One input has a value
The other input's are empty?
Apply a filter to the inputs
cy.get("div[data-test-letterinputcontainer='0']")
.find('input')
.should('have.length', 6)
.filter('input[value=""]') // how many empty?
.should('have.length', 5)
Or conversely
cy.get("div[data-test-letterinputcontainer='0']")
.find('input')
.should('have.length', 6)
.filter('input[value!=""]') // how many not empty?
.should('have.length', 1)
This should do the trick
cy.get("div[data-test-letterinputcontainer='0'] input")
.then(($ele) => {
let flag = false;
for (let i = 0; i < $ele.length; i++) {
if (Cypress.$($ele[i]).val().toString().length) {
//in case we found another input with a value.
if (flag) {
return false;
}
//first time finding a value for input.
flag = true;
}
}
return flag;
})
.should('eq', true);
To check one input has a value
cy.get("[data-test-letterinputcontainer=0]")
.should("be.visible")
.find("[value=f]")
.its("length")
.should("eq", 1);
To check rest of inputs do not have a value:
cy.get("[data-test-letterinputcontainer=0]")
.children()
.its("length")
.then((length) => {
cy.get("[data-test-letterinputcontainer=0]")
.find("[value='']")
.its("length")
.should("eq", length - 1);
});
Here is an example.
i have a form which contains a select option and a div section depends on the selected option. in the select option if i choose 1 for exemple , an input will be displayed
component.ts
types : any[] = [
{ value : '1'},
{ value : '2'},
{ value : '3'}
];
createForm = this.fb.group({
firstInput:['',Validators.required],
secondInput:['',Validators.required],
thirdInput:['',Validators.required],
});
component.html
<select class="form-control" [value]="selected"[(ngModel)]="selectedValue">
<option *ngFor="let x of types">{{x.value}}</option>
</select>
<div *ngIf="selectedValue == '1'">
<label for="1" class="control-label">1</label>
<input id="1" class="form-control" type="text" formControlName="firstInput">
</div>
<div *ngIf="selectedValue == '2'">
<label for="2" class="control-label">2</label>
<input id="2" class="form-control" type="text" formControlName="secondInput">
</div>
<div *ngIf="selectedValue == '3'">
<label for="3" class="control-label">3</label>
<input id="3" class="form-control" type="text" formControlName="thirdInput">
</div>
all the fields are required, my problem is : when i choose "1" for exemple without filling the input of "1" then i change for the second choice "2" and fill it, i can't submit the form because the fielControllName "firstInput" is empty despite being invisible, so i need to clear the selected value of ngModel ( as i think ) with each change.
So Initially your form must be like:
createForm = this.fb.group({
selectedValue:[null,Validators.required],
firstInput:[null],
secondInput:[null],
thirdInput:[null],
});
Your HTML code:
<form [formGroup]="createForm">
<select class="form-control" formControlName="selectedValue">
<option *ngFor="let x of types" value="{{x.value}}">{{x.value}}</option>
</select>
<div *ngIf="createForm.value.selectedValue== '1'">
<label for="1" class="control-label">1</label>
<input id="1" class="form-control" type="text" formControlName="firstInput">
</div>
<div *ngIf="createForm.value.selectedValue== '2'">
<label for="2" class="control-label">2</label>
<input id="2" class="form-control" type="text" formControlName="secondInput">
</div>
<div *ngIf="createForm.value.selectedValue== '3'">
<label for="3" class="control-label">3</label>
<input id="3" class="form-control" type="text" formControlName="thirdInput">
</div>
</form>
Then you must have on change Function:
OnChange() {
this.createForm.get('selectedValue').valueChanges.subscribe(
val => {
if (val==1) {
this.createForm.get('firstInput').setValidators([Validators.required]);
this.createForm.controls['firstInput'].updateValueAndValidity();
this.createForm.get('secondInput').setValidators([]);
this.createForm.controls['secondInput'].updateValueAndValidity();
this.createForm.get('thirdInput').setValidators([]);
this.createForm.controls['thirdInput'].updateValueAndValidity();
}
else if (val==2) {
this.createForm.get('firstInput').setValidators([]);
this.createForm.controls['firstInput'].updateValueAndValidity();
this.createForm.get('secondInput').setValidators([Validators.required]);
this.createForm.controls['secondInput'].updateValueAndValidity();
this.createForm.get('thirdInput').setValidators([]);
this.createForm.controls['thirdInput'].updateValueAndValidity();
}
else if (val==3) {
this.createForm.get('firstInput').setValidators([]);
this.createForm.controls['firstInput'].updateValueAndValidity();
this.createForm.get('secondInput').setValidators([]);
this.createForm.controls['secondInput'].updateValueAndValidity();
this.createForm.get('thirdInput').setValidators([Validators.required]);
this.createForm.controls['thirdInput'].updateValueAndValidity();
}
}
)
}
if you want to make value null you can use:
this.createForm.patchValue({
firstInput:null,
secondInput:null,
thirdInput:null,
})
<input type="email" class="form-control" id="email" placeholder="Enter
email" name="email" onblur="validation()">
<input type="text" name="war-email" id="war-email" value=""
class="error" readonly hidden/><br>
<input type="password" class="form-control" id="pwd"
placeholder="Enter password" name="pwd" onblur="validation()">
<input type="text" name="war-pas" id="war-pas" value="" class="error"
readonly hidden/><br>
<input type="cpassword" class="form-control" id="cpwd"
placeholder="Enter password" name="cpwd" onblur="validation()">
<input type="text" name="war-cpas" id="war-cpas" value=""
class="error" readonly hidden/><br>
<script>
function validation(){
if(document.getElementById("email").value==""){
$("#war-email").show();
document.getElementById("war-email").value="this is invalid email";
document.getElementById("war-email").style.color="red";
}else{
document.getElementById("war-email").value="this is valid email";
document.getElementById("war-email").style.color="green";
}
if(document.getElementById("pwd").value==""){
$("#war-pas").show();
document.getElementById("war-pass").value="Short password";
document.getElementById("war-pas").style.color="red";
}else{
document.getElementById("war-pas").value="Strong password";
document.getElementById("war-pas").style.color="green";
}
var len=document.getElementById("cpwd").value;
if(document.getElementById("pwd").value!=
document.getElementById("cpwd").value==)
{
$("#war-cpas").show();
document.getElementById("war-cpass").value="Both password should
matched";
document.getElementById("war-cpas").style.color="red";
}else{
document.getElementById("war-cpas").value="matched..!!";
document.getElementById("war-cpas").style.color="green";
}
}
</script>
First of all, put your code in a snippet so it will be easier for us to understand. Anyway, I'll tell how to attach blur event using jQuery.
$("input#name").on("blur", function()
{
if(!this.value)
{
alert("Please fill out the name");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="myForm">
<label>Your Name</label>
<input type="text" id="name">
</form>
If you need any other help, just let me know :-)
i just created a scenario , the thing i wanted, can you check out this fiddle jsfiddle.net/5PRMe/393. i want to validate this, some piece of code i used here, but comment it.kindly check this.
Bascially i am follow this link https://github.com/knockout/knockout/wiki/View-Add-Edit-Delete-Design-Pattern (full code of this link is at the bottom of the page), to create my code, but i want knockout validation, with proper messages, but i did't understand how to do validation if we have with binding with computedObservable, can anyone help me to sort out the problem?
var baseModel = function () {
this.id = ko.observable(0);
this.name = ko.observable("").extend({ required: true });
this.title = ko.observable(undefined).extend({
required: { message: "You must select title" },
});
this.email = ko.observable("").extend({ required: true });
this.phone = ko.observable("").extend({ required: true });
this.mobile = ko.observable('');
this.streetAddress = ko.observable('');
this.city = ko.observable('');
this.state = ko.observable('');
this.zipCode = ko.observable('');
this.fax = ko.observable('');
this.description = ko.observable('');
this.editSelectedItemErrors = ko.validation.group([this.name,this.accountId,this.title,this.gender,this.email,this.phone,this.country]);
}
var viewModel = function () {
var self = this;
self.editSelectedItem = ko.observableArray('');
var mappedItems = ko.mapping.fromJS(new baseModel());
self.editSelectedItem(mappedItems);
self.saveContact = function (form) {
if (baseModel.editSelectedItemErrors().length === 0) {
// save data
}
else{
baseModel.editSelectedItemErrors.showAllMessages();
}
}
self.SelectedRecord = ko.computed(function () {
var selected = self.editSelectedItem();
selected.selectedOption;
//selected.selectLanguage;
selected.streetAddress;
var result = (selected);
console.log(result.length);
if (result != null) {
result = ko.toJS(result);
var observable = ko.mapping.toJS(result);
//console.log(observable);
return observable;
} else {
return new baseModel();
};
}, self);
}
var contactModel = new viewModel();
$(function () {
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null,
decorateElement: true,
grouping: { deep: true, observable: true, live: true }
}, true);
ko.applyBindings(contactModel);
});
<div id="divContact" class="flt w100 space form" data-bind="with : SelectedRecord()">#*<!-- ko with : SelectedRecord -->*#
<div class="row">
<label>
First Name</label>
<span>
<input id="Name" name="Name" type="text" data-bind="value : name,uniqueName: true" class="field required" placeholder="Name" />
</span>
</div>
<div class="row">
Email</label>
<span>
<input id="Email" type="text" data-bind="value : email,uniqueName: true" class="required field" placeholder="Email" /></span>
</div>
<div class="row">
<label>
Phone</label>
<span>
<input id="Phone" type="text" data-bind="value : phone,uniqueName: true" class="field" placeholder="Phone" /></span>
<label>
Mobile</label>
<span>
<input id="Mobile" type="text" data-bind="value : mobile,uniqueName: true" class="field" placeholder="Mobile" /></span>
</div>
<div class="row">
<label>
Street Adress</label>
<span>
<input id="Street" type="text" data-bind="value : streetAddress,uniqueName: true" class="field" placeholder="Street" /></span>
<label>
City</label>
<span>
<input id="City" type="text" data-bind="value : city,uniqueName: true" class="field" placeholder="City" /></span>
</div>
<div class="row">
<label>
State</label>
<span>
<input id="State" type="text" data-bind="value : state,uniqueName: true" class="field" placeholder="State" /></span>
<label>
Zip Code</label>
<span>
<input id="Zip" type="text" data-bind="value : zipCode,uniqueName: true" class="field" placeholder="Zip Code" /></span>
</div>
<div class="row">
Fax</label>
<span>
<input id="Fax" type="text" data-bind="value : fax,uniqueName: true" class="field" placeholder="Fax" /></span>
</div>
<div class="row">
<label>
Description</label>
<span>
<textarea class="input-field " data-bind="value: description,uniqueName: true"></textarea></span>
</div>
<div class="row">
<input data-bind="click: function() { contactModel.saveContact($data,0);}" type="submit" value="Save" class="btn"/>
<input type="button" class="btn" value="Cancel" data-bind="click: function() { contactModel.cancelCreate($data,0);}">
</div>
Hi I've a page with two textboxes and I wanted to apply required validator to both controls. But when I run my code it is applying to only first control. Even though I've given both text boxes as blank, it is showing first text box as required.
Here is my code and not getting where do I missed the second one.
<input type="text" name="firstname" id="firstname" required validationmessage="First name required" />
<input type="text" name="lastname" id="lastname" required validationmessage="Last name required" />
<button class="k-button" id="btnAdd" onclick="addDetails();">Add</button>
function addDetails() {
var validator = $("#btnAdd").kendoValidator().data("kendoValidator");
if (validator.validate()) {
// Add details to db
}
}
Kendo Validator has to be applied to the input that you are validating not to the button. The HTML should be something like:
<div id="my-form">
<div>
<label>
Firstname:
<input type="text" name="firstname" id="firstname" required validationmessage="First name required"/>
</label>
</div>
<div>
<label>
Lastname :
<input type="text" name="lastname" id="lastname" required validationmessage="Last name required"/>
</label>
</div>
</div>
<button class="k-button" id="btnAdd">Add</button>
And the validation function:
$(document).ready(function () {
var validator = $("#my-form").kendoValidator().data("kendoValidator");
$("#btnAdd").on("click", function () {
if (validator.validate()) {
// Add details to db
console.log("good");
} else {
console.log("bad");
}
});
});