jquery validate in modal with meteorjs - javascript

I trying to use the jQuery validate in modal but this doesn't work or don't call the action to validate the inputs.
this is my from into the modal, this are into a template name="modalregistro"
<form id="formregister" class="p-t-15 formregister" role="form" method="get">
<div class="row">
<div class="col-sm-12">
<div class="form-group form-group-default">
<label>Correo electrónico</label>
<input type="text" name="uname" placeholder="usuario#correo.com" class="form-control" required>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group form-group-default">
<label>Contraseña</label>
<input type="password" id="setPassword" name="user[password]" placeholder="Minimo de 8 Carácteres" class="form-control" required>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default">
<label>Validar contraseña</label>
<input type="password" name="user[password_confirmation]" placeholder="Minimo de 8 Carácteres" class="form-control" required>
</div>
</div>
</div>
<div class="row m-t-10">
<div class="col-md-6">
<p>Estoy de acuerdo con <strong>TP Landings</strong>, terminos y condiciones de uso y su Privacidad.</p>
</div>
<div class="col-md-6 text-right">
¿Ayuda? Contactar el soporte
</div>
</div>
<hr class="b-dashed b-grey">
<div class="row">
<div class="col-sm-6 col-xs-12">
<button data-dismiss="modal" class="btn btn-default btn-lg btn-large btn-block text-uppercase">Cancelar</button>
</div>
<div class="col-sm-6 col-xs-12">
<button id="btnHecho" class="text-uppercase btn btn-primary btn-lg btn-large btn-block btn-cons show-notification" type="submit">Crear cuenta</button>
</div>
</div>
</form>
I call this template into my Layout of the website
<template name="website">
<section class="website">
{{> navbarWebsite}}
</section>
{{> modallogin}}
{{> modalregistro}}
</template>
and this is my rendered
Template.website.rendered = function(){
$(function(){
$('.formregister').validate()
});
jQuery('.formregister').validate({
rules: {
"user[password]": {
minlength: 2
},
"user[password_confirmation]": {
minlength: 2,
equalTo : "#setPassword"
}
}
});
}
the jQuery validate are on, and the website.rendered too but I don't know why validate it.

You are calling the .validate() method twice on the same form...
$(function(){
$('.formregister').validate()
});
jQuery('.formregister').validate({
rules: { ...
.validate() is the initialization method and once called on a particular form, it cannot be called again. All subsequent calls will be ignored. Since your rules are declared from the second instance, they are ignored.
EDIT:
Perhaps you don't realize that you're using a class selector when your form only has an id.
The form only contains an id:
<form id="formregister" ...
But your selector is targeting class="formregister":
$('.formregister')
To select id="formregister", you'll need to use an id selector:
$('#formregister')

Related

angularjs not post my option list value to backend

i have a form as the following
<form method="POST" name="addItem" role="form" ng-submit="saveAdd()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Create Item</h4>
</div>
<div class="modal-body">
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<strong>Category : </strong>
<div class="form-group">
<select ng-model="form.cid" placeholder="Category" name="cid" class="form-control" required >
<option value="1">abc</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6">
<strong>Title : </strong>
<div class="form-group">
<input ng-model="form.title" type="text" placeholder="Name" name="title" class="form-control" required />
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<strong>Description : </strong>
<div class="form-group" >
<textarea ng-model="form.description" class="form-control" required>
</textarea>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6">
<strong>Alias : </strong>
<div class="form-group" >
<textarea ng-model="form.item_alias" class="form-control" required>
</textarea>
</div>
</div>
</div>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" ng-disabled="addItem.$invalid" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
and the angluarjs function will pass the data to laravel backend.
$scope.saveAdd = function(){
dataFactory.httpRequest('items','POST',{},$scope.form).then(function(data) {
$scope.data.push(data);
$(".modal").modal("hide");
});
}
the laravel backend error:
a foreign key constraint fails (`laravel_ang`.`items`, CONSTRAINT
`items_cid_foreign` FOREIGN KEY (`cid`) REFERENCES `category` (`id`)) (SQL:
insert into `items` (`title`, `description`, `item_alias`, `updated_at`,
`created_at`) values (test, 123, 23, 2016-11-12 09:41:35, 2016-11-12 09:41:35))
At laravel route, it is a resource controller:
Route::resource('items', 'ItemController');
In controller, the function:
public function store(Request $request)
{
$input = $request->all();
$create = Item::create($input);
return response($create);
}
Any ideas to include cid in insert statement?

Dynamic forms with BootstrapValidator

In an application using BootstrapValidator, I have this form :
<form method="post" action="save.php" role="form" id="form" class="form-horizontal">
<div class="children-list col-sm-12">
<div class="child col-sm-12">
<div class="col-sm-12">
<div class="form-group">
<label class="col-sm-4 control-label" for="guest">Option 1</label>
<div class="col-sm-4">
<div class="radio">
<label>
<input type="radio" data-bv-notempty="true" data-bv-notempty-message="test" name="guest[1][member_ski]" value="0"> Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" data-bv-notempty="true" data-bv-notempty-message="test" name="guest[1][member_ski]" value="1"> No
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" href="#" class="btn btn-sm btn-default add-child">Add a child</button>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" class="btn btn-sm btn-default" value="Send"/>
</div>
</div>
</form>
And this Javascript :
$(document).ready(function() {
$('form').bootstrapValidator().on('click', '.add-child', function() {
list = $('.children-list')[0];
first = $(list).find('.child:first');
clone = $(first).clone();
$.each(clone.find('input'), function(_, input) {
$(input).attr('name', 'guest[2][member_ski]');
$(input).attr('data-bv-field', 'guest[2][member_ski]');
});
$(list).append(clone);
$('form').bootstrapValidator('addField', clone);
});
$('.btn.remove-child').hide();
});
When I click on the button to add a new child, and I submit the form, the first validation is working but not the second. Is there a wat to make it working both?
I ran into the same problem and noticed that when the Validator enriches the fields during the add, the DOM node wasn't reflecting it. The fix was to replace each field I added with the changes that the validator had added
_.each($(":input", html), function(field){
this.validator.addField($(field));//where this.validator is the BootStrapValidator Instacne
$("#"+$(field).prop("id")).replaceWith(field);
}, this);

The angular controller shows the modal form is valid, when it's not

I have a form that's pops in a modal directive (bootstrap UI).
I have 2 input with html5 validation: "required".
In the controller I wanted to find out if the form is valid, then proceed to the server. After I ran into a problem with scopes (when I tried to reffer $scope.FormName.$valid), I found a solution by sending form name with the ng-click.
Then I saw that the controller code shows that the form is valid (even when the required field is empty).
How can I implement check if the form is valid before submitting it.
Here is my code:
form in html
<form name="EmailForm">
<div class="row">
<div class="col-md-1 lbl_hdr">
date:
</div>
<div class="col-md-1">
{{Curr_Date | date:'dd/MM/yyyy'}}
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-1">
</div>
</div>
<div class="row">
<div class="col-md-1 lbl_hdr">
from:
</div>
<div class="col-md-1">
<input type="email" required placeholder="email" />
<br />
<br />
</div>
</div>
<div class="row">
<div class="col-md-3 lbl_hdr">
message:
</div>
</div>
<div class="row">
<div class="col-md-1">
<textarea class="msg_text" required rows="5"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-9">
<button type="submit" ng-click="SendEmail(EmailForm)" class="btn btn-primary btn_padded_top">send</button>
<button type="button" class="btn btn-primary btn_padded_top pull-left" ng-click="$close();">cancel</button>
</div>
</div>
</div>
</div>
</form>
controller
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: '/js/app/templates/msg_modal.html',
controller: function ($scope) {
$scope.Curr_Date = new Date();
$scope.SendEmail = function (EmailForm) {
if (EmailForm.$valid) {
EmailService.sendEmail("sdsd").success(
function (data) {
});
}//if valid
};
},
size: size
});
};
"if (EmailForm.$valid)" = always true
I had the same problem and turns out that the form elements must have ng-model in order for the AngularJS validation to kick in.
So just add it to all elements and it should be all good, e.g.
<input type="email" required placeholder="email" ng-model="email" />
Try using ng-submit and sending EmailForm.$valid in the arguments.
<form name="EmailForm" ng-submit="SendEmail(EmailForm.$valid)">
<div class="row">
<div class="col-md-1 lbl_hdr">
date:
</div>
<div class="col-md-1">
{{Curr_Date | date:'dd/MM/yyyy'}}
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-1">
</div>
</div>
<div class="row">
<div class="col-md-1 lbl_hdr">
from:
</div>
<div class="col-md-1">
<input type="email" required placeholder="email" />
<br />
<br />
</div>
</div>
<div class="row">
<div class="col-md-3 lbl_hdr">
message:
</div>
</div>
<div class="row">
<div class="col-md-1">
<textarea class="msg_text" required rows="5"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-9">
<button type="submit" class="btn btn-primary btn_padded_top">send</button>
<button type="button" class="btn btn-primary btn_padded_top pull-left" ng-click="$close();">cancel</button>
</div>
</div>
</div>
</div>
</form>
Then:
$scope.openModal = function () {
var modalInstance = $modal.open({
templateUrl: '/js/app/templates/msg_modal.html',
controller: function ($scope) {
$scope.Curr_Date = new Date();
$scope.SendEmail = function (isValid) {
if (isValid) {
EmailService.sendEmail("sdsd").success(
function (data) {
});
}//if valid
};
},
size: size
});
};

JQuery .click function only works after second click if I close a modal

i have a page where I have two buttons, one that opens a modal, and another one that only submits.
I have a .click event on the second button. If i go on the page and click the second button the click event goes fine, BUT if i first open the modal, close it and then i hit the second button, the first time does nothing and the second time it fires the .click event.
I would like to always fire the click event.
this is my code
$(document).ready(function(){
var focusout = false;
$(".prueba").click(function () {
if (focusout == false) {
focusout = true;
return;
}
});
var validator =$('#form1').validate(
{
ignore: "",
rules: {
parametros: {
required: function() { return focusout == true; },
},
terminos: {
required: function() { return focusout == true; },
}
},
highlight: function(element) {
$(element).closest('.grupo').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.grupo').removeClass('has-error');
}
});
$(".cancel").click(function() {
validator.resetForm();
});
}); // end document.ready
button 1:
<button type="submit" class="btn btn-primary" name="nueva_articulo"><i class="icon-plus"></i> Nuevo Item</button>
button 2:
<button type="submit" class="btn btn-primary prueba" name="buscar">Buscar</button>
full form:
<form action="" method="post" id="form1" enctype="multipart/form-data">
<p>
<button type="submit" class="btn btn-primary" name="nueva_articulo"><i class="icon-plus"></i> Nuevo Item</button>
<button type="submit" class="btn btn-primary" name="carga_masiva"><i class="icon-arrow-up"></i> Carga Masiva</button>
</p>
<br>
<div class="col-lg-1 grupo">
</div>
<div class="col-lg-10 grupo">
<div class="panel panel-default pagination-centered">
<div class="panel-heading">Búsqueda en Catálogo</div>
<div class="panel-body">
<div class="form-group ">
<div class="col-lg-6 grupo">
<input type="text" class="form-control " id="terminos" name="terminos" placeholder="Términos de búsqueda">
</div>
<div class="col-lg-6 grupo">
<select id="e1" name="parametros" style=" width:80%">
<option></option>
<option value="1" >Autor</option>
<option value="2" >Título</option>
</select>
</div>
</div>
<br> <br>
<div style="text-align:center">
<button type="submit" class="btn btn-primary prueba" name="buscar">Buscar</button>
</div>
</div>
</div>
</div>
<div class="col-lg-1 grupo">
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" name="myModal" data-backdrop="static" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-wide">
<div class="modal-content">
<div class="modal-header">
<button type="submit" class="close cancel" data-dismiss="modal" aria-hidden="true">×</button>
{if isset($smarty.post.nueva_articulo) }
<h4 class="modal-title">Nueva Articulo</h4>
{/if} </div>
<div class="modal-body">
{if isset($smarty.post.nueva_articulo) }
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="art_titulo" class="control-label">Título</label>
<input type="text" class="form-control input-sm" name="art_titulo">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="art_enlace" class="control-label">Enlace</label>
<input type="text" class="form-control input-sm" name="art_enlace">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="aut_id" class="control-label">Autor(es)</label>
<input type='hidden' id='e13' name="autores" style='width:100%'/>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="art_contenido" class="control-label">Contenido</label>
<textarea class="form-control input-sm" name="art_contenido" rows="5" ></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="etiquetas" class="control-label">Etiquetas</label>
<input type="text" id="e12" name="etiquetas" style="width:100%">
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<label for="foto" class="control-label">Imagen</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Buscar… <input type="file" name="foto">
</span>
</span>
<input type="text" class="form-control" name="nombre" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-12 grupo">
<div class="checkbox">
<label>
<input type="checkbox" name="rating" value="si"> Habilitar Rating y Reviews
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="redes" value="si"> Habilitar Compatir en Redes Sociales
</label>
</div>
</div>
</div>
{/if}
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default cancel" data-dismiss="modal" name="cerrar">Cerrar</button>
{if isset($smarty.post.nueva_articulo) }
<button type="submit" class="btn btn-primary" name="insertar_articulo">Guardar Cambios</button>
{/if}
</div>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
<!-- /.modal -->
</form>
They are both of type submit. You should only have 1 submit button on a form
Button 1 could just be a button
<button class="btn btn-primary" name="nueva_articulo"><i class="icon-plus"></i> Nuevo Item</button>
If you want, you can create a Form Object in javascript and generate it dynamically. That will do that you don't need to depend of the submit and forms, just fill the form object with the inputs that you want programatically (that even accept files or images).
But anyway, it seems that you have more than one click events on the same button if the one you want is triggering at the second attempt. You could try to play with event.preventDefault or $.unbind.
As you said taht you need to submit the inputs of the modal, try to place the content of the modal inside the tag and remove the submit type of one of the buttons.

Why form serialize does not work in this case?

I have a form which I wanna send via AJAX so I'll use serialize jQuery function.
This is the code (not all the elements has "name", but anyway the alert should display something):
http://jsfiddle.net/T6Rz3/2/
JS
$('#add-producto').click(function (e) {
alert($('#datos-add').serialize())
$.ajax({
type: "POST",
url: "insertar.php",
data: $('#datos-add').serialize(),
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
HTML
<form id="#datos-add">
<div class="form-horizontal">
<div class="modal modal-block">
<div class="modal-header">
<h3>Añadir productos</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label">Marca</label>
<div class="controls">
<input type="text" name="marca" id="marca" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label">Producto</label>
<div class="controls">
<input type="text" name="descr" id="descr" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label">Tallajes</label>
<div class="controls controls-row">
<input id="tallajes" value="España">
</div>
</div>
<div class="control-group">
<label class="control-label">Referencias</label>
<div class="controls controls-row">
<input id="referencias" class="input-xlarge">
</div>
</div>
<div class="control-group">
<label class="control-label">Número de tallas</label>
<div class="controls controls-row">
<input type="number" min="1" max="99" value="5" id="numero-tallas" class="span1">
</div>
</div>
<div class="control-group">
<label class="control-label">Primera talla</label>
<div class="controls controls-row">
<input type="text" id="primera-talla" value="XS" class="span1">
</div>
</div>
</div>
<div class="modal-footer">
<div class="btn-group">
<button id="borrar" class="btn" type="button">Borrar todo</button>
<button id="generar" class="btn btn-primary" type="button">Generar tabla</button>
</div>
</div>
</div>
<div class="form-horizontal">
<div id="formulario-medidas" class="modal modal-block">
<div class="modal-header">
<h4>Tabla de medidas</h4>
</div>
<div class="modal-body">
<table id="tabla-medidas" class="table table-bordered"></table>
</div>
<div class="modal-footer">
<button id="medidas-completadas" class="btn btn-success" type="button">Medidas completadas</button>
</div>
</div>
<div id="formulario-tallajes" class="modal modal-block">
<div class="modal-header">
<h4>Tabla de tallajes</h4>
</div>
<div class="modal-body">
<table id="tabla-tallajes" class="table table-bordered"></table>
</div>
<div class="modal-footer">
<button id="add-producto" class="btn btn-block btn-large btn-danger" type="button">Añadir producto</button>
</div>
</div>
</div>
</div>
</form>
Do you see what I'm doing wrong?
Any tip, advide or help will be appreciated, and if you need more info, let me know and I'll edit the post.
Your form id is "datos-añadir" but your JavaScript refers to "datos-add".
Here is a jsfiddle fork that works. All I did was fix the reference:
$('#add-producto').click(function (e) {
var $form = $('#datos-añadir');
alert($form.serialize());
return false;
Fist of all, there is a typo. It should be <form id="datos-add"> instead of <form id="#datos-add">.
But I also think you are serializing it the wrong way.
When you do a POST ajax call, you shoud use .serializeArray(), instead of .serialize().
The .serialize() will join all key/values like a query string.
The .serializeArray() will include all key/values in the request.
In short, try:
$('#add-producto').click(function (e) {
$.ajax({
type: "POST",
url: "insertar.php",
data: $('#datos-add').serializeArray(),
success: function (data) {
alert(data);
}
});
e.preventDefault();
});

Categories