Trouble with validation in dynamic forms with jquery + razor pages - javascript

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{
//.......
}
});

Related

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)
}
})

Validate modal-form with jquery

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

Form in ajax post method sends empty object

I have a webform with several fields I want to capture in an object and send it to a controller method. The form has this code:
<div class="panel-footer">
#using (Html.BeginForm("NuevaOpcion", "Home", FormMethod.Post, new { #id = "frm_nueva_opcion" })) {
#Html.HiddenFor(m => m.Id)
<div class="row">
<div class="col-md-6">
<div class="form-group" style="margin-bottom: .7em;margin-top: .7em;">
<button class="btn btn-success btn-xs" type="button" onclick=" $('#row-nueva-opcion').toggle()" id="add-opcion">
<span class="glyphicon glyphicon-plus-sign"></span> Añadir nueva opción
</button>
</div>
</div>
</div>
<div class="row" id="row-nueva-opcion" style="display:none">
<div class="col-md-10">
<label>
<input type="checkbox" id="opcion-extra" onclick=" $('#nuevo-precio').attr('disabled', !this.checked);" />
Es opción extra
</label>
<div class="input-group" style="margin-bottom:1.7em;">
<input type="text" placeholder="Opción" class="form-control" name="nombre" style="max-width:70%;">
<input type="number" placeholder="Cantidad" min="1" value="1" class="form-control" name="cantidad" style="max-width:15%;">
<input type="number" placeholder="Precio" class="form-control" id="nuevo-precio" name="precio" style="max-width:15%;" disabled>
<input type="hidden" name="idrespuesta" id="idrespuesta" value="#listItems.Select(x=>x.Value).FirstOrDefault()" />
<div class="input-group-addon">€</div>
<span class="input-group-btn">
<a class="btn btn-primary" data-title="Confirmación de acción" data-toggle="modal" data-target="#modal_confirm" onclick="confirmar('frm_nueva_opcion')">
<span class="glyphicon glyphicon-floppy-disk"></span> Guardar
</a>
</span>
</div>
</div>
<div class="col-md-8">
<div class="form-group">
<label>
¿Para que pregunta es la opción?
#Html.DropDownList("OptionSelectedItem", listItems, new { #class = "form-control" })
</label>
</div>
</div>
</div>
}
</div>
To manage it, I have a script that looks like this:
function mostrarModal(idmodal, mensaje, tipo) {
$(idmodal + ' .modal-body h4').addClass(tipo == 'error' ? 'text-danger' : 'text-secondary').html(mensaje);
$(idmodal).modal('show');
}
function enviar(form) {
debugger;
var NuevoPrecio = $('#' + form).attr("nuevo-precio");
if( (NuevoPrecio == null) || (typeof NuevoPrecio === "undefined") ) { var NuevoPrecio = 0; }
var datos = {
Id: $('#' + form).attr("#Id"),
IdPresupuestador: $('#' + form).attr("#idPresupuestador"),
IdRespuesta: $('#' + form).attr("#idrespuesta"),
Cantidad: $('#' + form).attr("#cantidad"),
Nombre: $('#' + form).attr("#nombre"),
Precio: NuevoPrecio,
}
$.post("NuevaOpcion", {
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(datos),
});
}
var modalConfirm = function (callback) {
$("#modal-btn-si").on("click", function () {
callback(true);
$("#modal-confirm").modal('hide');
});
$("#modal-btn-no").on("click", function () {
callback(false);
$("#modal-confirm").modal('hide');
}); };
function confirmar(form, text) {
$("#modal-confirm").modal('show');
modalConfirm(function (confirm) {
if (confirm) {
enviar(form);
}
}); };
Trouble is, I've changed the script on several points and now looks like this because the best I could manage was taking all the form in a single object. I can't work with the properties contained in that object, not on the script and neither on the controller method.
So, the question is, how am I selecting the fields wrong? I've tried with "#", ".", just the name between quotes, and as I said, the best I could get was the entire form in a single object. Thanks in advance.

Form Validation with JavaScript and PHP (Not refresh page on submit)

I am trying to do a form validation with JS that shows feedback as the user types. But of course when submitted the form it's sent using PHP. I already managed to do all of this the only problem I am having now is that when the form is submitted the page refreshes and my "Successfully sent" message cannot be seen. Here is my code and thanks a lot! :D
HTML FORM
<form method="post" id="emailForm" action="?">
<div class="form-group">
<label for="email">Email</label>
<input type="email" placeholder="ejemplo#gmail.com" class="form-control" name="email" id="email"/>
<p class="alert alert-danger errorEmail"></p>
</div>
<div class="form-group">
<label for="name">Nombre</label>
<input type="text" placeholder="María Rodriguez" class="form-control" name="name" id="name"/>
<p class="alert alert-danger errorName"></p>
</div>
<div class="form-group">
<label for="asunto">Asunto</label>
<input type="text" placeholder="Garantía producto" class="form-control" name="asunto" id="asunto" /><span class="badge badgeA"></span>
<p class="alert alert-danger errorAsunto"></p>
</div>
<div class="form-group">
<label for="mensaje">Mensaje</label>
<textarea placeholder="Ingrese su mensaje aquí, trate de ser lo más claro y conciso posible." name="mensaje" id="mensaje" class="form-control" rows="7"></textarea><span class="badge badgeM"></span>
<p class="alert alert-danger errorMensaje"></p>
</div>
<input type="submit" name="submit" id="submit" class="btn btn-success" value="Enviar!"/>
Field to display feedback of submission
<div class="alert alert-success enviado">
</div>
<div class="alert alert-danger noEnviado">
</div>
JavaScript (jQuery)
$(function() {
$(".errorEmail").hide();
$(".errorName").hide();
$(".errorAsunto").hide();
$(".errorMensaje").hide();
$(".enviado").hide();
$(".noEnviado").hide();
var error = false;
$('#email').keyup(function(){
checkEmail();
});
$('#name').keyup(function(){
checkName();
});
$('#asunto').keyup(function(){
checkAsunto();
});
$('#mensaje').keyup(function(){
checkMensaje();
});
function checkEmail() {
var email = $('#email').val();
error = false;
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if(re.test(email)) {
$('.errorEmail').hide();
}
else {
$('.errorEmail').html("Ingrese un correo electrónico válido.")
$('.errorEmail').show();
error = true;
}
}
function checkName() {
var name = $('#name').val().length;
var minName = 5;
var cantidad = - (name - minName);
error = false;
if (name < 5){
$('.errorName').html("Por favor ingrese su nombre. <b>Mínimo " + cantidad + " caracteres.</b>");
$('.errorName').show();
error = true;
}
else {
$('.errorName').hide();
}
}
function checkAsunto() {
var asunto = $('#asunto').val().length;
var minAsunto = 10;
var cantidad = - (asunto - minAsunto);
error = false;
if (asunto <10){
$('.errorAsunto').html("Por favor ingrese un asunto.<b> Mínimo " + cantidad + " caracteres.</b>");
$('.errorAsunto').show();
error = true;
}
else {
$('.errorAsunto').hide();
}
}
function checkMensaje() {
var email = $('#mensaje').val().length;
var minMensaje = 20;
var cantidad = - (email - minMensaje);
error = false;
if (email < 20){
$('.errorMensaje').html("Por favor ingrese un mensaje. <b> Mínimo " + cantidad + " caracteres. </b>");
$('.errorMensaje').show();
error = true;
}
else {
$('.errorMensaje').hide();
}
}
$('#emailForm').submit( function() {
checkEmail();
checkName();
checkAsunto();
checkMensaje();
if(error === false) {
$('.enviado').html("Mensaje enviado exitosamente");
$('.enviado').fadeIn(500);
$('.noEnviado').fadeOut(500);
return true;
} else {
$('.noEnviado').html("Ups... hubo un problema");
$('.noEnviado').fadeIn(500);
$('.enviado').fadeOut(500);
return false;
}
});
});
PHP
The PHP code is really simple some how it doesn't let me display it here but it just get's the $_POST values on the form and sends them using email();
Thanks guys
Instead of returning true replace it with an Ajax post request to the same script, on success show the message you wish.

Categories

Resources