Scilly Guy
Scilly Guy

Reputation: 42

Using jquery to get selected element's value

Why does this not work:

HTML:

<img src='picture.jpg'>
<select name='blah[0]' onchange='changePicture();'>
  <option value='default.jpg'>Default</option>
  <option value='somethingelse.jpg'>A picture</option>
</select>

Javascript:

function changePicture()
{
  $(this).siblings("img").attr("src",$(this).val());
}

Upvotes: 0

Views: 72

Answers (3)

j08691
j08691

Reputation: 207901

First you're not passing a reference to the select element in your code, so this has no value in your function. To do that, you'd do something like onchange='changePicture(this);', but I'm not recommending that.

Since you're using jQuery you should use jQuery's event handling like this:

$('select[name="blah[0]"]').change(function(){
    $(this).siblings("img").attr("src", $(this).val());
})

jsFiddle example

Upvotes: 1

Anwar
Anwar

Reputation: 4246

$(function() {
  $("#select").change(function() {
    var src = $("#select").val(); /* value of the current selected option */
    
    $("#img").prop("src", src);
    
    alert($("#img").prop("src"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id = "img" src='picture.jpg'>
<select id = "select" name='blah[0]' onchange='changePicture();'>
  <option value = "picture.jpg">Default Picture</option>
  <option value='default.jpg'>Default</option>
  <option value='somethingelse.jpg'>A picture</option>
</select>

I added 2 ids, img to identify the image, and select to identify the select. I used .change() JQuery function which is triggered when <option> is changed. I take the value of the <option> selected, and change the src of the image.

Upvotes: 0

Patrick Smith
Patrick Smith

Reputation: 261

Modify your Javascript function to accept a parameter:

function changePicture(tag)
{
  $(tag).siblings("img").attr("src",$(this).val());
}

Your HTML will call the function passing it 'this':

<img src='picture.jpg'>
<select name='blah[0]' onchange='changePicture(this);'>
  <option value='default.jpg'>Default</option>
  <option value='somethingelse.jpg'>A picture</option>
</select>

Upvotes: 1

Related Questions