Not an expert on bind functions. I created the snippet below to demonstrate what I'm trying to do.
I want to fire an event every time the 1st character of an input field is entered, but only the first character. I want it to run even if the user clears the input and starts over.
$("#userCardNumber")
If I use .one("keyup", function()
then it only runs once and if the user clears the field, hits backspace, or otherwise types over the 1st character it doesn't run again (as in my understanding it has been unbound/unbind)
$("#userCardNumber2")
I can quasi-accomplish my intent by using .on("keyup", function()
adding an if (element.length === 1) { }
inside that function, but this seems terribly inefficient as it runs on every keyup and since this is a card number field that's 14-15 extra times it runs unnecessarily.
Trying to learn the most efficient way to do things, so curious how I can achieve the desired outcome without burning the extra keyups computations like I do in $("#userCardNumber2")
?
(function($) {
// On ready functions
$(function() {
$("#userCardNumber").one("keyup", function() {
var el = $(this);
cardType = el.val();
if (cardType = 3) {
console.log("AmEx");
} else if (cardType = 4) {
console.log("Visa");
} else if (cardType = 5) {
console.log("Mastercard");
} else if (cardType = 6) {
console.log("Discover");
} else {
console.log("something else");
}
console.log("Ran function")
});
$("#userCardNumber2").on("keyup", function() {
var el = $(this);
cardType = el.val();
if (cardType.length === 1) {
if (cardType = 3) {
console.log("AmEx");
} else if (cardType = 4) {
console.log("Visa");
} else if (cardType = 5) {
console.log("Mastercard");
} else if (cardType = 6) {
console.log("Discover");
} else {
console.log("something else");
}
}
console.log("Ran function")
});
});
}(jQuery));
div {
margin-top: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input id="userCardNumber" type="text">
</div>
<div>
<input id="userCardNumber2" type="text">
</div>