Reputation: 419
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
Upvotes: 1
Views: 2603
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');
}
$("#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
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
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