Dojo - Input fields are not Appending to the grid - javascript

I Created a grid using dojo.I 'm having a form with input fields while i entered the values and click the "Add Row" button the input fields are not appending to the grid. Delete Option is working fine but add row is not working. I have attached the link of jsfiddle kindly refer for more.
form = new Form({
onSubmit: function(evt) {
evt.preventDefault();
var formValue = this.get("value");
dataStore.newItem(formValue);
}
}, "formContainer");
form.startup();
});
jsfiddle

Fully agree with #Himanshu.
You HTML is strange.
If you want to use a submit button, you must put it inside the <form> element.
Also, still like #Himanshu said, you must provide an id in order to user newItem
See the following working jsfiddle example:
https://jsfiddle.net/xzkc7hbs/8/
For better records, here is a working snippets.
(ignore the script error, those are security warnings, and run it in full page. Otherwise the script errors are over the textboxes)
require([
'dojo/_base/lang',
'dojox/grid/DataGrid',
'dojo/data/ItemFileWriteStore',
'dojo/dom',
'dijit/form/Button',
'dojo/dom-class',
"dojo/dom-construct",
"dojo/on",
"dijit/form/Form",
"dijit/form/TextBox",
"dojo/store/Memory",
"dojo/data/ObjectStore",
"dojo/request",
"dijit/registry",
'dojo/domReady!',
'dojox/grid/_CheckBoxSelector'
], function(lang, DataGrid, ItemFileWriteStore, dom, Button, domClass, domConstruct, on, Form, TextBox, Memory, ObjectStore, request, registry) {
var data = {
identifier: 'id',
items: []
};
var data_list = [{
fname: "Boy",
lname: "Mayer",
email: "boy#mayer.com",
num: 54526
}, {
fname: "Paul",
lname: "Taucker",
email: "paul#taucker.com",
num: 12345
}, {
fname: "Steven",
lname: "Spil",
email: "steven#spil.com",
num: 87654
}, {
fname: "computer",
lname: "Tech",
email: "comp#tech.com",
num: 45158
}, {
fname: "User",
lname: "Interface",
email: "user#inter.in",
num: 94979
}];
var rows = data_list.length;
for (i = 0, l = rows; i < rows; i++) {
data.items.push(lang.mixin({
id: i + 1
}, data_list[i % l]));
}
var dataStore = new dojo.data.ItemFileWriteStore({
data: data
});
var layout = [{
type: "dojox.grid._CheckBoxSelector",
width: '30px'
},
[{
'name': 'Sl',
'field': 'id',
'width': '20px',
'editable': 'false'
}, {
'name': 'Firstname',
'field': 'fname',
'width': '140px',
'editable': 'true'
}, {
'name': 'Lastname',
'field': 'lname',
'width': '130px',
'editable': 'true'
}, {
'name': 'Email',
'field': 'email',
'width': '140px',
'editable': 'true'
}, {
'name': 'Number',
'field': 'num',
'width': '80px',
'editable': 'true'
}]
];
var grid = new DataGrid({
store: dataStore,
query: {
id: "*"
},
queryOptions: {},
structure: layout
});
grid.placeAt("gridDiv");
grid.startup();
var button = new Button({
label: "Add Row",
}, "addRow");
button.startup();
var button = new Button({
label: "Delete",
}, "deleteBtn");
button.startup();
dojo.connect(deleteBtn, "onclick", function() {
var items = grid.selection.getSelected();
if (items.length) {
dojo.forEach(items, function(selectedItem) {
if (selectedItem !== null) {
dataStore.deleteItem(selectedItem);
}
});
}
});
var form = new Form({
onSubmit: function(evt) {
evt.preventDefault();
var formValue = form.get("value");
console.debug(formValue);
dataStore.fetch({
onComplete: function(allItems) {
var newId = allItems.length + 1;
dataStore.newItem({
id: newId,
fname: formValue.first,
lname: formValue.last,
email: formValue.dob,
num: formValue.mobile
});
}
})
}
}, "myForm");
form.startup();
});
*,
th {
font: 14px'verdana', sans-serif;
}
td {
font: 13px'verdana', sans-serif;
}
#gridDiv {
height: 14em;
margin-bottom: 15px;
width: 42em;
}
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js" data-dojo-config="parseOnLoad:true"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/resources/dojo.css">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dijit/themes/claro/claro.css">
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojox/grid/resources/claroGrid.css">
<div class="claro">
<div id="gridDiv"></div>
<button id="deleteBtn"></button>
<form id="myForm">
<div id="formContainer">
<input type="text" id="first" name="first" data-dojo-type="dijit/form/TextBox" value="" placeholder="Firstname" required/>
<input type="text" id="last" name="last" data-dojo-type="dijit/form/TextBox" value="" placeholder="Lastname" required />
<input type="text" id="email" name="dob" data-dojo-type="dijit/form/TextBox" value="" placeholder="Email" required />
<input type="text" id="mobile" name="mobile" data-dojo-type="dijit/form/TextBox" value="" placeholder="Mobile Number" required />
</div>
<button type="submit" value="submit" data-dojo-type="dijit/form/Button" id="submitForm">Add Row</button>
</form>
</div>

There are some problems with your HTML code. There is no need for the form element. You just need a div and place your dijit.form.Form in the div element. And, the submit button needs to be inside that div. It will automatically get triggered.
See the updated fiddle: JSFiddle
There is one more thing, to add data to the store, you have to provide an id to the newItem. Store will not accept an element without an id.

Related

Remove selected option from select2 multiselect on change.

I have the following code. The aim is to style a select2 box with textbox as the searchbox. So I have implemented it as multiselect , but I only want one option to be selected.
One option is to restrict using maximumSelectionLength: 1. But in this case the limit message will be shown which i do not want to happen. (Even if i hide it some space will be taken up ).
Other option is to hide everything other than last-child , in that case multiple values will be send to backend when form is submitted.
So is there a way to remove the currently selected value when the new value is selected in multiselect ?
I'm using select2 version 3.5.2
$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: true,
placeholder: "Click here and start typing to search.",
data: [
{ id: 1, text: "Honolulu" },
{ id: 2, text: "Tokyo" },
{ id: 3, text: "Delhi" },
{ id: 4, text: "Zurich" }
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/>
<h3>Select a value</h3>
<input type="text" id="placeSelect"/>
You can only keep the last selected item and remove all other. Like this way :
$('#placeSelect').click(function () {
var t = $("#placeSelect").val().substr($("#placeSelect").val().length - 1);
$("#placeSelect").val(t).trigger("change");
});
$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: true,
placeholder: "Click here and start typing to search.",
data: [
{ id: 1, text: "Honolulu" },
{ id: 2, text: "Tokyo" },
{ id: 3, text: "Delhi" },
{ id: 4, text: "Zurich" }
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/>
<h3>Select a value</h3>
<input type="text" id="placeSelect"/>
$('#placeSelect').select2({
width: '100%',
allowClear: true,
multiple: false,
placeholder: "Click here and start typing to search.",
data: [
{ id: 1, text: "Honolulu" },
{ id: 2, text: "Tokyo" },
{ id: 3, text: "Delhi" },
{ id: 4, text: "Zurich" }
]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script>
<link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/>
<h3>Select a value</h3>
<input type="text" id="placeSelect"/>
You are using a multi option select, I suggest you to do the following:
multiple: false,
just add the following code in your query and it will work as you need it
$('ul.select2-choices').on("click", function() {
$("ul.select2-choices li .select2-search-choice-close").click();
});

Dynamic textbox on Boostrap UL - unable to type

I have added dynamically a textbox to the bottom of the ul as an option. When I try to type inside the focus is lost. If I remove the e.stopPropagation() and the use clicks on the textbox, then the list closes.
How can I type inside my custom textbox txtCategory the same way it allows typing on the 'Search' box without closing the list? The txtCategory has value '2' when loaded.
Here is the fiddle
Script
<script type="text/javascript">
var customOption = "<li class='multiselect4-item multiselect-filter' value='0'><div class='input-group'><input class='xxx' id='txtCategory' value='2'><input type='button' id='btnAddOption' value='Add'></div></li>";
$(document).ready(function () {
//$("#theChildx").hide();
$('#example-post-checkboxName').multiselect({
enableFiltering: true,
enableClickableOptGroups: true,
enableCollapsibleOptGroups: true,
includeSelectAllOption: true,
onDropdownShow: function (select, container) {
//var siz = parseInt($('#theParentx').height(),5) + parseInt($('#theParentx .multiselect-container').height(), 10) + parseInt($('#theChildx').height(),7);
//var w = $('#theParentx .multiselect-container').width();
//$('#theChildx').css({ 'top': siz + "px", 'width': w }).show();
},
onDropdownHide: function (event) {
//$("#theChildx").hide();
},
templates: {
divider: '<li class="multiselect-item divider"></li>',
liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>'
}
});
var data = [{
title: 'First group',
children: [{ label: 'Cheese', value: 'cheese' , selected: true},
{ label: 'Tomatoes', value: 'tomatoes', selected: false, "attributes": {"some-attribute": 1, "another-attribute": false } }]
}, {
title: 'Second group',
children: [{ label: 'Mozzarella', value: 'mozzarella' },
{ label: 'Mushrooms', value: 'mushrooms' }]
}];
$("#example-post-checkboxName").multiselect('dataprovider', data);
$('.dropdown-menu').append(customOption);
//add actions on dynamically created button
$('.dropdown-menu').on("click", "#txtCategory", function (e) {
e.stopPropagation();
});
$('.dropdown-menu').on("click", "#btnAddOption", function () {
// alert('clicked');
var theValue = '<option>' + $('#txtCategory').val() + '</option>';
//$('#txtCategory').val();
$('#example-post-checkboxName').append(theValue);
$('#example-post-checkboxName').multiselect('rebuild')
{
$('.dropdown-menu').append(customOption);
alert('ok');
};
return false;
});
});
</script>
HTML
<div class="form-group">
<label class="col-sm-2 control-label">Multiselect</label>
<div class="col-sm-10">
<div id="theParentx">
<select id="example-post-checkboxName" name="multiselect[]" aria-labelledby="dropdownMenu3" multiple="multiple" required>
</select>
<div id="theChildx" class="dropdown-menu">
<input />
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default input-group-addon">Submit</button>
</div>
</div>
Add keydown event along with click to your dynamic textbox as below:
$('.dropdown-menu').on("keydown click", "#txtCategory", function (e) {
e.stopPropagation();
});
Updated Fiddle Here

Pass data from a JavaScript array to an HTML form

I am trying to learn JavaScript and I came across a practice problem in a book I purchased that I cannot seem to crack. The task is to flesh out a javascript formBuilder function to generate HTML forms dynamically from a JavaScript array. I have copied the code from the book onto a CodePen page for visual and testing purposes.
CodePen: http://codepen.io/anon/pen/gpwZMX
HTML sample:
<div>
<button data-sample='1'>Run 1</button>
<button data-sample='2'>Run 2</button>
<button data-sample='3'>Run 3</button>
</div>
<hr>
<div id='spec'>
<i>This div will display the currently-processed spec</i>
</div>
<br>Output:
<div id='result'>
<i>I sure wish I had a cool html form in me...</i>
</div>
<!--here are some test cases in docblock form-->
<div class='testcase' id='1'>
/** Comment Form
* Make a comment on the blog post!
* #param string[100] title
* #param email email
* #param text body
* #param bool subscribe Email me when someone comments on my comment!
*/
</div>
JavaScript sample:
var samples = [
{
title:"Comment Form",
desc:"Make a comment on the blog post!",
params:[
{
type: 'text',
max_length: 100,
name: 'title'
},
{
type: 'email',
name: 'email'
},
{
type:'textarea',
name:'body'
},
{
type:'checkbox',
name:'subscribe',
label:'mail me when someone comments on my comment!'
}
]
}]
formBuilder sample:
//builds an HTML form using all information present in `spec` and places the resulting HTML in jquery element `$el`
function formBuilder(spec,$el){
$el.html("<i>I still wish I had a cool html form in me...</i>");
}
$("button").on("click",function($e){
var specIndex = $($e.target).data('sample');
var specData = samples[specIndex-1];
$("#spec").html("Sample spec "+(specIndex)+" looks like: <br>"+JSON.stringify(specData));
formBuilder(specData, $("#result"));
});
Errors in the codepen code exist, paste the code below into your project:
var samples = [
{
title:"Comment Form",
desc:"Make a comment on the blog post!",
params:[
{
type: 'text',
max_length: 100,
name: 'title'
},
{
type: 'email',
name: 'email'
},
{
type:'textarea',
name:'body'
},
{
type:'checkbox',
name:'subscribe',
label:'mail me when someone comments on my comment!'
}
]
},
{
title:"Car Order Form",
desc:"Choose your car!",
params:[
{
type:'select',
values:['red','blue','green','black','white','taupe'],
name: 'color'
},
{
type: 'checkbox',
values:['fog-lights','radio','a-c','wheels','headlights'],
name: 'options'
},
{
type:'string',
minLength:7,
maxLength:7,
name:'vanityPlate',
optional:true
},
{
type:'int',
name:'price',
}
]
},
{
title:"New User Creator",
desc:"Create a new user account",
params:[
{
type:'string',
maxLength:20,
name:'fname',
label:'First Name'
},
{
type:'string',
maxLength:20,
name:'lname',
label:'Last Name'
},
{
type:'date',
name:'dob',
label:'Date of Birth'
},
{
type:'email',
multiple:true,
maxCount:4,
name:'emails',
label:'Email Addresses'
},
{
type: 'string',
name: 'addr1',
label: 'Street Address'
},
{
type: 'string',
name: 'city'
},
{
type: 'state',
name: 'state',
},
{
type: 'int',
name: 'zipcode',
maxValue: 99999,
minValue: 0,
label: 'ZIP'
},
]
}
]
//builds an HTML form using all information present in `spec` and places the resulting HTML in jquery element `$el`
function formBuilder(spec,$el){
var inputs = getInputs(spec);
$el.html("<form title='"+spec.title+"'><fieldset><legend>"+spec.desc+"</legend>"+inputs+"</fieldset></form>");
}
function getInputs(spec) {
var inputs = "";
for(var i = 0; i < spec.params.length; i++) {
var input = "<input ";
var attributes = JSON.stringify(spec.params[i]).split(",");
console.log(attributes);
for(var j = 0; j < attributes.length; j++) {
$.each(spec.params[i], function(key, value) {
input += key + "='" + value + "' ";
});
}
inputs += input + "/><br/>";
}
return inputs;
}
$("button").on("click",function($e){
var specIndex = $($e.target).data('sample');
var specData = samples[specIndex-1];
$("#spec").html("Sample spec "+(specIndex)+" looks like: <br>"+JSON.stringify(specData));
formBuilder(specData, $("#result"));
});
The last item in an array does not get a comma appended to it. Always ensure to end a line of code with a semi-colon as well. Those are the changes I made to your code, now it runs, as I assume, correctly unless you have any other issues?

How Can I Hide Kendo UI Grid Columns using JavaScript, React, Angular, Vue or ASP.NET MVC

I'm working on a HTML5 and JavaScript website.
Is it possible to have a hidden column in Kendo UI Grid and access the value using JQuery?
Using JavaScript
See the Kendo UI API reference.
Hide a column during grid definition
You can add hidden: true:
$("#gridName").kendoGrid({
columns: [
{ hidden: true, field: "id" },
{ field: "name" }
],
dataSource: [ { id: 1, name: "Jane Doe" }, { id: 2, name: "John Doe" } ]
});
Hide a column by css selector
$("#gridName").find("table th").eq(1).hide();
Hide a column by column index
var grid = $("#gridName").data("kendoGrid");
grid.hideColumn(1);
Hide a column by column name
var grid = $("#gridName").data("kendoGrid");
grid.hideColumn("Name");
Hide a column by column object reference
var grid = $("#gridName").data("kendoGrid");
grid.hideColumn(grid.columns[0].columns[1]);
Using React
See the Kendo UI for React API reference
Hide a column during grid definition
You can set show: false:
class App extends React.Component {
columns = [
{
title: 'Product Id',
field: 'ProductID',
show: false
},
{
title: 'Product Name',
field: 'ProductName',
show: true
},
{
title: 'Unit Price',
field: 'UnitPrice',
show: true
}
]
constructor() {
super();
this.state = {
columns: this.columns,
show:false
};
}
render() {
return (
<div>
<Grid data={products} >
{this.state.columns.map((column, idx) =>
column.show && (<Column key={idx} field={column.field} title={column.title} />)
)}
</Grid>
</div>
);
}
}
Using Angular
See the Kendo UI for Angular API reference
Hide a column during grid definition
You can add [hidden]="true"
#Component({
selector: 'my-app',
template: `
<kendo-grid [data]="gridData" [scrollable]="scrollable" style="height: 200px">
<kendo-grid-column [hidden]="true" field="ID" width="120">
</kendo-grid-column>
<kendo-grid-column field="ProductName" title="Product Name" width="200">
</kendo-grid-column>
<kendo-grid-column field="UnitPrice" title="Unit Price" width="230">
</kendo-grid-column>
</kendo-grid>
`
})
Programmatically hide a column
#Component({
selector: 'my-app',
template: `
<div class="example-config">
<button (click)="restoreColumns()" class="k-button">Restore hidden columns</button>
</div>
<kendo-grid [data]="gridData" style="height:400px">
<ng-template ngFor [ngForOf]="columns" let-column>
<kendo-grid-column field="{{column}}" [hidden]="hiddenColumns.indexOf(column) > -1" >
<ng-template kendoGridHeaderTemplate let-dataItem>
{{dataItem.field}}
<button (click)="hideColumn(dataItem.field)" class="k-button k-primary" style="float: right;">
Hide
</button>
</ng-template>
</kendo-grid-column>
</ng-template>
</kendo-grid>
`
})
export class AppComponent {
public gridData: any[] = sampleCustomers;
public columns: string[] = [ 'CompanyName', 'ContactName', 'ContactTitle' ];
public hiddenColumns: string[] = [];
public restoreColumns(): void {
this.hiddenColumns = [];
}
public hideColumn(field: string): void {
this.hiddenColumns.push(field);
}
}
Using Vue
See the Kendo UI for Vue API reference
Hide a column during grid definition
You can add :hidden="true"
<kendo-grid :height="600"
:data-source-ref="'datasource1'"
:pageable='true'>
<kendo-grid-column field="ProductID" :hidden="true"></kendo-grid-column>
<kendo-grid-column field="ProductName"></kendo-grid-column>
<kendo-grid-column field="UnitPrice" title="Unit Price" :width="120" :format="'{0:c}'"></kendo-grid-column>
<kendo-grid-column field="UnitsInStock" title="Units In Stock" :width="120"></kendo-grid-column>
</kendo-grid>
Using ASP.NET MVC
See the Kendo MVC API reference
Hide a column during grid definition
#(Html.Kendo().Grid<Something>()
.Name("GridName")
.Columns(columns =>
{
columns.Bound(m => m.Id).Hidden()
columns.Bound(m => m.Name)
})
)
Using PHP
See the Kendo UI for PHP API reference
Hide a column during grid definition
<?php
$column = new \Kendo\UI\GridColumn();
$column->hidden(true);
?>
As #Nic says there are multiple ways of hiding a column but I'm gonna assume that you are using KendoUI methods for hiding it. I.e: set the column hidden to true or programmatically invoke hideColumn.
If so, you should remember that you model might have fields that are not displayed or not even mapped in columns but they exist and you can still access them.
If we have the following Grid definition:
var grid = $("#grid").kendoGrid({
dataSource: ds,
selectable: true,
...
columns :
[
{ field: "Id", hidden: true },
{ field: "FirstName", width: 90, title: "First Name" },
{ field: "LastName", width: 200, title: "Last Name" }
]
}).data("kendoGrid");
Where I've declared a column Id as hidden. I still can access the value of Id by going to the model using:
// I want to access the Id for row 3
var row = $("tr:eq(3)", "#grid");
// Retrieve the item from the grid using dataItem method
var item = $("#grid").data("kendoGrid").dataItem(row);
// Show Id
alert("Id is " + item.Id);
Runnable example
var grid = $("#grid").kendoGrid({
dataSource: [
{ Id: 1, FirstName: "John", LastName: "Smith" },
{ Id: 2, FirstName: "Jane", LastName: "Smith" },
{ Id: 3, FirstName: "Jack", LastName: "Smith" },
{ Id: 4, FirstName: "Joseph", LastName: "Smith" },
{ Id: 5, FirstName: "Jeff", LastName: "Smith" },
],
selectable: true,
columns :
[
{ field: "Id", hidden: true },
{ field: "FirstName", width: 90, title: "First Name" },
{ field: "LastName", width: 200, title: "Last Name" }
]
}).data("kendoGrid");
$("#show").on("click", function(e) {
var row = grid.select();
if (row) {
var item = grid.dataItem(row);
alert ("The ID is :" + item.Id);
} else { 
alert("Select a row");
}
});
#grid {
width : 490px;
}
<link href="http://cdn.kendostatic.com/2014.2.903/styles/kendo.common.min.css" rel="stylesheet" />
<link href="http://cdn.kendostatic.com/2014.2.903/styles/kendo.default.min.css" rel="stylesheet" />
<script src="http://cdn.kendostatic.com/2014.2.903/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.2.903/js/kendo.all.min.js"></script>
Select row and click <button id="show" class="k-button">Here</button> to show hidden Id.
<div id="grid"></div>

angular ng-repeat on input from json

I am trying to pull all the forms for my page from a json object with values to plug into the ng-required, max-values min-values and type fields. But these values aren't being inserted into the dom. How would I go about repeating over a number of input elements and control whether or not they were text boxes or file uploads and whether or not they are required? I did up a fiddle based on what I was hoping to accomoplish but cant figure out why this doesn't work. see the jsfiddle.
HTML
<form novalidate name="form1" ng-controller="step1">
<div ng-repeat="field in json">
<label>
{{field.label}}
</label>
<input type="field.type" ng-model="field.model">
</div>
</form>
Javascript
function step1($scope) {
$scope.json = [
{
"error": "Must be more then 3 letters",
"label": "store Name 1",
"model": "storeName"
},
{
"error": "Must be more then 3 letters",
"label": "store Name 1",
"model": "storeName"
}
];
}
Setting input type dynamically is bit tricky, but may be achived with custom directive that appends input to the DOM. From the other hand, inserting inputs to the form dynamically from custom directive you can't enjoy things like myForm.myInput.$error.requred. Besides of it you probably want to add error message and some styling to invalid inputs, therefore you need some CSS.
Here is an example of dynamic form created from JSON with ng-required, ng-maxlength and ng-minlength enabled:
Plunker: http://plnkr.co/edit/F7BGq0sfSLvKE48eDTzQ?p=preview
HTML
<!DOCTYPE html>
<html ng-app="demo">
<head>
<script src="http://code.angularjs.org/1.2.10/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="demoController">
<form name="demoForm">
<div demo-directive ng-repeat="input in inputs"></div>
</form>
</body>
</html>
CSS
.error .required,
.error .minlength,
.error .maxlength {
display: none;
}
.ng-invalid-required + .error .required,
.ng-invalid-minlength + .error .minlength,
.ng-invalid-maxlength + .error .maxlength {
display: inline;
}
.ng-invalid {
outline: 1px solid red;
}
.error {
color: red;
}
JavaScript
angular.module('demo', []).
controller('demoController', function($scope) {
$scope.inputs = [{
inputType: 'checkbox',
name: 'f1',
checked: true,
label: 'input 1',
required: true
}, {
inputType: 'text',
name: 'f2',
value: 'some text 1',
label: 'input 2',
required: true
}, {
inputType: 'file',
name: 'f3',
label: 'input 3'
}, {
inputType: 'text',
name: 'f4',
value: 'some text 2',
label: 'input 2',
min: 2,
max: 15
}];
}).
directive('demoDirective', function($compile) {
return {
template: '<div><label>{{input.label}}: </label></div>',
replace: true,
link: function(scope, element) {
var el = angular.element('<span/>');
switch(scope.input.inputType) {
case 'checkbox':
el.append('<input type="checkbox" name="{{input.name}}" ng-model="input.checked" ng-required="{{input.required}}"/><span class="error"><span class="required">Required!</span></span>');
break;
case 'text':
el.append('<input type="text" name="{{input.name}}" ng-model="input.value" ng-required="{{input.required}}" ng-minlength="{{input.min}}" ng-maxlength="{{input.max}}" /><span class="error"><span class="required">Required!</span><span class="minlength">Minimum length is {{input.min}}!</span><span class="maxlength">Maximum length is {{input.max}}!</span></span>');
break;
case 'file':
el.append('<input type="file" name="{{input.name}}" ng-model="input.value" ng-required="{{input.required}}"/><span class="error"><span class="required">Required!</span></span>');
break;
}
$compile(el)(scope);
element.append(el);
}
}
});

Categories

Resources