Change an image when input is given

前端 未结 5 1966
执念已碎
执念已碎 2021-01-28 17:10

I have a small basic html code with JavaScript . All I want is when I type 3,it should show me an image as specified and for 9 accordingly. This is the demo. Visit http://jsbin.

相关标签:
5条回答
  • 2021-01-28 17:39

    Place you script code inside

    $(document).ready(function(){
        //your code goes here
    });
    

    and replace

    $('#cardImage')[0].src = 'data/1357696142_mastercard1'+ num2img[n] +'.gif';
    

    by

    $('#cardImage')[0].src = 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.gif';
    
    0 讨论(0)
  • 2021-01-28 17:41

    You need to change the $('#cardImage')[0] to $('#cardImage').attr('src' , 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png'); as # will return one element replace See the jsfiddle http://jsfiddle.net/mailtoshebin/dMWmw/

    var num2img = {
      "3":"visa",
      "9":"mastercard"
    };
    
    $('#num').on('input', function(){
      var val = this.value;
      if(val.length<=1){
         var n = this.value.charAt(0);
         if(val && num2img[n]!==undefined){
           $('#cardImage').attr('src' , 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png');
         }else{
           $('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
         }
      }
    });
    
    0 讨论(0)
  • 2021-01-28 17:45

    try capturing "keypress" event on input box, http://api.jquery.com/keypress/ OR try capturing "change" event on input box, http://api.jquery.com/change/

    0 讨论(0)
  • 2021-01-28 17:52

    Try this

    $(document).ready(function(){
    
    var num2img = {
      "3":"visa",
      "9":"mastercard"
    };
    
        $('#num').keyup(function(){
          var val = this.value;
          if(val.length<=1){
             var n = this.value.charAt(0);
             if(val && num2img[n]!==undefined){
               $('#cardImage')[0].src = 'http://placehold.it/100x100/eee&text='+ num2img[n] +'.png';
             }else{
               $('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
             }
          }
        });
    });
    

    DEMO

    0 讨论(0)
  • 2021-01-28 17:53

    try something like this

    $(function(){
    
        // you have not given any event
        $('#num').on('keyup', function(){
          var val = this.value;
          if(val.length){//your length checking logically wrong
             var n = this.value.charAt(0);
             if(val && num2img[n]!==undefined){
               $('#cardImage')[0].src = 'data/1357696142_mastercard1'+ num2img[n] +'.gif';
             }else{
               $('#cardImage')[0].src = 'http://placehold.it/100x100/cf5';
             }
          }
        });
    })
    
    0 讨论(0)
提交回复
热议问题