views:

277

answers:

3

How to show an image while we select the option below.

Example : -

<select name="payment">
<option value="">Please Select</option>
<option value="Paypal">Paypal</option>
<option value="Bank">Bank</option>
</select>

<div id="payment"><img src="paypal.gif" alt="paypal" /></div>

If we select paypal on div id="payment" will show the logo paypal and if bank will show bank logo.

Can be done with jquery? let me know.

A: 

You'll need to hide the paypal.gif first

<select name="payment">
<option value="Paypal">Paypal</option>
<option value="Bank">Bank</option>
</select>

<div id="payment"><img src="paypal.gif' alt="paypal' /></div>

Then bind a change handler to the select.

<script>
var images = { 
    'Paypal': 'paypal.gif', 
    'Bank': 'bankLogo.gif'
};

$("select").bind("change",function(){
    $("div#payment img:first").attr('src', images[$("select :selected").val()] );
});
</script>
Andy
You dont show the bank logo
James Westgate
Run the code, it works using `$("div#payment img").show();`
Andy
@Andy - This is what I thought at first too, but he edited the question, he wants to show the `bank.gif` if it's bank, `paypal.gif` if it's paypal.
Nick Craver
Thanks for the heads up! Updated.
Andy
Ah the old edit the question trick. I wondered why both of you had missed that :D
James Westgate
+1  A: 

Doh, misread the question, updated:
You can do this with just a small event handler, like this:

$(function() {
  $("select[name=payment]").bind("change", function() {
    $("#payment img").attr('src', $(this).val().toLowerCase() + ".gif");
  }).change();
});

This approach adjusts the src of the image based on the current selected value. Also, we're triggering the event one time on document.ready to make the initial hide/show state match the dropdown.

Nick Craver
You dont show the bank logo ?
James Westgate
@James - Was just editing to change that, re-read the question for an ID and realized that wasn't what he wanted.
Nick Craver
@Nick thanks working!. I added please select. How to disable the image if value is empty
bob
Er Bob. You need to start thinking for yourself here mate.
James Westgate
yes.. got it. thanks guy
bob
+1  A: 

Assumption: your bank logo is called bank.gif.

EDIT: added code to check for blank value.

$('select[name=payment]').change(function() {

  var val = $(this).val();

  $('div#payment img')
    .attr('src', val + '.gif')
    .css('display', val.length ? 'block' : 'none');
});
James Westgate