7
I’m a beginner in jQuery and I’m having a hard time doing a form validation with jQuery to the CRM of a church that is next:
I have a code HTML that is part of a CRM that I am developing. In this HTML I have a form with only one row and several columns, however, there is the option to add more rows with the button that is right next to the columns. Up to this point, everything OK.
The problem happens when I will validate these fields to generate a file bean of own CRM following the steps to make the validation work. It would happen as follows:
- Validate if the first field of form is completed (because that
has a
id
). If he is, he keeps going through the rest columns and saving in some array or something like in jQuery. - If there are more lines, it will proceed to the next line and repeat the
process (I made a
foreach
, but I don’t know if it’s right) and this process will take place until the last line, where in case the last line is completely unfilled, it will be ignored and generated the bean afterward. - The other validation is that if in the middle of the
form
the first column, in any line, which is empty, will send a message from error saying that the field is mandatory.
Below I will leave the code that I have done so far to get better understanding:
function addRow(element) {
var ln = $('#countLine').val();
ln++;
$linha = $('#tabela tr:last').clone();
$('input', $linha).val('');
$('div.yui-ac-container', $linha).attr('id', 'EditView_Membro_results' + ln);
$('ul.list-data', $linha).attr('id', 'UserAutoCompleteContent' + ln);
$('.membro_id', $linha).attr('id', 'membro_id' + ln);
$('.dizimo_id', $linha).attr('id', 'dizimo_id' + ln);
$('.oferta_id', $linha).attr('id', 'oferta_id' + ln);
$('.oferta_especial_id', $linha).attr('id', 'oferta_especial_id' + ln);
$('.missoes_id', $linha).attr('id', 'missoes_id' + ln);
$('.cesta_basica_id', $linha).attr('id', 'cesta_basica_id' + ln);
$('.ana_nazareno_id', $linha).attr('id', 'ana_nazareno_id' + ln);
$('.outros_id', $linha).attr('id', 'outros_id' + ln);
$('.membro_autocomplete', $linha).attr('id', 'Membro' + ln);
$('.dizimo_autocomplete', $linha).attr('id', 'Dizimo' + ln);
$('.oferta_autocomplete', $linha).attr('id', 'Oferta' + ln);
$('.oferta_especial_autocomplete', $linha).attr('id', 'OfertaEspecial' + ln);
$('.missoes_autocomplete', $linha).attr('id', 'Missoes' + ln);
$('.cesta_basica_autocomplete', $linha).attr('id', 'CestaBasica' + ln);
$('.ana_nazareno_autocomplete', $linha).attr('id', 'AnaNazareno' + ln);
$('.outros_autocomplete', $linha).attr('id', 'Outros' + ln);
$('#tabela tr:last').after($linha);
bind();
$(element).attr('onclick', 'DeleteRow(this)');
$(element).html('Remover');
$('#countLine').val(ln);
}
function DeleteRow(element)
{
var row = $(element).closest('tr');
row.remove();
}
//adiciona classe css quando for feito o click
$(document).ready(function(){
$("button").click(function(){
$("td").addClass("tabe");
});
});
function HideDivsOnBlur()
{
$(".yui-ac-content").hide();
$(".yui-ac-hd").hide();
}
function autoCompleteMembro(nomeMembro, idInput, divResults)
{
var parametro = $(nomeMembro).val();
var id_input = nomeMembro.attr('id');
var row = id_input.match(/\d+/)[0];
var dados = new Object();
dados.form = "EditView";
dados.method = "query";
dados.modules = ["Accounts"];
dados.field_list = ["name", "id"];
dados.populate_list = ["account_name", "account_id_c"];
dados.required_list = ["account_id_c"];
dados.conditions = [{"name" : "name", "op" : "like_custom", "end" : "%", "value" : ""}];
dados.limit = "10";
dados.no_match_text = "Nada foi Encontrado";
var dadosJson = JSON.stringify(dados);
var dataJson = { to_pdf : "true", module : "Home", action : "quicksearchQuery", data : dadosJson, query : parametro}
$.ajax({
url: "index.php",
data: dataJson,
type: "post",
success: function(resp){
console.log(resp);
var resposta = $.parseJSON(resp);
if(resposta.fields.length > 0)
{
// remove a lista buscada apos selecionar o membro
$("#UserAutoCompleteContent"+ row + " li").remove();
$("#EditView_Membro_results"+ row + " .yui-ac-content").show();
$("#EditView_Membro_results"+ row + " .yui-ac-hd").show();
$(divResults).show();
$(divResults).children(0).show();
$(divResults).children(0).css("z-index", "10000");
$(divResults).children(1).show();
$(resposta.fields).each(function(index, item){
$("#UserAutoCompleteContent"+row).append(
'<li style="z-index: 10000;" onclick="changeAssignedUserId(\''
+ item.id + '\', \'' + item.name.toUpperCase() + '\',\'' + $(idInput).attr('id') + '\',\'' +
$(nomeMembro).attr('id') + '\',\'' + $(divResults).find('ul').attr('id') + '\');">'
+ item.name.toUpperCase() + '</li>');
});
$("#EditView_Membro_results"+row+" li").hover(
function(){
$(this).css("background-color", "#426FD9")
$(this).css("color", "#fff")
},
function(){
$(this).css("background-color", "#fff")
$(this).css("color", "#000")
});
}
}
});
}
function changeAssignedUserId(Id, Name, MembroIdInputId, ProdNomeInputId, UlId)
{
console.log(MembroIdInputId);
$("#" + MembroIdInputId).val(Id);
$("#" + ProdNomeInputId).val(Name);
// remove a lista buscada apos selecionar o item
$("#" + UlId + " li").remove();
// esconde o bloco do resultado da busca
$(".yui-ac-content").hide();
$(".yui-ac-hd").hide();
}
function bind()
{
$('.membro_autocomplete').unbind('keyup').keyup(function(){
$inputMembro = $(this).closest('input');
$inputMembroId = $(this).closest('td').find("input[class='membro_id']");
$divResultados = $(this).closest('td').find("input[class='yui-ac-container']");
autoCompleteMembro($inputMembro, $inputMembroId, $divResultados);
});
}
bind();
function sendToPhp()
{
/* Verificar validação */
var linha = [];
$('#tabela tr').each(function(){
$(this).find("input[type=text]").each(function() {
// if($('#Membro0').val() !== ''){
//// $('#Membro0').closest("td");
// console.log($('#Membro0').val());
// return true;
// }
// else{
// console.log('Chegou aqui Valor Nulo');
// return false;
// }
linha = [ $(this).val() ];
console.log(linha)
});
// loop no array linha
});
// if($('.membro_id').val() !== null)
// {
// //foreach verificando se o proximo de cada posição na coluna possui valor
// //setar com false e em caso de valor mudar para true
// }
// else if($('.membro_id').val() === null)
// {
// //foreach verificando se o proximo de cada posição na coluna possui valor
// //setar com false e em caso de valor mudar para true
// }
}
function check()
{
var ok = 1;
$('#Membro0').blur(function()
{
if($(this).val().length === 0)
{
ok = 0; $(this).css('border-color','red');
alert('Campo MEMBRO deve ser preenchido');
}
else{ $(this).css('border-color',''); }
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="EditView_tabs">
<div>
<div id="detailpanel_1" class="edit view edit508 expanded">
<form id="formRelatorio" method="POST" action="index.php?module=culto_relatorio_dizimo&action=gravaRelatorio">
<input type="hidden" name="module" value="culto_relatorio_dizimo">
<input type="hidden" name="record" value="">
<input type="hidden" id="action" name="gravaRelatorio">
<input type="hidden" name="return_module" value="culto_relatorio_dizimo">
<input type="hidden" name="return_action" value="relatorioDizimo">
<table id="tabela" width="90%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam edit view panelContainer">
<tr>
<th class="larg">Membro</th>
<th class="larg">Dizimo</th>
<th class="larg">Oferta</th>
<th class="larg">Oferta Especial</th>
<th class="larg">Missões</th>
<th class="larg">Cesta Básica</th>
<th class="larg">ANA Nazareno</th>
<th class="larg">Outros</th>
<th> </th>
</tr>
<tr class='conteudo'>
<td class="tabe">
<input id="membro_id0" class="membro_id" type="hidden" value="">
<input id="Membro0" class="larg membro_autocomplete" type="text">
<div id="EditView_Membro_results0" class="yui-ac-container">
<div class="yui-ac-content" style="display: none;">
<div class="yui-ac-hd" style="display: none;">
</div>
<div class="yui-ac-bd">
<ul id="UserAutoCompleteContent0" style="z-index: 100;" class='list-data'> </ul>
</div>
<div class="yui-ac-ft" style="display: none;">
</div>
</div>
</div>
</td>
<td class="tabe">
<input id="dizimo_id0" class="dizimo_id" type="hidden" value="">
<input id="Dizimo0" class="larg dizimo_autocomplete" type="text">
<div id="EditView_Dizimo_results0" class="yui-ac-container">
</div>
</td>
<td class="tabe">
<input id="oferta_id0" class="oferta_id" type="hidden" value="">
<input id="Oferta0" class="larg oferta_autocomplete" type="text">
<div id="EditView_Oferta_results0" class="yui-ac-container">
</div>
</td>
<td class="tabe">
<input id="oferta_especial_id0" class="oferta_especial_id" type="hidden" value="">
<input id="OfertaEspecial0" class="larg oferta_especial_autocomplete" type="text">
<div id="EditView_OfertaEspecial_results0" class="yui-ac-container">
</div>
</td>
<td class="tabe">
<input id="missoes_id0" class="missoes_id" type="hidden" value="">
<input id="Missoes0" class="larg missoes_autocomplete" type="text">
<div id="EditView_Missoes_results0" class="yui-ac-container">
</div>
</td>
<td class="tabe">
<input id="cesta_basica_id0" class="cesta_basica_id" type="hidden" value="">
<input id="CestaBasica0" class="larg cesta_basica_autocomplete" type="text">
<div id="EditView_CestaBasica_results0" class="yui-ac-container">
</div>
</td>
<td class="tabe">
<input id="ana_nazareno_id0" class="ana_nazareno_id" type="hidden" value="">
<input id="AnaNazareno0" class="larg ana_nazareno_autocomplete" type="text">
<div id="EditView_AnaNazareno_results0" class="yui-ac-container">
</div>
</td>
<td class="tabe">
<input id="outros_id0" class="outros_id" type="hidden" value="">
<input id="Outros0" class="larg outros_autocomplete" type="text">
<div id="EditView_Outros_results0" class="yui-ac-container">
</div>
</td>
<td> <button type="button" onclick="addRow(this)">Adicionar</button> </td>
</tr>
</table>
</form>
<div class="fora">
<button type="button" class="buton" id="sendBtnEnviar" onclick="sendToPhp()">Inserir</button>
<input id="countLine" class="countLine" type="hidden" value="1">
</div>
</div>
</div>
</div>
The famous
console.log()
brings some result?– William Aparecido Brandino
yes he carries the name of the member in the first field
– user53602
About the function you use by clicking the send button (of course, this is not used, and in jQuery itself you can capture the event from the button [as you are beginner, it is good to take a look]), where you declared the variable
$linha
?– William Aparecido Brandino
see this yes, the variable $line is declared at the very beginning of Function addRow
– user53602
For the required fields you can use the HTML5 "required". To go through the fields and validate the values, you can use the . each() of jQuery: $( "#table input" ).each(Function( ) { var text = $.Trim($(this).val()); }); Trim removes whitespace at the beginning and end.
– Jhonatan Pereira
For validation, I found this here (not yet tested): https://jqueryvalidation.org/documentation/
– Jhonatan Pereira
@user53602 What church name? Still need help ?
– SneepS NinjA