all input fields with limited chars, am using with jquery function to get proper output if i use keyup it works fine but not applying to all popup wizard in my application if i use keydown it shows incorrect values while typing on input fields
<div>
<input type="text" />
<textarea></textarea><label style="font-size:11px ;"></label>
</div>
<hr/>
<div>
<input type="text" />
<textarea></textarea><label style="font-size:11px ;"></label>
</div>
<hr/>
$(document).on('keydown','input[type="text"],textarea ',function(){
tag_name = $(this).prop("tagName")
if(tag_name == 'TEXTAREA'){
limit = 200
limit_warning = 179
$(this).attr('maxlength',200,)
}
else{
limit = 20
limit_warning = 15
$(this).attr('maxlength',20,)
}
this_vall = $(this).val()
length_count = this_vall.length
var text_field = length_count "/" limit;
label_tag = $(this).siblings('label')
is_label_exist = label_tag.length
if(is_label_exist <1){
x = ` <label style="font-size:11px ;">${text_field}</label>`
$(this).parent().append(x)
$(label_tag).text(text_field)
}
else{
$(label_tag).text(text_field)
}
CodePudding user response:
Use input, it can handle paste too
Also DRY and don't bleed vars into global scope
Lastly if you have something called exists, then don't use it as not exists
$(document).on('input', 'input[type="text"],textarea ', function() {
const tag_name = $(this).prop("tagName");
const isTextArea = tag_name === 'TEXTAREA';
const limit = isTextArea ? 200 : 20;
const limit_warning = isTextArea ? 179 : 15;
$(this).attr('maxlength', limit);
let this_vall = $(this).val();
let length_count = this_vall.length;
let text_field = length_count "/" limit;
let label_tag = $(this).siblings('label');
let is_label_exist = label_tag.length > 0;
if (!is_label_exist) {
x = ` <label style="font-size:11px ;">${text_field}</label>`
$(this).parent().append(x)
}
$(label_tag).text(text_field)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
200 chars:
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin dolor nunc, suscipit in posuere quis, eleifend ut tortor. Quisque ullamcorper massa leo, vel euismod est dignissim nec. Nulla in eros ac.</div>
<div>
<input type="text" />
<textarea></textarea><label style="font-size:11px ;"></label>
</div>
<hr/>
<div>
<input type="text" />
<textarea></textarea><label style="font-size:11px ;"></label>
</div>
<hr/>