I'm trying to use jQuery no validator in a form that has a textarea using TinyMCE and I can't leave it as required.
I found some examples to make this requirement, but everyone I add ends up removing TinyMCE from my textarea.
Can anyone can help me? all examples are always giving error.
This is my code:
#model Contato
#{
ViewData["Title"] = "Contato nos";
Layout = "~/Views/Shared/_Layout.cshtml";
var end = "https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d14635.842857905212!2d-47.446606835918516!3d-23.49792447583607!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x94cf61e82bba04e5%3A0xec1214319ddea74d!2sMarcenaria%20MF!5e0!3m2!1spt-BR!2sbr!4v1620093541821!5m2!1spt-BR!2sbr";
}
<!-- ======= Breadcrumbs ======= -->
<section id="breadcrumbs" class="breadcrumbs">
<div class="container">
<div class="d-flex justify-content-between align-items-center">
<h2>Contato</h2>
<ol>
<li><a asp-controller="Home" asp-action="Index">Marcenaria MF</a></li>
<li>Contato</li>
</ol>
</div>
</div>
</section><!-- End Breadcrumbs -->
<!-- ======= Contact Section ======= -->
<div class="map-section">
<iframe style="border:0; width: 100%; height: 350px;" src=#end frameborder="0" allowfullscreen></iframe>
</div>
<section id="contact" class="contact">
<div class="container">
<div class="row justify-content-center" data-aos="fade-up">
<div class="col-lg-10">
<div class="info-wrap">
<div class="row">
<div class="col-lg-4 info">
<i class="bi bi-geo-alt"></i>
<h4>Endereço:</h4>
<p> R. Yashica, N° 350 - Jardim Bela Vista,<br>Sorocaba - SP, 18016-440</p>
</div>
<div class="col-lg-4 info mt-4 mt-lg-0">
<i class="bi bi-envelope"></i>
<h4>Email:</h4>
<p>info#example.com<br>contact#example.com</p>
</div>
<div class="col-lg-4 info mt-4 mt-lg-0">
<i class="bi bi-phone"></i>
<h4>Telefones:</h4>
<p>(15) 99756-6839<br>(15) 99761-6833</p>
</div>
</div>
</div>
</div>
</div>
<div class="row mt-5 justify-content-center" data-aos="fade-up">
<div class="col-lg-10">
<form id="form_contato" asp-controller="Contatos" asp-action="Contato" method="post" role="form" class="php-email-form" enctype="multipart/form-data">
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="Nome" class="form-control" asp-for="Nome" placeholder="Seu Nome">
<span asp-validation-for="Nome" class="text-danger"></span>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="Email" asp-for="Email" placeholder="Seu Email">
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="Assunto" asp-for="Assunto" placeholder="Assunto">
<span asp-validation-for="Assunto" class="text-danger"></span>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="Mensagem" rows="5" asp-for="Mensagem" placeholder="Mensagem"></textarea>
<span asp-validation-for="Mensagem" class="text-danger"></span>
</div>
<div class="my-3">
<div class="loading" id="loading">Loading</div>
<div class="error-message" id="error-message"></div>
<div class="sent-message" id="sent-message">Sua mensagem foi enviada. Obrigado!</div>
</div>
<div class="text-center"><button type="submit">Enviar Mensagem</button></div>
</form>
</div>
</div>
</div>
</section><!-- End Contact Section -->
<script src="~/tinymce/js/tinymce/tinymce.min.js"></script>
<script src="~/tinymce/langs/pt_BR.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script>
$(document).ready(function () {
tinymce.init({
selector: 'textarea',
height: 250,
menubar: false,
plugins: 'link, autolink link, textcolor, paste',
toolbar: false,
content_css: '//www.tiny.cloud/css/codepen.min.css',
language: 'pt_BR',
paste_remove_styles_if_webkit: false,
paste_block_drop: false,
paste_data_images: false,
paste_as_text: true,
paste_enable_default_filters: false,
paste_webkit_styles: "none",
browser_spellcheck: true,
contextmenu: true,
branding: false,
statusbar: false,
setup: function (ed) {
//On change call
ed.on('change', function (e) {
//Validate tinyMCE on text change
tinyMCE.triggerSave();
$("#" + ed.id).valid();
}
);
},
});
$(function () {
$.validator.setDefaults({
submitHandler: function () {
$('#loading').addClass('d-block');
}
});
var content = tinyMCE.get("Mensagem");
tinyMCE.triggerSave();
//initialize validatoe
var validator = $("#form_contato").submit(function () {
// update underlying textarea before submit validation
alert($("#Mensagem").val());
}).validate({
ignore: ".ignore",
rules:
{
Email: {
required: true,
email: true,
},
Nome: {
required: true,
},
Assunto: {
required: true
},
Mensagem: {
required: true,
},
},
errorPlacement: function (label, element) {
// position error label after generated textarea
if (element.is("textarea")) {
label.insertAfter(element.next());
} else {
label.insertAfter(element)
}
}
});
validator.focusInvalid = function () {
// put focus on tinymce on submit validation
if (this.settings.focusInvalid) {
try {
var toFocus = $(this.findLastActive() || this.errorList.length && this.errorList[0].element || []);
if (toFocus.is("textarea")) {
tinyMCE.get(toFocus.attr("#Mensagem")).focus();
} else {
toFocus.filter(":visible").focus();
}
} catch (e) {
// ignore IE throwing errors when focusing hidden elements
}
}
}
})
});
</script>
#if (ViewData["MSG"] != null)
{
<script>
alert(#ViewData["MSG"].ToString());
</script>
}
I really appreciate your help guys
Related
I have the following drop zone js and have a file input hidden with an asp-for tag which should map to my viewmodel. However there is nothing being mapped. The controller accepts a parameter List FormFiles.
<form method="post" asp-action="Index" asp-controller="Customer" class="js-step-form js-validate" enctype="multipart/form-data"
data-hs-step-form-options='{
"progressSelector": "#validationFormProgress",
"stepsSelector": "#validationFormContent",
"endSelector": "#validationFormFinishBtn",
"isValidate": true
}'>
<!-- Step -->
<!-- End Step -->
<!-- Content Step Form -->
<div id="validationFormContent">
<div id="validationFormAccount" class="active">
<div class="row">
<div class="col-sm-6">
<!-- Form Group -->
<div class="form-group js-form-message mb-3">
<label class="input-label">Loyality Spend</label>
<input id="LoyalitySpendTextBox" type="text" class="form-control stringValidation" required
data-msg="Please enter Loyality Spend." placeholder="Loyality Spend" aria-label="Current Value" value="#Model.Customer.LoyaltySpend" asp-for="#Model.Customer.LoyaltySpend">
</div>
<!-- End Form Group -->
</div>
<div class="col-sm-6">
<!-- Form Group -->
<div class="form-group mb-3">
<label class="input-label">Documents</label>
<!-- Dropzone -->
<div id="attachFilesLabel" class="js-dropzone dropzone-custom custom-file-boxed">
<div class="dz-message dz-filename">
<img class="avatar avatar-xl avatar-4by3 mb-3" src="~/front-dashboard-v1.1/src/assets/svg/illustrations/browse.svg" alt="Image Description">
<h5>Drag and drop your file here</h5>
<p class="mb-2">or</p>
<span class="btn btn-sm btn-white" id="chose_files_btn" onclick="doOpen(event)">
Browse File
<input type="file" asp-for="#Model.FormFiles" id="File" name="File" size="1" style="display: none" />
</span>
</div>
</div>
<!-- End Dropzone -->
</div>
<!-- End Form Group -->
</div>
</div>
</div>
</form>
If you want to bind data with name FormFiles,you can use paramName of Dropzone.And if you want to upload files when button click,try to use autoProcessQueue: false,,and in button click event add e.preventDefault();wrapperThis.processQueue();.If you want to delete files,you need to add addRemoveLinks: true, and use removedfile. Here is a demo.
View:
<form asp-action="Upload" asp-antiforgery="false"
class="dropzone" id="myAwesomeDropzone" enctype="multipart/form-data">
<div class="fallback">
<input asp-for="FormFiles" type="file" multiple />
</div>
js:
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.2/dropzone.css"/>
<script>
function myParamName() {
return "FormFiles";
}
Dropzone.options.myAwesomeDropzone = {
autoProcessQueue: false,
paramName: myParamName, // The name that will be used to transfer the file
uploadMultiple: true,
parallelUploads: 100,
addRemoveLinks: true,
removedfile: function (file) {
file.previewElement.remove();
},
init: function () {
console.log("active");
var wrapperThis = this;
$("#submit").click(function (e) {
e.preventDefault();
wrapperThis.processQueue();
});
},
accept: function (file, done) {
done();
}
};
</script>
action:
[HttpPost]
public IActionResult Upload(List<IFormFile> FormFiles)
{
return Ok();
}
result:
I'm trying to create a cv creater form and need to let users add more inputs (auto).
I created inputs and they work just fine, but I need to change the name attribute for each auto added block.
For example :
<input type="text" id="fname" name="fname">
<input type="text" id="fname" name="fname2">
<input type="text" id="fname" name="fname3">
I know I can use name="value[]" array, but every new block goes into a different column in the database, so I need to change attributes.
My code :
$(document).ready(function() {
var max_fields = 10;
var wrapper = $("#contant");
var add_button = $("#add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div id="input-social" class="input-container"><input type="text" id="social" class="col-11 form-control" name="fname" placeholder="fname"> <span id="deleteInput" class="AutoInput" title="Delete"><i class="fas fa-trash-alt"></i></span></div>');
} else {
alert('You Riched limit.')
}
});
$(wrapper).on("click", "#deleteInput", function(e) {
e.preventDefault();
$(this).parent('#input-social').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/e794a0f8b4.js" crossorigin="anonymous"></script>
<div class="form-group">
<div class="row">
<label class="col-3 inputFontSize" for="social">Others</label>
<div id="contant" class="col-7">
<button id="add_form_field" class="btn add_form_field">Add more <i class="fas fa-plus"></i></button>
</div>
<!-- col-9 -->
</div>
<!-- row -->
</div>
<!-- form-group -->
Thanks for all helps
You can use your x variable that is incremented for each added input and append it to the name attribute. We'll use a 'template string'. The adjustment is name="fname${x}" which will substitute ${x} for the value of x.
$(wrapper).append(`
<div id="input-social" class="input-container">
<input type="text" id="social" class="col-11 form-control" name="fname${x}" placeholder="fname">
<span id="deleteInput" class="AutoInput" title="Delete">
<i class="fas fa-trash-alt"></i>
</span>
</div>`
);
$(document).ready(function() {
var max_fields = 10;
var wrapper = $("#contant");
var add_button = $("#add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append(`<div id="input-social" class="input-container"><input type="text" id="social" class="col-11 form-control" name="fname${x}" placeholder="fname"> <span id="deleteInput" class="AutoInput" title="Delete"><i class="fas fa-trash-alt"></i></span></div>`);
} else {
alert('You Riched limit.')
}
});
$(wrapper).on("click", "#deleteInput", function(e) {
e.preventDefault();
$(this).parent('#input-social').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://kit.fontawesome.com/e794a0f8b4.js" crossorigin="anonymous"></script>
<div class="form-group">
<div class="row">
<label class="col-3 inputFontSize" for="social">Others</label>
<div id="contant" class="col-7">
<button id="add_form_field" class="btn add_form_field">Add more <i class="fas fa-plus"></i></button>
</div>
<!-- col-9 -->
</div>
<!-- row -->
</div>
<!-- form-group -->
I am working on SPA (Single Page Application) for Online Team Collaboration service(OTC) ,and I include HTML pages by ng-include,in some included page there is a popover ,this one contains a possibility for creating a public group chat,and in order to create one ,the user must submit, now my question is : how can i display a "successfully created" message in the same popover instead of the main div for creating the group in the popover?
The external page (the page that include other pages):
<div ng-show="ctrChanneldiv" ng-contoller="ctrChannelCon" style="float: right;" class="col-md-3">
<div ng-include="'CreateChannel.html'" ></div>
</div>
The Controller ctrChannelCon:
appvar.controller('ctrChannelCon',['$scope','$http','$rootScope',function($scope, $http, $rootScope){
$scope.createBtn = function() {
$http.post("http://localhost:8080/ExampleServletv3/crtchannelservlet",this.crtchannel)
.success(function(response) {
setTimeout(function () {
$scope.$apply(function(){
//******* Here Display "Successfully Created" In the Popover *******//
});
});
});
};
}]);
In CreateChannel.html :
<div>
<div class="row">
<a href="#" class="popper" data-toggle="popover"
data-placement="bottom"><span class="glyphicon glyphicon-plus"></span>Create Channel</a>
<div class="popper-content hide">
<div class="form-group">
<!-- ng-controller="createChannelCon" -->
<div class="form-group">
<label>Channel name:</label>
</div>
<div class="form-group">
<input ng-model="crtchannel.Name" type="text" placeholder="enter channel's name" maxlength="30"
class="form-control input-md" required />
</div>
<div class="form-group">
<label>Description:</label>
</div>
<div class="form-group">
<textarea cols="15" ng-model="crtchannel.Description" type="text"
placeholder="enter channel's description" maxlength="500"
class="form-control input-md" required></textarea>
</div>
<div>
<input ng-model="crtchannel.Type" type="radio" name="chtype"
value="private" required /> Private<br> <input
ng-model="crtchannel.Type" type="radio" name="chtype"
value="public" /> Public<br>
</div>
<div class="form-group">
<button ng-click="createBtn()" class="btn btn primary">Apply</button>
</div>
</div>
</div>
<script>
$('.popper').popover({
container : 'body',
html : true,
content : function() {
return $(this).next('.popper-content').html();
}
});
</script>
</div>
</div>
Any suggestions?
Thanks
You may use ngClass directive to counter this problem. ngClass directive allows conditional application of classes. Create a div for successfully created in the popup and set up ng-class directive with a variable in the scope and assign it true and false as per your requirement.
JS
appvar.controller('ctrChannelCon',['$scope','$http','$rootScope',function($scope, $http, $rootScope){
$scope.createBtn = function() {
$http.post("http://localhost:8080/ExampleServletv3/crtchannelservlet",this.crtchannel)
.success(function(response) {
setTimeout(function () {
$scope.$apply(function(){
//******* Change value of a model *******//
$scope.hidden = false;
});
});
});
};
}]);
HTML
<span ng-class="{hide: hidden}">Successfully Created</span>
CSS
.hide { display: none; }
Set a flag in your controller on success and use this flag to show or hide the success message:
...
<div class="form-group">
<button ng-click="createBtn()" class="btn btn primary">Apply</button>
</div>
<div ng-show="isSuccess">Successfully Created</div>
Inside the controller:
$scope.isSuccess = false;
$scope.createBtn = function() {
$http.post("http://localhost:8080/ExampleServletv3/crtchannelservlet",this.crtchannel)
.success(function(response) {
setTimeout(function () {
$scope.$apply(function(){
//******* Here Display "Successfully Created" In the Popover *******//
$scope.isSuccess = true;
});
});
});
};
I am doing a job and I am not getting out of this error 2 days ago I will be posting the html code and TypeScript.
Code Index
<html>
<head>
<base href="/angular-21-menu-busca-alteracao-inclusao-remocao-selecao-inc/">
<title>Angular 2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="app/css/bootstrap.css">
<link rel="stylesheet" href="app/css/site.css">
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script src="app/js/jquery-1.12.4.js"></script>
<script src="app/js/bootstrap.js"></script>
<script src="app/js/script.js"></script>
<script src="app/js/web-animations.min.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<angular-app>Loading...</angular-app>
</body>
</html>
Code Html
<h2 class="text-center">Cadastro de Clientes</h2>
<!-- Adicionar -->
<h4 id="mensagem" class="text-center" [style.color]="getCor()" [style.visibility]="getVisibilidade()">{{mensagem}}</h4>
<!-- Fim adicionar -->
<div class="container">
<div class="row">
<div class="col-xs-12">
<div *ngIf="aluno">
<div class="media-list">
<div class="row">
<div class="col-xs-12">
<div class="media">
<div class="media-body">
<form class="form-horizontal" [formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGroup.valid)" novalidate>
<fieldset [disabled]="isDesabilitado">
<legend>Inf. Básicas</legend>
<div class="form-group form-group-sm">
<label class="col-sm-2 control-label" for="nome">Nome</label>
<div class="col-sm-9">
<input type="text"
id="nome"
[ngClass]="{'form-control': true, 'input-sm': true, 'submitted': submitted}"
>
</div>
<div class="col-sm-9 col-sm-offset-2">
<div *ngIf="formErrors.nome && submitted" class="alert alert-danger">
{{ formErrors.nome }}
</div>
</div>
<div class="col-sm-1"></div>
</div>
<!--
<div class="form-group form-group-sm">
<label class="control-label col-sm-2">Sexo</label>
<div class="col-sm-10">
<input type="radio" [(ngModel)]="aluno.sexo" name="sexo" value="M"> Masculino
</div>
<div class="col-sm-10 col-sm-offset-2">
<input type="radio" [(ngModel)]="aluno.sexo" name="sexo" value="F"> Feminino
</div>
</div>
<div class="form-group form-group-sm">
<label class="control-label col-xs-12 col-sm-2" for="sus">Num.SUS</label>
<div class="col-xs-9 col-sm-3">
<input [(ngModel)]="aluno.sus" maxlength="15" name="sus" class="form-control" id="sus">
</div>
<div class="col-xs-3 col-sm-7"></div>
</div>
</fieldset>
<br/>
<fieldset [disabled]="isDesabilitado">
<legend>Endereço</legend>
<div class="form-group form-group-sm">
<label class="col-sm-2 control-label" for="endereco">Logradouro</label>
<div class="col-sm-9">
<input [(ngModel)]="aluno.endereco" name="endereco" class="form-control"
type="text"
id="endereco">
</div>
<div class="col-sm-1"></div>
</div>
<div class="form-group form-group-sm">
<label class="col-sm-2 control-label" for="bairro">Bairro</label>
<div class="col-sm-9">
<input [(ngModel)]="aluno.bairro" name="bairro" class="form-control" type="text"
id="bairro">
</div>
<div class="col-sm-1"></div>
</div>
<div class="form-group form-group-sm">
<label class="col-sm-2 control-label" for="cidade">Cidade</label>
<div class="col-sm-9">
<input [(ngModel)]="aluno.cidade" name="cidade" class="form-control" type="text"
id="cidade">
</div>
<div class="col-sm-1"></div>
</div>
<div class="form-group form-group-sm">
<label class="col-xs-12 col-sm-2 control-label" for="estado">Estado</label>
<div class="col-xs-5 col-sm-2">
<input [(ngModel)]="aluno.estado" maxlength="2" name="estado" class="form-control" type="text"
id="estado">
</div>
<div class="col-xs-7 col-sm-8"></div>
</div>
-->
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
<div class="wrapper">
<!-- Adicionar -->
<button *ngIf="exibirEditar" class="btn btn-primary" (click)="editavel()">
<span class="glyphicon glyphicon-edit"></span> Editar
</button>
<button *ngIf="exibirAlterar" [disabled]="!f.valid" class="btn btn-primary" (click)="alterar(aluno)">
<span class="glyphicon glyphicon-save"></span> Alterar
</button>
<button *ngIf="exibirCadastrar" [disabled]="!usuarioGroup.valid" class="btn btn-primary" (click)="cadastrar(aluno)">
<span class="glyphicon glyphicon-save"></span> Salvar
</button>
<!-- Fim adicionar -->
<button class="btn btn-warning" (click)="voltar()">
<span class="glyphicon glyphicon-backward"></span> Voltar
</button>
</div>
<br/>
<br/>
<br/>
</div>
</div>
</div>
</div>
Code TS
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute, Params } from '#angular/router';
import { AlunoService } from './aluno.service';
import { Aluno } from './aluno';
import { Router } from '#angular/router';
import {FormBuilder, FormGroup, Validators} from "#angular/forms";
import {AutoValida} from "./auto.valida";
interface UsuarioForm {
nome: string,
sexo: string,
endereco: string,
bairro: string,
cidade: string,
estado: string,
sus: string,
}
#Component({
selector: 'exibir-aluno',
templateUrl: 'app/partials/exibir-aluno.component.html',
styleUrls: ['app/css/exibir-aluno.css']
})
export class ExibirAlunoComponent implements OnInit{
usuarioForm: UsuarioForm = {nome: '', sexo: '', endereco: '', bairro: '', cidade: '', estado: '', sus: '',};
usuarioGroup: FormGroup;
alunos: Aluno[];
aluno: Aluno = null;
isDesabilitado: boolean = true;
// Adicionar campos aqui!
exibirEditar: boolean = true;
exibirAlterar: boolean = false;
mensagem: string = "Esta mensagem será alterada ao exibir!";
visibilidade: string = "hidden";
cor: string = "blue";
exibirCadastrar: boolean = false;
constructor(private fb: FormBuilder,
private alunoService:AlunoService,
private route:ActivatedRoute,
private router: Router) { }
ngOnInit():void {
this.buildForm();
console.log('executando ngOninit de ExibirAlunoComponent');
let id = +this.route.snapshot.params['id'];
console.log('id = ', id);
// id = NaN
if (isNaN(id)) {
this.novo();
}
else {
this.alunoService.getAluno(id)
.subscribe(
data => {
this.aluno = data;
},
err => {
this.mensagem = "Aluno NÃO encontrado! Status:" + err.status;
this.cor = "red";
this.visibilidade = "visible";
}
);
}
}
novo() {
this.isDesabilitado = false;
this.exibirEditar = false;
this.exibirCadastrar = true;
this.exibirAlterar = false;
this.visibilidade = "hidden";
this.aluno = {
id: null,
nome: '',
sexo: '',
endereco: '',
bairro: '',
cidade: '',
estado: '',
sus: '',
}
}
editavel() {
this.isDesabilitado = false;
this.exibirEditar = false;
this.exibirAlterar = true;
this.visibilidade = "hidden";
this.exibirCadastrar = false;
}
salvo() {
this.isDesabilitado = true;
this.exibirEditar = true;
this.exibirAlterar = false;
this.exibirCadastrar = false;
}
cadastrar(aluno: Aluno) {
this.salvo();
this.alunoService.cadastrar(aluno)
.subscribe(
resposta => {
console.log (resposta);
this.mensagem = "Aluno cadastrado com sucesso!";
this.cor = "blue";
this.visibilidade = "visible";
},
err => {
this.mensagem = "Aluno NÃO cadastrado! Status:" + err.status;
this.cor = "red";
this.visibilidade = "visible";
}
);
}
alterar(aluno: Aluno) {
this.salvo();
this.alunoService.atualizar(aluno)
.subscribe(
resposta => {
console.log (resposta);
this.mensagem = "Aluno alterado com sucesso!";
this.cor = "blue";
this.visibilidade = "visible";
},
err => {
this.mensagem = "Aluno NÃO alterado! Status:" + err.status;
this.cor = "red";
this.visibilidade = "visible";
}
);
}
voltar(): void {
let link = ['/alunos/exibirtodos'];
this.router.navigate(link);
}
getVisibilidade() {
return this.visibilidade;
}
getCor() {
return this.cor;
}
buildForm(): void {
this.usuarioGroup = this.fb.group({
'nome': [this.usuarioForm.nome, [Validators.required, AutoValida.validaNome]],
'sexo': [this.usuarioForm.sexo, [Validators.required]],
'sus': [this.usuarioForm.sus, [Validators.required]],
'endereco': [this.usuarioForm.endereco, [Validators.required]],
'bairro': [this.usuarioForm.bairro, [Validators.required]],
'cidade': [this.usuarioForm.cidade, [Validators.required]],
'estado': [this.usuarioForm.estado, [Validators.required]]
});
}
formErrors = {
nome: '',
sexo: '',
endereco: '',
bairro: '',
cidade: '',
estado: '',
sus: '',
}
submitted: boolean = false;
onSubmit(){
this.submitted = true;
if (!this.usuarioGroup.valid){
return;
}
}
}
Error
Can't bind to 'formGroup' since it isn't a known property of 'form'. (" <div class="media-body">
<form class="form-horizontal" [ERROR ->][formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGroup.valid)" novalidate>
"): ExibirAlunoComponent#14:57
No provider for ControlContainer ("
<div class="media-body">
[ERROR ->]<form class="form-horizontal" [formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGrou"): ExibirAlunoComponent#14:27 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:
Can't bind to 'formGroup' since it isn't a known property of 'form'. (" <div class="media-body">
<form class="form-horizontal" [ERROR ->][formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGroup.valid)" novalidate>
"): ExibirAlunoComponent#14:57
No provider for ControlContainer ("
<div class="media-body">
[ERROR ->]<form class="form-horizontal" [formGroup]="usuarioGroup" role="form" (ngSubmit)="onSubmit(usuarioGrou"): ExibirAlunoComponent#14:27
I tried in various ways that came from my head, but I did not succeed.
Thank you very much in advance
The [] are missing in
formGroup="usuarioGroup"
It should be
[formGroup]="usuarioGroup"
The former creates an attribute with the string value 'usuarioGroup',
while the later binds the usuarioGroup field of the component to the formGroup property of the FormGroup directive.
Check if you has the ReactiveFormsModule imported in your module
I am new to Backbone JS and Question could be duplicate but I am not able to figure out the Problem. I need to handle form submit event in my application to use the default HTML5 validation. but unfortunately it's not working for me. below In securityTokenTmpl and securityQATmpl, i have form with submit button which is not firing submit event but click working fine.
view---------
var securityInfoView = Backbone.View.extend({
tagName : 'div',
className : 'security-info-wrap',
initialize : function() {
var self = this;
$('.application-content-wrap').append(self.$el);
this.$el.append(securityInfoTmpl(self.options.result.bankInfo.siteModel));
if (typeName === "TOKEN_ID" || typeName === "MULTI_LEVEL") {
self.$el.find('.security-info-wrap .content-wrap').html(securityTokenTmpl({
results : data
}));
}
if (typeName === "SECURITY_QUESTION") {
self.$el.find('.security-info-wrap .content-wrap').html(securityQATmpl({
results : data
}));
}
},
events : {
'submit' : 'submit'
},
submit : function(e) {
console.log("form submit");
e.preventDefault();
// there after HTML5 validation i want to make Rest call
}
});
securityQATmpl Template
{{#results}}
<div>
<form id="securityQA" method="POST">
<div class="row">
{{#fieldInfo}}
{{#questionAndAnswerValues}}
<div class="small-12 columns"><label class="addAccountLabel">{{question}}</label>
<input required type='{{responseFieldType}}' name='{{metaData}}'/>
</div>
{{/questionAndAnswerValues}}
{{/fieldInfo}}
</div>
</div>
<div class="row">
<div class="small-9 columns"></div>
<div class="small-3 columns"><input type="submit" class="button" value="Next"/>
</div>
</div>
</form>
<div class="clear"></div>
{{/results}}
securityTokenTmpl Template
{{#results}}
<div>
<form id="securityToken" method="POST">
{{#fieldInfo}}
<div class="row">
<div class="small-12 columns"><label class="addAccountLabel">{{displayString}}</label>
<input required type='{{responseFieldType}}' size='{{maximumLength}}' name="securityToken"/>
</div>
{{/fieldInfo}}
</div>
</div>
<div class="row">
<div class="small-9 columns"></div>
<div class="small-3 columns"><input type="submit" class="button" value="Next" /></div>
</form>
{{/results}}
There was an error in Templates i had a div in template which i was opening before form opening tag and closing before form closing tag it should be closed after form closing tag.
{{#results}}
<div>
<form id="securityToken" method="POST">
{{#fieldInfo}}
<div class="row">
<div class="small-12 columns"><label class="addAccountLabel">{{displayString}}</label>
<input required type='{{responseFieldType}}' size='{{maximumLength}}' name="securityToken"/>
</div>
</div>
{{/fieldInfo}}
<div class="row">
<div class="small-9 columns"></div>
<div class="small-3 columns"><input type="submit" class="button" value="Next" /></div>
</div>
</form>
</div>
{{results}}