Sam Danger
Sam Danger

Reputation: 49

Use value form drop down menu?

I have a menu such as this:

<select>
<option value="21">option a</option>
<option value="13">option b</option>
<option value="21">option c</option>
</select>

Depending on what option is being selected I need get the corresponding value to use elsewhere in links and images. (it also needs to pull from the default option before it is clicked)

<img src="mysite.com/images/[valuegoeshere].jpg">
<a href="mysite.com/pages/[valuegoeshere].jpg">

There are several unique versions of these drop downs on page.

What is the easiest way to do this?

Upvotes: 0

Views: 101

Answers (3)

Ashirvad
Ashirvad

Reputation: 2377

you can get the selected value by handling change event of select drop down like this

$('#yourselectid').change(function(){
currentSelectedValue=$(this).val();
alert(currentSelectedValue);
})

Working fiddle

http://jsfiddle.net/yeZ3j/

UPDATED FIDDLE

http://jsfiddle.net/yeZ3j/1/

Updated Code:

$('select').change(function() {
    currentSelectedValue = $(this).val();
    $('img').attr('src', 'mysite.com/images/' + currentSelectedValue + '.jpg');
    $('a').attr('href', 'mysite.com/images/' + currentSelectedValue + '.jpg');

    $('body').append('<br>currentSource of img is :' + $('img').attr('src') + ' and anchor is: ' + $('a').attr('href'))
});
$(function() {
    $('select').trigger('change')
})​

Upvotes: 2

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91309

Use the following on $(document).ready():

function update(val) {
  $("img").attr("src", "mysite.com/images/" + val + ".jpg");
  $("a").attr("href", "mysite.com/pages/" + val + ".jpg");
}

var defaultVal = $("select").change(function () {
  update(this.value); // update <img> and <a> with the newly selected value
}).val();

update(defaultVal); // update <img> and <a> with the default value

DEMO.

Upvotes: 3

Alex Fischer
Alex Fischer

Reputation: 545

If the form is being submitted as a GET request, then this would be easy. Also remember to give a name attribute to the select. If you want to do it server-side and the name attribute is "my_name", then PHP to change the value of a link would look like this:

$option = $_GET["my_name"];
$link_text = "<a href='mysite.com/pages/" . $option . ".jpg'>link</a>";
$img_text = "<img src='mysite.com/images/" . $option . ".jpg' />";
echo $img_text . "\n" . $link_text;

Upvotes: 0

Related Questions