Issue of logic with jquery validator ?
Hi, everyone
I wish someone could help me with a little problem or I'm stuck. My problem is that I'm trying to prevent any additional lines from being added as long as the number is less than or equal to the stock number.
I use jquery validator to perform this verification in real time.
Thanks for the help
This is my Jquery code :
jQuery(function($) {
$.validator.addMethod("stock", function(value, element) {
const stockReel = parseInt($(element).parent().prev().text())
return this.optional(element) || (parseInt(value) <= stockReel);
}, " The quantity entered is greater than the actual stock.");
$.validator.addClassRules('rowQuantite', {
stock: true
});
$("#form_Ajout").validate();
})
var count=1;
var currIndex="";
var trSet="";
$("#cmd").delegate(".AddRow","click",
function(e) {
// var lengthX = $('#'+tid+' > option').length;
var $tr = $(this).closest('tr');
e.preventDefault();
//counter = $('#'+tid+' > option').length;
//console.log(lengthX);
var lengthX = $('#choice > option').length;
var lengthX = lengthX - 1;
var table2 = $('#cmd > tbody').find('tr').length;
var table2 = table2 -1;
if($(this).val()=='Delete')
{
trSet=$(this).closest('tr').nextAll();
currIndex=$(this).closest('tr').find('td span').html();
$(this).closest('tr').remove();
}
else {
var $tr = $(this).closest('tr').clone(true);
$tr.find("input[type=number]").val("");
var $input = $tr.find('select.rowArticle');
var $input2 = $tr.find('input.rowQuantite');
++count;
$tr.find('td span').html(count);
$tr.find('td span').attr('id',count);
var id = 'choice' + count;
var id2 = 'QuantiteChoice' + count;
$input.attr('id', id).data('index', count);
$input2.attr('id', id2).data('index', count);
//console.log(count);
$tr.appendTo($(this).closest('table'));
if ( lengthX <= table2 ) {
$('.AddRow').attr('disabled', true);
// $('.AddRow').hide();
$('.AddRow').attr('disabled', true).prop('value', "Limite atteinte");
} else if( lengthX => table2)
{
return;
}
}
});
This is my html code :
- <form id="form_Ajout" name="formulaire">
<table class="tableCommune" id="cmd">
<tr><th>Article</th><th>Stock</th><th>QT</th><th></th></tr>
<td>
<select id="choice" class="rowArticle" name="choiceArticles[]" >
<option class="9" value="a">a</option>
<option class="9" value="b">b</option>
<option class="9" value="c">c</option>
<option class="9" value="d">d</option>
<option class="9" value="e">e</option>
</select>
</td>
<td>
58
</td>
<td>
<input type="number" min="1" class="rowQuantite" size="5" maxlength="5" name='quantites[]' value=''>
</td>
<td>
<input type ="hidden" id="test">
<input type="Button" value="+" class="AddRow" id="" />
<input type="button" class="delete" value="Delete"/>
</td>
</table>
<input type="hidden" value="0" id="counter">
<br>
<button type="submit" class="boutonValider" id="valid_form">Valider</button>
</form>