user3128920
user3128920

Reputation: 419

Change image src depending on an elements value using javascript

I have this html

<div class="fake-input">
               <input type="text" data-theme="a" placeholder="Card Number" id="ccnumber" name="ccnumber" class="textBox input tokenex_data" data-form="ui-body-a" />

        <img id="cc" src="http://www.zermatt-fun.ch/images/mastercard.jpg" width=30 />
        </div>

  <div class="form-group" style="margin-left:0px">
                <input type='hidden' id='ccType' name='ccType'/>
            <ul class="cards">
            <li class="visa">Visa</li>
            <li class="visa_electron">Visa Electron</li>
            <li class="mastercard">MasterCard</li>
            <li class="maestro">Maestro</li>                   
            </ul>
              </div>

depeding on the value of the hidden input field ccType,I want to change the image src. Th below code is not syntactically correct,its just a demonstration and a raw idea of what im trying to do

if (ccType=="visa")
{
change the image src to 'www.xyz.com/visa.png'
}
if( ccType=="maestro")
{
change image src to 'www.xyz.com/masestro/png'
}

the src inside

    <img id="cc" src="http://www.zermatt-fun.ch/images/mastercard.jpg" width=30 />

should be changed

Im trying to do this using a javascript.This is my fiddle

http://jsfiddle.net/DMx8a/

Upvotes: 1

Views: 2603

Answers (3)

Satpal
Satpal

Reputation: 133403

Use .attr(), it set attributes for the set of matched elements.

 $('#cc').attr('src', 'www.xyz.com/visa.png')

Code

if (ccType=="visa")
{
    $('#cc').attr('src', 'www.xyz.com/visa.png');
}
if( ccType=="maestro")
{
    $('#cc').attr('src', 'www.xyz.com/masestro/png');
}

DEMO

EDIT

$("#ccnumber").on('blur', function () {
    var ccType = $(this).val();
    if (ccType == "visa") {
        $('#cc').attr('src', 'https://i.sstatic.net/aMCHQ.png?s=32&g=1');
    }
    if (ccType == "maestro") {
        $('#cc').attr('src', 'https://www.gravatar.com/avatar/9edb7a1c14bbcbeaa16bd9149764c3c6?s=32&d=identicon&r=PG&f=1');
    }
})

DEMO with blur event on ccnumber textbox

Upvotes: 2

Siva Tumma
Siva Tumma

Reputation: 1701

If you are using plain javascript, go for the following: document.getElementById('cc').setAttribute('src', 'www.xyz.com/visa.png');.

Like :

var imageElement = document.getElementById('cc');
if (ccType=="visa"){imageElement.setAttribute('src','www.xyz.com/visa.png');}
if( ccType=="maestro"){imageElement.setAttribute('src', 'www.xyz.com/masestro/png');}

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Or just regular JS:

var image = document.getElementById("cc");
if (ccType=="visa")
{
    //change the image src to 'www.xyz.com/visa.png'
    image.src = 'www.xyz.com/visa.png'
}
if( ccType=="maestro")
{
    //change image src to 'www.xyz.com/masestro/png'
    image.src = 'www.xyz.com/masestro/png'
}

Upvotes: 0

Related Questions