parsley.js with jquery-chosen errorsClass not applied - jquery-chosen

I'm struggling to work out why parsley.js won't add the errorClass I've defined to fields enhanced with chosen (https://harvesthq.github.io/chosen/)
I've created this fiddle which shows the issue I have. There are 2 identical select lists - one enhanced with chosen and the other standard.
When you click the submit button, both fields are validated but only the standard select has the 'has-error' class applied to its parent 'input-group' div.
Any ideas? I'd like to get these two great plugins playing together.
Code follows:
<form id="myForm">
<div class="input-group">
<select class="select" name="a[]" multiple="multiple" data-parsley-required data-parsley-mincheck="2">
<optgroup label="Section">
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
</optgroup>
<optgroup label="Section">
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
</optgroup>
</select>
</div>
<div class="input-group">
<select name="b[]" multiple="multiple" data-parsley-required data-parsley-mincheck="2">
<optgroup label="Section">
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
</optgroup>
<optgroup label="Section">
<option>Drop Down Option A</option>
<option>Drop Down Option B</option>
</optgroup>
</select>
</div>
<input type="submit" />
</form>
$(document).ready(function() {
window.ParsleyConfig = {
errorClass: 'has-error',
successClass: 'has-success',
classHandler: function(ParsleyField) {
return ParsleyField.$element.parents('.input-group');
},
errorsContainer: function(ParsleyField) {
return ParsleyField.$element.parents('.input-group');
},
errorsWrapper: '<span class="error-block">',
errorTemplate: '<div></div>'
};
$(".select").chosen();
$("#myForm").parsley();
$("#myForm").on('submit', function(e) {
var f = $(this);
f.parsley().validate();
if (f.parsley().isValid()) {
alert('The form is valid');
} else {
alert('There are validation errors');
}
e.preventDefault();
});
});
.has-error {
background-color: #ff0000;
}

ok, the solution was simple!
The change is to the return from classHandler and errorsContainer - use parent (singular) instead of parents (plural)
change the config js to....
window.ParsleyConfig = {
errorClass: 'has-error',
successClass: 'has-success',
classHandler: function(ParsleyField) {
return ParsleyField.$element.parent('.input-group');
},
errorsContainer: function(ParsleyField) {
return ParsleyField.$element.parent('.input-group');
},
errorsWrapper: '<span class="error-block">',
errorTemplate: '<div></div>'
};

Related

can't submit form select option Vuelidate

I'm using Vuelidate version 0.7.6, for form validation, i have a selected option to validate it with submit form, if a chose a validate option or a null option i have error i wrote the same code for input text it works, but for select no:
<div class="col-md-4">
<label for="exampleFormControlS1">Famille:</label>
<select
class="form-control form-control-sm mt-2"
id="exampleFormControlSelect1"
name="family"
v-model="familyId"
#change="onChange($event)"
:class="{
'is-invalid': $v.family.$error,
'is-valid': !$v.family.$invalid,
}"
><option value="null">- -- -</option>
<option
v-for="lineItem in familyListe"
:key="lineItem.id"
:value="lineItem.id"
>
{{ lineItem.name }}</option
>
</select>
<div class="invalid-feedback">
<span v-if="!$v.family.required">Famille requise</span>
</div>
</div>
validations: {
family: {
required,
},
}
I guess you should change v-model to "family" instead of "familyId" to validate your field correctly.
<select
class="form-control form-control-sm mt-2"
id="exampleFormControlSelect1"
name="family"
v-model="family"
#change="onChange($event)"
:class="{
'is-invalid': $v.family.$error,
'is-valid': !$v.family.$invalid,
}"
>...
onChange method according to Vuelidate Docs: Form submission
methods: {
onChange() {
console.log("onChange!");
if (this.$v.$invalid) {
this.submitStatus = "ERROR";
} else {
this.submitStatus = "OK";
}
}
}
Check the following CodeSandbox for details:
https://codesandbox.io/s/stackoverflow-69434609-vuelidate-t11qy?file=/package.json

Angular 2 Template Driven Forms - Array Input Elements

I have been struggling for 1 and half day and still couldn't find any solution to the problem. I am working on simple form which has select and checkboxes element.When I try submitting the form I do not get the values of select and checkboxes but rather I just get true in the console.
I am working on template driven form.
<form (ngSubmit)="addSubcontractor(subcontractorForm)" #subcontractorForm="ngForm">
<h5>Type :</h5>
<div class="form-group">
<div *ngFor="let contractor_type of contractor_types;let i = index;" class="pull-left margin-right">
<label htmlFor="{{ contractor_type | lowercase }}">
{{ contractor_type }} :
</label>
<input type="checkbox" name="_contractor_type[{{i}}]" [value]="contractor_type" ngModel>
</div>
<div class="form-group">
<select class="form-control costcodelist" name="_cc_id[]" multiple="true" ngModel>
//When I put ngModel on select I just keep getting error
//TypeError: values.map is not a function
<option *ngFor="let costcode of costcodes" [selected]="costcode.id == -1" [value]="costcode.id">{{ costcode.costcode_description }}</option>
</select>
</div>
</form>
Component Section
export class SubcontractorComponent implements OnInit, OnDestroy {
private contractor_types = ['Subcontractor', 'Supplier', 'Bank', 'Utility'];
constructor(private costcodeService: CostcodeService,
private subcontractorService: SubcontractorService) {
this.subcontractorService.initializeServices();
}
ngOnInit() {
this.costcode_subscription = this.costcodeService.getAll()
.subscribe(
(costcodes) => {
this.costcodes = costcodes;
});
}
addSubcontractor(form: NgForm) {
console.log(form.value);
}
}
When I remove ngModel from select element the code runs fine and When I submit the form I get the following output.
_contractor_type[0]:true
_contractor_type[1]:true
_contractor_type[2]:true
_contractor_type[3]:""
I do not get the checkboxes values as well the selected options from select element.
Your comments and answer will appreciated a lot.
Thanks
Here is a simple selection that i use with my Template driven form.
<form #f="ngForm" (submit)="addOperator(f.valid)" novalidate>
<label>Name</label>
<input [(ngModel)]="operator.name" name="name">
<label >Service</label>
<select #service="ngModel" name="service" [(ngModel)]="operator.service">
<option *ngFor='let service of services' [ngValue]='service'>{{service.name}}</option>
</select>
<label >Enabled</label>
<label>
<input type="checkbox" name="enabled" [(ngModel)]="operator.enabled">
</label>
<button type="submit">Create Operator</button>
</form>
.ts
operator: Operator;
ngOnInit() {
this.operator = <Operator>{}; // // Initialize empty object, type assertion, with this we loose type safety
}
addOperator(isValid: boolean) {
if (isValid) {
this.operatorsService.addOperator(this.operator).then(operator => {
this.goBack();
});
}
}
Also im importing this
import { FormsModule, ReactiveFormsModule } from '#angular/forms';

Angular cast select value to int

I have a form with different selects like :
<select [(ngModel)]="selected.isConnected" (ngModelChange)="formChanged()" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
My backend expect to receive an int in the "isConnected" attribute. Unfortunately as soon as I change the value of the select the attribute is cast to a string :
{
isConnected : "0", // 0 expected
}
For standard <input> I could use type="number" but for a <select> I'm clueless.
Is there a way to force angular 2 to cast the data to int ?
Use [ngValue] instead of "value":
<select [(ngModel)]="selected.isConnected" id="etat">
<option [ngValue]="0">Not connected</option>
<option [ngValue]="1">Connected</option>
</select>
If you want cast it within formChanged() method (Which you haven't provided yet).
You should use + symbol as shown below,
formChanged(): void {
selected.isConnected = +selected.isConnected;
...
}
No, sadly you're forced to parse it on your own in the formChanged() method, since you always get a string back from the select.
You could try it with something like this:
formChanged(): void {
selected.isConnected = parseInt(selected.isConnected);
// ...
}
You can send a Number variable to select and assign the value for that select element. Then if you want to capture the value when it changes, you can add (change) event to select and retrieve the value as shown below.
import { Component } from '#angular/core';
#Component({
selector: 'my-app',
template: `<select value="{{isConnected}}" (change)="printConnected($event.target.value)" name="etat" id="etat" class="form-control">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>
<div *ngIf="changed">You've selected {{isConnected}}<div>`
})
export class AppComponent {
isConnected : number = 1;
changed : boolean = false;
printConnected(value){
this.isConnected = value;
this.changed=true;
}
}
You can view an example at http://plnkr.co/edit/xO2mrTdpTGufkgXqdhYD?p=preview
I am using reactive bindings and do not want to use [(ngModel)]. Instead I created a piped observable that uses JSON.parse(value) (because +value doesn't handle "null"):
*.component.html:
<div class="col-lg-4 form-group">
<label>Group Type</label>
<select class="form-control" (change)="groupType$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let groupType of filterData.groupTypes" [value]="groupType.id">{{groupType.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group" *ngIf="filteredGroups$ | async as groupOptions">
<label>Group</label>
<select class="form-control" (change)="group$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let group of groupOptions" [value]="group.id">{{group.label}}</option>
</select>
</div>
<div class="col-lg-4 form-group">
<label>Status</label>
<select class="form-control" (change)="status$.next($event.target.value)">
<option [value]="null"></option>
<option *ngFor="let status of filterData.statuses" [value]="status.id">{{status.label}}</option>
</select>
</div>
*.component.ts:
group$ = new BehaviorSubject<string>(null);
groupId$ = this.group$.pipe(
map((groupId: string) => JSON.parse(groupId) as number)
);
groupType$ = new BehaviorSubject<string>(null);
groupTypeId$ = this.groupType$.pipe(
map((typeId: string) => JSON.parse(typeId) as number)
);
status$ = new BehaviorSubject<string>(null);
statusId$ = this.status$.pipe(
map((statusId: string) => JSON.parse(statusId) as number)
);
[ngValue] is intended for objects. It generates an artificial option value even for numeric constants. For those who might be concerned about tests or readability, you can expand two way binding microsyntax
<select [ngModel]="selected.isConnected"
(ngModelChange)="selected.isConnected=$event && +$event" id="etat">
<option value="0">Not connected</option>
<option value="1">Connected</option>
</select>

Ember: recover data from dynamic "select" tags

Using Ember, I am trying to build a form, with <select> droplists populated from stores. I don't know how to recover a value from here to use in a "save" function.
What am I doing wrong?
Here is a simplified version of what I have :
The route accesses to differents models. This works fine :
import Ember from 'ember';
export default Ember.Route.extend({
model() {
var store = this.store;
return Ember.RSVP.hash({
fighters: store.findAll('fighter'),
duels:store.findAll('duel')
});
},
setupController(controller, models) {
var fighters = models.fighters;
var duels = models.duels;
controller.set('fighters', fighters);
controller.set('duels', duels);
}
});
The Controller should save a new duel using the form's values. Here "formdata" is null when the form is submitted
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
save(formdata) {
var newduel = this.store.createRecord('duel', {
fighter1:formdata.fighter1,
fighter2:formdata.fighter2,
});
}
}
});
The template displays droplists OK, but I cannot "connect" to the value in the controller, whatever ##FIGHTERn## I try !
<form {{action "save" formdata on "submit"}}>
<dl>
<dt>
<select value='##FIGHTER1##'>
{{#each fighters as |fighter|}}
<option value={{fighter.id}}>{{fighter.name}}</option>
{{/each}}
</select>
</dt>
<dt>
<select value=##FIGHTER2##>
{{#each fighters as |fighter|}}
<option value={{fighter.id}}>{{fighter.name}}</option>
{{/each}}
</select>
</dt>
</dl>
<button type="submit">Add</button>
<form {{action "save" formdata on "submit"}}>
<dl>
<dt>
<select onchange={{action (mut fighter1) value="target.value"}}>
{{#each fighters as |fighter|}}
<option value={{fighter.id}} selected={{is-equal fighter1 fighter.id}}>{{fighter.name}}</option>
{{/each}}
</select>
</dt>
<dt>
<select onchange={{action (mut fighter2) value="target.value"}}>
{{#each fighters as |fighter|}}
<option value={{fighter.id}} selected={{is-equal fighter2 fighter.id}}>{{fighter.name}}</option>
{{/each}}
</select>
</dt>
</dl>
<button type="submit">Add</button>
Controller:
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
save() {
this.store.createRecord('duel', {
fighter1: scope.get("fighter1"),
fighter2: scope.("fighter2"),
});
}
}
});
This can help you out

Display textbox after selection of option

I'm making a form at the moment and I was wondering how I could get the script to show a textbox after I have selected options "other" or "option 3".
HTML:
<select name="choice" onchange="if(this.selectedIndex==5)
{this.form['other'].style.visibility='visible'}else
{this.form['other'].style.visibility='hidden'};">
<option value="" selected="selected">Select...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="other">Other</option>
</select>
<input type="textbox" name="other" style="visibility:hidden; margin-left:3px"/>
Javascript:
window.addEvent('domready', function() {
$('hearabout').addEvent('change', function() {
if ($('hearabout').value == 'Rekening' ) {
$('other_input').setStyle('display', 'block');
} else {
$('other_input').setStyle('display', 'none');
}
});
if ($('hearabout').value == 'Rekening' ) {
$('other_input').setStyle('display', 'block');
} else {
$('other_input').setStyle('display', 'none');
}
});
How do I change "this.selectedIndex==5" so that it takes both option 3 and 5?
Thanks
Add ID for ur select <select id='someth'>
Add an event for changing the selected value:
$('#someth').on('change', function(){
if (('#someth').val() == "other")
{
$('#YourInputID').css('display','block');
}
});
Dont miss to add display:none; in the input style