Reputation: 335
I have an input field and the user can either type in a code or copy/paste it from an email. I need to check the length of the input val() to activate a button afterwards, if the given value has a specific length. The length check works fine while typing, but not every time when pasting a value. The length is mostly 0 then - but not EVERY time. What am I doing wrong here, I don't get it? It should work EVERY TIME.
$(document).on('keyup change paste click', '#promocode', function () {
var code = $(this).val();
$("#result").html(code.length);
if (code.length == 8) {
$("#result").html("length ok");
}
else {
$("#result").html("NOT ok");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Copy/Paste a value into this field:
<form>
<input type="text" id="promocode" placeholder="xxxx-xxx" />
<div id="result">Enter value (8-digits)</div>
</form>
Upvotes: 2
Views: 1202
Reputation: 1667
$("#promocode").on('change keydown paste input propertychange click keyup blur', function(){
if($('#promocode').val().length == 8){
$("#result").html('okay');
}
else{
$("#result").html('not okay');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input type="text" id="promocode" placeholder="xxxx-xxx" />
<div id="result">Enter value (8-digits)</div>
try this, it includes methods which will fire when input changes. fiddle link
Upvotes: 1
Reputation: 2051
For me (chrome/windows) your code worked with copy/paste and typing. The only time it failed was when I used right-click and paste. To fix that, I added the input event to your list. Now it works all the time.
$(document).on('keyup change paste click input', '#promocode', function () {
var code = $(this).val();
$("#result").html(code.length);
if (code.length == 8) {
$("#result").html("length ok");
}
else {
$("#result").html("NOT ok");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Copy/Paste a value into this field:
<form>
<input type="text" id="promocode" placeholder="xxxx-xxx" />
<div id="result">Enter value (8-digits)</div>
</form>
Upvotes: 1