Saturday, 17 August 2013

Is it possible to apply a change event to a substring of a value using jQuery?

Is it possible to apply a change event to a substring of a value using
jQuery?

I'm building a credit card form for a client and want the credit card
company logo to appear once the person starts typing their credit card
number.
All Visa's start with 4. MC with 5. Discover with 6. Amex 36, Diners 37.
So I'm trying something like this:
<script>
$(document).ready(function() {
$($('#cardNumber').val().substring(0,1)).change(function() {
switch ($(this).val()) {
case '4':
$('#cardImage').hide().html('<img src="img/visa.png"
alt="Visa" style="width: 50px; height:
30px;">').fadeIn(250);
break;
case '5':
$('#cardImage').hide().html('<img
src="img/mastercard.png" alt="Mastercard"
style="width: 50px; height: 30px;">').fadeIn(250);
break;
case '6':
$('#cardImage').hide().html('<img
src="img/discover.png" alt="Discover" style="width:
50px; height: 30px;">').fadeIn(250);
break;
}
});
});
</script>
<form name="creditCardForm" id="creditCardForm" action="" method="post">
<fieldset>
<label for="cardNumber">Card Number:</label>
<span id="cardImage"></span>
<input type="text" name="cardNumber" id="cardNumber">
</fieldset>
</form>
...whereas I'm trying to apply a change function to just the first
character in the value. Is something like this possible?
--UPDATE--
Based on the comment below, I modified the form to have a hidden field
that contains just the first number entered. The problem I'm encountering
now is that the keyup is not triggering a change on the hidden field.
Chaining a .change() function to the end of the hidden field triggers the
image to appear every time. I don't want to un0bind the event after the
first digit is typed in case the user goes back and modifies the first
digit again.
Any thoughts on a way to proceed here?
<script>
$(document).ready(function() {
$('#cardNumber').on('keyup', function() {
$('#firstCreditCardDigit').val($(this).val().substring(0,1));
});
$('#firstCreditCardDigit').change(function() {
switch ($(this).val()) {
case '4':
$('#cardImage').hide().html('<img src="img/visa.png"
alt="Visa" style="width: 50px; height:
30px;">').fadeIn(250);
break;
case '5':
$('#cardImage').hide().html('<img
src="img/mastercard.png" alt="Mastercard"
style="width: 50px; height: 30px;">').fadeIn(250);
break;
case '6':
$('#cardImage').hide().html('<img
src="img/discover.png" alt="Discover" style="width:
50px; height: 30px;">').fadeIn(250);
break;
}
});
});
</script>
<form name="creditCardForm" id="creditCardForm" action="" method="post">
<input type="hidden" name="firstCreditCardDigit"
id="firstCreditCardDigit">
<fieldset>
<label for="cardNumber">Card Number:</label>
<span id="cardImage"></span>
<input type="text" name="cardNumber" id="cardNumber">
</fieldset>
</form>

No comments:

Post a Comment