Reputation: 109
html:
<div class="col-md-10 col-sm-10 col-xs-10">
{{ form_widget(experienceForm.description, {
'attr': {
'class': 'form-control field-max-length field-max-length field-line-length',
'rows': 6
}
})}}
</div>
handleChangeLineCounter = function() {
$('.field-line-length').keyup(function (e) {
e.preventDefault();
var countLineNum = (this.value.match(/\n/g)||[]).length;
console.log(countLineNum);
checkEnterKey ($(this), 7, countLineNum);
});
}
function checkEnterKey (getVarName, maxLine, countLine) {
var msg2 = maxLine - countLine +' lignes restantes,';
if ((maxLine - countLine) === 1 || (maxLine - countLine) === 0) {
msg2 = maxLine - countLine +' ligne restante,';
}
getVarName.keypress(function(e) {
if(e.which === 13) {
if ((maxLine - countLine) < 1) {
return false;
}
else if ((maxLine - countLine) > 0) {
return true;
}
}
});
$('.counter-msg-2').remove();
getVarName.after('<span class="counter-msg-2 m-r-5"><span class="counter_msg_2">' + msg2 + '</span></span>');
}
From the above code, in the function checkEnterKey()
, when (maxLine - countLine
) reaches 0, I press delete key or backspace key then press enter key again, the key stops working.
On the contrary if (maxLine - countLine
) does not reach 0, I press delete key or backspace key then press enter key again, the key works.
How can I make the enter key work when I reach (maxLine - countLine) = 0
?
Upvotes: 1
Views: 68
Reputation: 5283
There is a few problems with your code:
keypress
on every keyup
and that is very bad.remove()
and after()
from JQuery which are more expensive than just laying the element and using html()
simply.The following solution has some code cleanup as well as remedies to the issue mentioned above.
// main function for attaching the event handlers to your element
function handleChangeLineCounter(max) {
// initial value for the counter
$('.counter-msg-2').html(`${max} lignes restantes`);
// keypress event to handle only allowing the needed lines
// this code is not part of the keyup event because returning
// false here won't prevent the key from appearing
$('.field-line-length').keypress(function (e) {
let diff = max - ($(this).val().match(/\n/g) || []).length;
if (e.which === 13 && diff === 0) {
return false;
}
});
// keyup event to handle the counter display
// this code is not part of the keypress event because the last
// input key would be missing
$('.field-line-length').keyup(function (e) {
let diff = max - ($(this).val().match(/\n/g) || []).length;
let msg = ((diff <= 1) ? `${diff} ligne restante` : `${diff} lignes restantes`);
$('.counter-msg-2').html(msg);
});
};
handleChangeLineCounter(7);
.field-line-length {
width: 500px;
height: 120px;
overflow-y: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="field-line-length"></textarea>
<span class="counter-msg-2 m-r-5">
<span class="counter_msg_2"></span>
</span>
I hope this helps.
Upvotes: 1