0

I am creating a credit card page for my mobile website. I want that as soon as I enter the number, say, 5, the image in input box should be of maestro-card, entering 4 changes the image to be that of some other card, and so on. Much as the Clear Trip mobile site does.

I used JavaScript's onkeypress event but it receives an action when there is no value is in the text box.

<input type="text" size="20" autocomplete="off" style="width:80%"  onkeypress="func();"/> <div class="card-img"></div>

How should I do it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
hkasera
  • 2,118
  • 3
  • 23
  • 32
  • 1
    Since you are asking rather basic things i really hope you won't prompt for the user's credit card number, too. – ThiefMaster May 02 '12 at 15:30

2 Answers2

0

You should handle the keyup and input events.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
-1

jsFiddle: http://jsfiddle.net/ksHa2/12/

<div class="card-img"><img id="img" src="http://www.google.com/logos/2012/laborday12-hp.jpg"/></div>

<input type="text" size="20" autocomplete="off" style="width:80%" onkeydown="update(this);" onchange="update(this);"/>

<script>
    function update( object )
    {
        if ( object.value.length == 1 )
        {
            document.getElementById('img').src = "http://www.google.com/logos/2012/ramon_y_cajal-2012-hp.jpg";
        }
        else if ( object.value.length == 2 )
        {
            document.getElementById('img').src = "http://www.google.com/logos/2012/queensday12-hp.jpg";
        }
        else if ( object.value.length == 3 )
        {
            document.getElementById('img').src = "http://www.google.com/logos/2012/queensday12-hp.jpg";
        }
        else
        {
            document.getElementById('img').src = "http://www.google.com/logos/2012/laborday12-hp.jpg";
        }
    }
</script>
​
Jonathan Payne
  • 2,223
  • 13
  • 11
  • I want the change to happens as i enter the number.In your case as i enter 1 i should get that image not when text box goes out of focus! – hkasera May 02 '12 at 15:47
  • You might need to read [my answer](http://stackoverflow.com/a/10029116/1048572) on the question "Alternative to a million IF statements"... Your function in one line: `document.getElementById('img').src = "http://www.google.com/logos/2012/" + ["ramon_y_cajal-2012-hp", "queensday12-hp", "queensday12-hp", "laborday12-hp"][object.value.length-1] + ".jpg";` – Bergi May 02 '12 at 15:49