Validate modal-form with jquery - javascript

i have a problem with validate modal-form with jquery. If i click the button nothing happens. Instead if i write inside an input form and i click on the button it convalidate.It's like the code didn't see the javascript. I have locked the solutions of my problem many times but i can't find them. I have a separate file javascript and i put it in the head of the page where is the modal. I put also the links for the jquery library from google.
I noticed that when i open the page for the first time and press the button to validate it validate without check the parameters that i write in the script and the other times when i click the button nothing happens.
Here the links of the libraries:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
This is my modal contain the form:
<!-- Modale -->
<div class="modal fade" id="modaleReg" tabindex="-1" role="dialog" aria-labelledby="modale" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-sm" id="modifyMod" role="document">
<!-- Contenitore modale -->
<div class="modal-content">
<!-- Header modale -->
<div class="modal-header">
<h5 class="modal-title" id="titMod">modale</h5>
<span class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true">×</span>
</div>
<!-- Body modale -->
<div class="modal-body">
<!--Form per iscrizione -->
<form action="#" id="form">
<div class="form-group">
<label for="name">Nome</label>
<input id="name" name="name" type="text" class="form-control" placeholder="Nome">
</div>
<div class="form-group">
<label for="surname">Cognome</label>
<input id="surname" name="surname" type="text" class="form-control" placeholder="Cognome">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input id="email" name="email" type="email" class="form-control" aria-describedby="emailHelp" placeholder="Email">
<small id="emailHelp" class="form-text text-muted">Non condivideremo mai la tua email con nessuno.</small>
</div>
<div class="form-group">
<label for="password">Crea password</label>
<input id="password" name="password" type="password" class="form-control">
</div>
<div class="form-group">
<label for="confermaPsw">Conferma password</label>
<input id="confermaPsw" name="confermaPsw" type="password" class="form-control">
</div>
<button type="submit" class="btn btn-primary btnmod">Continua</button>
</form>
</div>
<!-- Footer modale -->
<div class="modal-footer">
</div>
<!--Fine contenitore modale -->
</div>
</div>
</div><!-- Fine modale -->
This is my javascript code:
$(document).ready(function() {
// Selezione form e definizione dei metodi di validazione
$("#form").validate({
// Definiamo le nostre regole di validazione
rules : {
// name - nome del campo di input da validare
name : {
// Definiamo il campo name come obbligatorio
required : true
},
password : {
required : true,
// Settiamo la lunghezza minima e massima per il campo password
minlength : 5,
maxlength : 8
},
email : {
required : true,
// Definiamo il campo email come un campo di tipo email
email : true
}
},
// Personalizzimao i mesasggi di errore
messages: {
name: "Inserisci il nome",
password: {
required: "Inserisci una password password",
minlength: "La password deve essere lunga minimo 5 caratteri",
maxlength: "La password deve essere lunga al massimo 8 caratteri"
},
email: "Inserisci la tua email"
},
});
});

Can you please add below code with validate function and try again
$(document).ready(function() {
// Selezione form e definizione dei metodi di validazione
$("#form").validate({
// Definiamo le nostre regole di validazione
rules : {
// name - nome del campo di input da validare
name : {
// Definiamo il campo name come obbligatorio
required : true
},
password : {
required : true,
// Settiamo la lunghezza minima e massima per il campo password
minlength : 5,
maxlength : 8
},
email : {
required : true,
// Definiamo il campo email come un campo di tipo email
email : true
}
},
// Personalizzimao i mesasggi di errore
messages: {
name: "Inserisci il nome",
password: {
required: "Inserisci una password password",
minlength: "La password deve essere lunga minimo 5 caratteri",
maxlength: "La password deve essere lunga al massimo 8 caratteri"
},
email: "Inserisci la tua email"
},
submitHandler: function(form) {
// code to submit the form
}
});
});
You can also try to add you code in modal box and it will works fine

Related

Trouble with validation in dynamic forms with jquery + razor pages

I'm working with a form that consists in the following idea, I have courses, each course contains one or n modules.
I created a form that contains a course name and a module. After you saved the module (Click on guardar modulo) the button to add an additional module is enabled, so you can add another one and save it.
By clicking on guardar modulo the modules are saved in an array.
Then, clicking in Crear curso takes the array of modules and the course name and perform a POST. So I saved the course plus its modules.
After completing the fields, if guardar modulo is pressed. The modulo will be stored as explained before.
The issue is that validation is only applied when creating the course (Clicking in crear curso button)
My idea is that validation must be applied when I click on guardar modulo too but It is not applying it.
For simplicity I added the first field of module in the validation (moduleName field).
Here's my code
Index.cshtml
<div class="row">
<div class="col-md-4">
<partial name="_AgregarModuloModal" />
<form>
<div class="form-group">
<label for="cursoName">Nombre Curso</label>
<input type="text"
id="cursoName"
name="cursoName"
class="form-control"
placeholder="Ingrese el nombre del curso"
required />
</div>
<div class="accordion" id="accordion">
<partial name="_ModuloForm" />
</div>
<div class="alert alert-success alert-dismissible fade" id="modulo-added-alert" role="alert">
El módulo ha sido agregado al curso
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<br />
<button type="button" id="showModalForm"> Agregar otro módulo</button>
<br />
<button type="submit" id="submitBtn" class="btn btn-primary">Crear curso</button>
</form>
</div>
</div>
<div>
<a asp-page="Index">Volver</a>
</div>
#section Scripts {
<script>
var modulos = [];
var otherModules = 0;
$(function () {
$('form').validate({
rules: {
cursoName: {
required: true,
minlength: 4,
maxlength: 16
},
moduloName: {
required: true,
minlength: 4,
maxlength: 16
}
},
messages: {
cursoName: {
required: 'El campo es obligatorio',
minlength: 'Debe tener al menos 4 caracteres',
maxlength: 'No debe superar 16 caracteres'
},
moduloName: {
required: 'El campo es obligatorio',
minlength: 'Debe tener al menos 4 caracteres',
maxlength: 'No debe superar 16 caracteres'
}
}
});
var previousForm = $('.card-0').clone(true);
var previousModal = $('#guardar-modulo-modal').clone(true);
$('#modulo-added-alert').css('display', 'none');
$('#showModalForm').prop('disabled', true);
$('#confirm-add-modulo').click(function () {
var id = 'modulo-0';
var modName = $('#moduloName').val();
var modDescripcion = $('#moduloDescripcion').val();
var modEncuentros = $('#moduloEncuentros').val();
var modCupo = $('#moduloCupo').val();
var modCupoTolerancia = $('#moduloCupoTolerancia').val();
var modFechaInicio = $('#moduloFechaInicio').val();
var modFechaFin = $('#moduloFechaFin').val();
var modFechaLimite = $('#moduloFechaLimiteInscripcion').val();
var modalidad = $('#moduloModalidad :selected').text();
// check modules here .. Refactor repeated lines.
const idx = modulos.findIndex(function (mod) {
return mod.id === id
});
if (idx !== -1) {
modulos[idx].nombreModulo = modName;
modulos[idx].descripcionModulo = modDescripcion;
modulos[idx].encuentrosModulo = modEncuentros;
modulos[idx].cupoModulo = modCupo;
modulos[idx].cupoTolerancia = modCupoTolerancia;
modulos[idx].fechaInicio = modFechaInicio;
modulos[idx].fechaFin = modFechaFin;
modulos[idx].fechaLimite = modFechaLimite;
modulos[idx].modalidadModulo = modalidad;
} else {
modulos.push({
id: 'modulo-0',
nombreModulo: modName,
descripcionModulo: modDescripcion,
encuentrosModulo: modEncuentros,
cupoModulo: modCupo,
cupoTolerancia: modCupoTolerancia,
fechaInicio: modFechaInicio,
fechaFin: modFechaFin,
fechaLimite: modFechaLimite,
modalidadModulo: modalidad
});
}
// bad smell --> codigo repetido line --> 190
$('#guardar-modulo-modal').modal('hide');
$('#btn-guardar-modulo').text('Actualizar');
$('#showModalForm').prop('disabled', false);
$('#collapseModButton').addClass('collapsed');
$('#collapseModulo').addClass('collapse');
$('#collapseModulo').removeClass('show');
$('#modulo-added-alert').css('display', 'block');
});
$('#btn-guardar-modulo').click(function () {
// save modulo but first perform validation
$('form').validate({
rules: {
moduloName: {
required: true,
minlength: 4,
maxlength: 16
}
},
messages: {
moduloName: {
required: 'El campo es obligatorio',
minlength: 'Debe tener al menos 4 caracteres',
maxlength: 'No debe superar 16 caracteres'
}
}
});
$('#guardar-modulo-modal').modal('show');
});
$('#showModalForm').click(function (evt) {
evt.preventDefault();
agregarNuevoModulo();
});
function agregarNuevoModulo() {
var newModuloForm = otherModules === 0
? previousForm.clone(true).insertAfter($('.card-0'))
: previousForm.clone(true).insertAfter($('.card-0' + otherModules));
otherModules += 1;
$('#showModalForm').prop('disabled', true);
crearModalAgregarModulo(otherModules);
$.each($('input', newModuloForm), function (i, item) {
$(item).attr('id', $(item).attr('id') + otherModules);
$(item).attr('name', $(item).attr('name') + otherModules);
});
$.each($('select', newModuloForm), function (i, item) {
$(item).attr('id', $(item).attr('id') + otherModules);
$(item).attr('name', $(item).attr('name') + otherModules);
});
var btnAddModulo = $(newModuloForm).find('#btn-agregar-modulo');
$(btnAddModulo).attr('id', $(btnAddModulo).attr('id') + otherModules);
$(newModuloForm).attr('class', $('.card-0').attr('class') + otherModules);
var collapseModuloButton = ($(newModuloForm).find("#collapseModButton"));
$(collapseModuloButton).attr('id', $(collapseModuloButton).attr('id') + otherModules);
$(collapseModuloButton).attr('data-target', '#collapseModulo' + otherModules);
var collapseForm = $(newModuloForm).find("#collapseModulo")
$(collapseForm).attr('id', $(collapseForm).attr('id') + otherModules);
var displayModal = $(newModuloForm).find('#btn-guardar-modulo');
$(displayModal).attr('id', $(displayModal).attr('id') + otherModules);
$(displayModal).attr('data-target', '#guardar-modulo-modal' + otherModules);
}
function crearModalAgregarModulo(otherModules) {
var previousModelId = (otherModules - 1) > 0 ? otherModules - 1 : '';
var clonedModal = previousModal.clone(true).insertAfter('#guardar-modulo-modal' + previousModelId);
$(clonedModal).attr('id', $(clonedModal).attr('id') + otherModules);
var saveModuloBtn = $(clonedModal).find('#confirm-add-modulo');
$(saveModuloBtn).attr('id', $(saveModuloBtn).attr('id') + otherModules);
$(saveModuloBtn).click(function () {
var modName = $('#moduloName' + otherModules).val();
var modDescripcion = $('#moduloDescripcion' + otherModules).val();
var modEncuentros = $('#moduloEncuentros' + otherModules).val();
var modCupo = $('#moduloCupo' + otherModules).val();
var modCupoTolerancia = $('#moduloCupoTolerancia' + otherModules).val();
var modFechaInicio = $('#moduloFechaInicio' + otherModules).val();
var modFechaFin = $('#moduloFechaFin' + otherModules).val();
var modFechaLimite = $('#moduloFechaLimiteInscripcion' + otherModules).val();
var modalidad = $('#moduloModalidad' + otherModules + ':selected').text();
var id = 'modulo-' + otherModules;
const idx = modulos.findIndex(function (mod) {
return mod.id === id
});
if (idx !== -1) {
modulos[idx].nombreModulo = modName;
modulos[idx].descripcionModulo = modDescripcion;
modulos[idx].encuentrosModulo = modEncuentros;
modulos[idx].cupoModulo = modCupo;
modulos[idx].cupoTolerancia = modCupoTolerancia;
modulos[idx].fechaInicio = modFechaInicio;
modulos[idx].fechaFin = modFechaFin;
modulos[idx].fechaLimite = modFechaLimite;
modulos[idx].modalidadModulo = modalidad;
} else {
modulos.push({
id: 'modulo-' + otherModules,
nombreModulo: modName,
descripcionModulo: modDescripcion,
encuentrosModulo: modEncuentros,
cupoModulo: modCupo,
cupoTolerancia: modCupoTolerancia,
fechaInicio: modFechaInicio,
fechaFin: modFechaFin,
fechaLimite: modFechaLimite,
modalidadModulo: modalidad
});
}
$('#guardar-modulo-modal' + otherModules).modal('hide');
$('#btn-guardar-modulo' + otherModules).text('Actualizar');
$('#showModalForm').prop('disabled', false);
$('#collapseModButton' + otherModules).addClass('collapsed');
$('#collapseModulo' + otherModules).addClass('collapse');
$('#collapseModulo' + otherModules).removeClass('show');
$('#modulo-added-alert').css('display', 'block');
});
}
});
</script>
}
_ModuloForm.cschtml
<div class="card card-0">
<div class="card-header" id="moduloForm">
<h5 class="mb-0">
<button class="btn btn-link" id="collapseModButton" type="button" data-toggle="collapse" data-target="#collapseModulo" aria-expanded="true" aria-controls="collapseOne">
Módulo
</button>
</h5>
</div>
<div id="collapseModulo" class="collapse show" aria-labelledby="moduloForm" data-parent="#accordion">
<div class="card-body">
<div class="form-group">
<label for="moduloName">Nombre Modulo</label>
<input type="text" id="moduloName" name="moduloName" class="form-control" placeholder="Ingrese el nombre del módulo" required />
</div>
<div class="form-group">
<label for="moduloDescripcion">Referencia</label>
<input type="text" id="moduloDescripcion" name="moduloDescripcion" class="form-control" placeholder="Ingrese la descripción del modulo" required />
</div>
<div class="form-group">
<label for="moduloEncuentros">Cantidad de encuentros</label>
<input type="number" id="moduloEncuentros" name="moduloEncuentros" class="form-control" placeholder="Ingrese la cantidad de encuentros" required />
</div>
<div class="form-group">
<label for="moduloCupo">Cupo</label>
<input type="number" id="moduloCupo" name="moduloCupo" class="form-control" placeholder="Ingrese el cupo máximo" required />
</div>
<div class="form-group">
<label for="moduloCupoTolerancia">Cupo Tolerancia</label>
<input type="number" id="moduloCupoTolerancia" name="moduloCupoTolerancia" class="form-control" placeholder="Ingrese el cupo de tolerancia" required />
</div>
<div class="form-group">
<label for="moduloFechaInicio">Fecha comienzo</label>
<input type="date" id="moduloFechaInicio" name="moduloFechaInicio" class="form-control" placeholder="Ingrese la fecha de inicio del modulo" required />
</div>
<div class="form-group">
<label for="moduloFechaFin">Fecha finalización</label>
<input type="date" id="moduloFechaFin" name="moduloFechaFin" class="form-control" placeholder="Ingrese la fecha de finalización de módulo" required/>
</div>
<div class="form-group">
<label for="moduloFechaLimiteInscripcion">Fecha límite de inscripción</label>
<input type="date" id="moduloFechaLimiteInscripcion" name="moduloFechaLimiteInscripcion" class="form-control" placeholder="Ingrese la fecha de limite de inscripción" />
</div>
<div class="form-group">
<label for="moduloModalidad">Modalidad</label>
<select id="moduloModalidad" name="moduloModalidad" class="form-control">
<option value="Presencial">Presencial</option>
<option value="Presencial">Virtual</option>
</select>
</div>
<div class="form-group">
<label for="addNewModulo">Guardar Módulo</label>
<button type="button"
class="btn btn-primary button_lenga_primary"
id="btn-guardar-modulo">
Guardar Modulo
</button>
</div>
</div>
</div>
</div>
It's working but partially, if I click on Crear Curso the validation is applied (see image below). But I need to perform a validation in each module when I click on Guardar modulo
Is this possible ? I know code is a mess but I'm going to refactor it after I solve the validation issue.
Because the type of Guardar modulo is button instead of submit, So if you want to show the error message, you need add $("form").valid() in $('#btn-guardar-modulo').click(function () {}) method.
$('#btn-guardar-modulo').click(function () {
// save modulo but first perform validation
$('form').validate({
rules: {
moduloName: {
required: true,
minlength: 4,
maxlength: 16
}
},
messages: {
moduloName: {
required: 'El campo es obligatorio',
minlength: 'Debe tener al menos 4 caracteres',
maxlength: 'No debe superar 16 caracteres'
}
}
});
if($("form").valid()){
//.. modules are saved in an array......
}else{
//.......
}
});

Test if a function with multiple if/else blocks return true or false in javascript

I'm not sure if this question has been asked before or not,
I'm trying to make a validation form using Javascript.
My question is: is there any way to test if my functions validateEmailLogin() and validatePsswordLogin() returns true or false in all if/else blocks, so I can test in the function isValide() whether the two functions return true or false and do a treatment.
Ps: it's a bit messy code and any suggestions to reduce it and make it cleaner are welcome.
Here's my html and js code :
function validateEmailLogin() {
var emailInput = document.getElementById("email").value;
var emailMessageEmpty = document.getElementById("emailEmptyMessage");
var emailMessagePatern = document.getElementById("emailEmptyPaternMessage");
if (emailInput == "") {
emailMessageEmpty.classList.remove("d-none");
} else {
emailMessageEmpty.classList.add("d-none");
}
if (!(emailInput.includes("#") && emailInput.includes("."))) {
emailMessagePatern.classList.remove("d-none");
} else {
emailMessagePatern.classList.add("d-none");
}
}
function validatePsswordLogin() {
var passwordInput = document.getElementById("password").value;
var passwordMessageEmpty = document.getElementById("passwordEmptyMessage");
var passwordMessagePatern = document.getElementById("passwordPaternMessage");
var Patern = /^[A-Za-z]+$/;
if (passwordInput == "") {
passwordMessageEmpty.classList.remove("d-none");
} else {
passwordMessageEmpty.classList.add("d-none");
}
if ((passwordInput.length < 8)) {
passwordMessagePatern.classList.remove("d-none");
} else {
passwordMessagePatern.classList.add("d-none");
}
if (Patern.test(passwordInput)) {
passwordMessagePatern.classList.remove("d-none");
} else {
passwordMessagePatern.classList.add("d-none");
}
}
function isValide() {
if (validateEmailLogin() && validatePsswordLogin()) {
window.location.href = "file:///C:/Users/amin/Desktop/Projet-edits/Projet/home.html";
return false;
} else {
alert('check your credentials');
}
}
My HTML
form name="loginForm" method="POST">
<div class="form-group">
<label for="email">Email <sup class="text-danger">*</sup></label>
<input type="email" class="form-control" id="email" onfocusout="validateEmailLogin()" name="loginEmail" placeholder="Entrer votre email" >
<p id="emailEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Le champ email est vide</small></p>
<p id="emailEmptyPaternMessage" class="text-danger mb-0 mt-1 d-none"><small>Le champ email Doit contenir '#' et '.'</small></p>
</div>
<div class="form-group">
<label for="password">Mot de passe <sup class="text-danger">*</sup></label>
<input type="password" class="form-control" id="password" onfocusout="validatePsswordLogin()" name="login-password" placeholder="Mot de passe" >
<p id="passwordEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Mot de passe est vide</small></p>
<p id="passwordPaternMessage" class="text-danger mt-1 mb-0 d-none">
<small>Les mots de passe doivent contenir au moins 8 caractères, y compris des majuscules, des minuscules et des chiffres.</small></p>
</div>
<button onclick="return isValide()" type="submit" class="btn btn-primary-color w-100">Connecter</button>
<p class="mt-2">Pas encore membre? S'enregistrer</p>
</form>
I like your code!
The message holders = nice!
I've made some modifications:
added valid flag initialized as true, set to false when not valid, and returned from both validate functions
changed isValide to valide and removed the return
removed the <form>
removed type=submit from button
button just calls valide - whatever is needed to be done - from there
commented out change of href for demonstration - uncomment when ready, actually, use location.replace(URL); instead of window.location.href = URL;
Notes:
your URL is a local file...
the email validator function is not complete (x#.com#.com - passes, for example...)
function validateEmailLogin() {
var valid=true;
var emailInput = document.getElementById("email").value;
var emailMessageEmpty = document.getElementById("emailEmptyMessage");
var emailMessagePatern = document.getElementById("emailEmptyPaternMessage");
if (emailInput == "") {
emailMessageEmpty.classList.remove("d-none");
valid=false;
} else {
emailMessageEmpty.classList.add("d-none");
}
if (!(emailInput.includes("#") && emailInput.includes("."))) {
emailMessagePatern.classList.remove("d-none");
valid=false;
} else {
emailMessagePatern.classList.add("d-none");
}
return valid;
}
function validatePsswordLogin() {
var valid=true;
var passwordInput = document.getElementById("password").value;
var passwordMessageEmpty = document.getElementById("passwordEmptyMessage");
var passwordMessagePatern = document.getElementById("passwordPaternMessage");
var Patern = /^[A-Za-z]+$/;
if (passwordInput == "") {
passwordMessageEmpty.classList.remove("d-none");
valid=false;
} else {
passwordMessageEmpty.classList.add("d-none");
}
if ((passwordInput.length < 8)) {
passwordMessagePatern.classList.remove("d-none");
valid=false;
} else {
passwordMessagePatern.classList.add("d-none");
}
if (Patern.test(passwordInput)) {
passwordMessagePatern.classList.remove("d-none");
valid=false;
} else {
passwordMessagePatern.classList.add("d-none");
}
return valid;
}
function valide() {
if (validateEmailLogin() && validatePsswordLogin()) {
alert("valid");
// window.location.href = "file:///C:/Users/amin/Desktop/Projet-edits/Projet/home.html";
} else {
alert('check your credentials');
}
}
.d-none {
display:none;
}
<!-- form name="loginForm" method="POST" -->
<div class="form-group">
<label for="email">Email <sup class="text-danger">*</sup></label>
<input type="email" class="form-control" id="email" onfocusout="validateEmailLogin()" name="loginEmail" placeholder="Entrer votre email" >
<p id="emailEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Le champ email est vide</small></p>
<p id="emailEmptyPaternMessage" class="text-danger mb-0 mt-1 d-none"><small>Le champ email Doit contenir '#' et '.'</small></p>
</div>
<div class="form-group">
<label for="password">Mot de passe <sup class="text-danger">*</sup></label>
<input type="password" class="form-control" id="password" onfocusout="validatePsswordLogin()" name="login-password" placeholder="Mot de passe" >
<p id="passwordEmptyMessage" class="text-danger mt-1 mb-0 d-none"><small>Mot de passe est vide</small></p>
<p id="passwordPaternMessage" class="text-danger mt-1 mb-0 d-none">
<small>Les mots de passe doivent contenir au moins 8 caractères, y compris des majuscules, des minuscules et des chiffres.</small>
</p>
</div>
<button onclick="valide()" xtype="submit" class="btn btn-primary-color w-100">Connecter</button>
<p class="mt-2">Pas encore membre? S'enregistrer</p>
<!-- /form -->

How to get a ID in a modal coming by dataTable?

My question is, I'm posting an ID into a modal, but when I click in a datepicker inside modal, it gives me as an undefined value, it seems that I'm losing the ID somewhere, could you help me? Here is my code:
Here is my modal HTML:
<div class="modal fade" id="modalUpdatePeriodico" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered " role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Prontuário médico</h4>
<!-- para pegar o id do meu campo -->
<input type="hidden" id="hiddenIdPeriodic"/>
</div>
<div class="modal-body">
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- Inicio do Formulario de Pesquisa -->
<form id="formUpdatePeriodico" enctype="multipart/form-data" action="#" method="POST">
<!-- Form Data e Qtde dias -->
<div class="form-row">
<div class="form-group col-md-6">
<label for="dateExam">Data da Realização</label>
<input type="text" class="form-control datepicker-calendar" id="dateExam" name="dateExam">
</div>
<div class="form-group col-md-6">
<label for="statusExam">Status</label>
<select class="form-control select2" id="statusExam" name="statusExam">
<option value="1">Inapto</option>
<option value="2">Apto</option>
</select>
</div>
</div>
</form>
<!-- Fim do Formulario de Pesquisa -->
</div>
<!--/.col (right) -->
</div>
<!-- /.row -->
</div>
<div class="modal-footer">
<button
type="button"
id="btnSavePeriodic"
class="btn btn-success"
data-dismiss="modal"
onclick="saveEmpRestrictions('periodics', inputMatriculaAtes, dateExam, statusExam, hiddenIdPeriodic, examType);">
Salvar
</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Fechar</button>
</div>
</div>
</div>
Here is my DataTable JS code:
function tbPeriodic() {
// Definição do id da tabela como um dataTable
$("#tbPeriodico").DataTable({
"ajax": "webservices/ws_medicalRecord/tables/tb_medicalRecords.php?action=per&matriculaOp=" + <?php echo $matricula; ?>,
sorting: false,
"columns":
[
{ "data": "id" ,
render: function(data, type, row) { // Função para link de download dos arquivos que foram "upados" no formulário.
data = '' + row.id + '';
return data;
}
},
{ "data": "ult_exame" },
{ "data": "tipo_exame" },
{ "data": "status_exame" },
{ "data": "prox_exame" }
]
});
}
Here is my function to post my id into a input hidden:
$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
console.log(id);
var modal = $(this);
modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
});
Here is my datepicker function:
$('.datepicker-calendar').datepicker({
autoclose: true
});
So, when I input a date from my datepicker the console shows me undefined, could you help me?
Thanks a lot!
I think you are confused here and there are 2 things happening. Or I should say there is one thing happening and the other step is missing. I am going to try and clarify this for you.
#1
The undefined is happening because you are not getting the value of id correctly. Add a class clickme to your dataTable <a> like below and get rid of the modal call.
dataTable
data = '<a class="clickme" href="#" data-id="' + row.id + '" id="' + row.id + '">' + row.id + '</a>';
Then get rid of
$("#modalUpdatePeriodico").on('show.bs.modal', function (event) {
var callModal = $(event.relatedTarget); // Para pegar tudo que há na opção que chama o modal
var id = callModal.data('id'); // pegando o parametro ID da minha opção que chama o modal (data-id)
console.log(id);
var modal = $(this);
modal.find('.modal-header #hiddenIdPeriodic').val(id); // Adicionando o id em um campo hidden só para pegar esse valor depois
});
and change it to
$(document).on('click', '.clickme', function() {
var id = $(this).data('id');
$('#modalUpdatePeriodico').modal('show');
$('#modalUpdatePeriodico').find('#hiddenIdPeriodic').val(id);
console.log(id);
})
#2
The date thing is a different event so add this to get the date
$('.datepicker-calendar').datepicker({
autoclose: true,
onSelect: function(date) {
console.log(date)
}
})

How do i validate a dynamic input field , laravel 5.4?

i have a html form with two fields that can added dynamically using javascript, but i can't validate the arrays of inputs in my request file
please see form below
{!!Form::open(['route'=>'create_course.store','class'=>'ed_contact_form ed_toppadder40', 'files'=>'true'])!!}
<div class="form-group {!!$errors->has('name')?'has-error':''!!}">
{!!Form::text('name',null,['class'=>'form-control', 'placeholder'=>'Titre du cours'])!!} {!!$errors->first('name', '<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!! $errors->has('description')?'has-error':''!!}">
{!!Form::textarea('description', null,['class'=>'form-control','placeholder'=>'Description du Cours'])!!}
{!!$errors->first('description','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('category')?'has-error':''!!}">
{!!Form::select('category' ,array(
'Choisir la Catégorie du cours',
'1'=>'Développement Web',
'2'=>'Développement mobile',
'3'=>'Business management',
'4'=>'Langues',
'5'=>'Motivation'
),['class'=>'form-control','id'=>'selectCat'])!!}
{!!$errors->first('category','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('price')?'has-error':''!!}">
{!!Form::text('price','Gratuit',['class'=>'form-control','placeholder'=>'price'])!!}
{!!$errors->first('price','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('sale')?'has-error':''!!}">
{!!Form::number('sale',null,['class'=>'form-control','placeholder'=>'Prix Promo'])!!}
{!!$errors->first('sale','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('langue')?'has-error':''!!}">
{!!Form::select('langue', array(
'Langue du cours',
'Moore'=>'Moore',
'Dioula'=>'Dioula',
'Wolof'=>'Wolof',
'Swahili'=>'Swahili',
'Fula'=>'Fula',
'Yoruba'=>'Yoruba',
'Twi'=>'twi'
),['class'=>'form-control','id'=>'selectLangue'])!!}
{!!$errors->first('langue','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('duration')?'has-error':''!!}">
{!!Form::number('duration','Gratuit',['class'=>'form-control','placeholder'=>'Durée du cours en semaines'])!!}
{!!$errors->first('duration','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!!$errors->has('image')?'has-error':''!!}">
{!!Form::label('imageCourse','Image du Cours')!!}
{!!Form::file('image',['class'=>'form-control','placeholder'=>'image du cours','id'=>'imageCourse'])!!}
{!!$errors->first('image','<small class="help-block">:message</small>')!!}
</div>
<div class="form-group {!! $errors->has('video[]')?'has-error':''!!}">
{!!Form::label('CourseVideo', 'Les Vidéos de votre Cours')!!}
<div class="lesson_container">
<div>
{!!Form::text('lesson_title[]',null,['class'=>'form-control','placeholder'=>'Titre de la Lesson'])!!}
{!! Form::file('video[]',['class'=>'form-control','id'=>'CourseVideo'])!!}
{!!
$errors->first('video[]','<small class="help-block">:message</small>')
!!}
</div>
<div class="row"></div>
<br>
{!!Form::button('Ajouter une lesson <i class="fa fa-plus" aria-hidden="true"></i>
',['class'=>'btn ed_btn ed_orange pull-left','id'=>'add_lesson'])!!}
</div>
<br>
</div>
{!!Form::hidden('prof_id',$prof_id)!!}
{!! Form::submit('Enregistrer',['class'=>'btn ed_btn ed_orange pull-right'])!!}
{!!Form::close()!!}
my script to add fiels dynamically
$(document).ready(function()
{
var wrapper=$(".lesson_container");
var add=$("#add_lesson");
$(add).click(function(e)
{
e.preventDefault();
$(wrapper).append('<br> <br><br><div><label for="newvideo">Ajouter une Video</label><input type="text" name="lesson_title[]" value="" class="form-control", placeholder="Titre de la lesson" id="newvideo"><input type="file" name="video[]" class="form-control"><div></div><br><button href="#" class="btn-primary" id="delete">Suprimer <i class="fa fa-trash-o" aria-hidden="true"></i></button></div>')
});
$(wrapper).on("click","#delete", function(e){
e.preventDefault();
$(this).parent('div').remove();
});
});
and my Request code
public function rules()
{
$rules=[
'name'=>'required|string|max:255',
'description'=>'required|string',
'category'=>'required|string',
'price'=>'required|string',
'sale'=>'string',
'langue'=>'required|string',
'duration'=>'required|integer',
'image'=>'required|image',
'prof_id'=>'required|integer'
//
];
var_dump($this->input('video'));
$videos=count($this->input('video'));
foreach(range(0,$videos) as $index)
{
$rules['video'.$index]='file|mimes:mp4,mov,wmv';
}
$lessons=count($this->input('lesson_title'));
foreach(range(0,$lessons) as $idx)
{
$rules['lesson_title.'.$idx]='required|string';
// echo $rules['lesson_title.'.$idx];
// var_dump($this->input('lesson_title'));
}
return $rules ;
}
}
When i print the two arrays $this->input('lesson_title') and $this->input('video') i get NULL means the arrays are empty .
What can be the issue here ? any help ?

message via ajax is hiding fields

I have a problem I could not solve
I'm trying to send the message via ajax and update a div when sending the message
the only problem is that when I comment on something that updates a div field textarea and buttons just disappear
I also put a button to display the message field and buttons
Here is the code I'm using
<script type="text/javascript">
function hide_menu(){
if(document.getElementById('responder').style.display == "none"){
document.getElementById('responder').style.display = "block";
document.getElementById('button').style.display = "block"
$('html, body').animate({scrollTop:$('#responder').position().top});
}else{
document.getElementById('responder').style.display = "none"
document.getElementById('button').style.display = "none"
$('html, body').animate({scrollTop:$('#da-content-wrap').position().top});
}
}
</script>
<script type="text/javascript" language="javascript">
$(function($) {
// Quando o formulário for enviado, essa função é chamada
$("#da-ex-validate1").submit(function() {
// Colocamos os valores de cada campo em uma váriavel para facilitar a manipulação
var mensagem = $("#cleditor").val();
var user = $("#user").val();
// Fazemos a requisão ajax com o arquivo envia.php e enviamos os valores de cada campo através do método POST
$.post('<?= URL::getBase();?>form/insert/comment.php?id=<?=$_id;?>', {user: user, mensagem: mensagem }, function(resposta) {
// Quando terminada a requisição
// Exibe a div status
$("#status").slideDown();
// Se a resposta é um erro
if (resposta != false) {
// Exibe o erro na div
alert('Ocoreu um erro !');
}
// Se resposta for false, ou seja, não ocorreu nenhum erro
else {
$("#mensagens").load('<?= URL::getBase();?>load.php?id=<?= $_id;?>');
// Limpando todos os campos
$("#cleditor").val('');
}
});
});
});
</script>
Here is the HTML
<!-- Content Area -->
<div class="da-panel-content"> <img src="buildings.png" alt="" />Reply
<div id="mensagens">
<?= comments::_build($_id);?>
</div>
<form id="da-ex-validate1" class="da-form" method="post" action="javascript:func()" >
<div id="responder" style="display:none;">
<textarea id="cleditor" name="mensagem" class="large required"></textarea>
<input type="hidden" name="user" id="user" value="<? GetInfo::_id(NULL);?>"/>
</div>
<div class="da-button-row" id="button" style="display:none;">
<input type="reset" value="<?= $_LANG[137];?>" class="da-button gray left" />
<input type="submit" id="da-ex-growl-2" value="<?= $_LANG[219];?>" class="da-button red" />
</div>
</form>
</div>
where is "<?= comments::_build($_id);?>" is the list of records.
I also made ​​a page load.php practically calls the same function.
http://i.stack.imgur.com/V46Nr.jpg
sorry any mistake english :-)

Categories

Resources