James Lyngaas
James Lyngaas

Reputation: 13

How can I get the value to change everytime I change the select box?

How script works: When this script is run it grabs the id# (example 123) from the option in the select box (#artist) and it puts that number at the end of a basic link that has a class of updategallerylink. So I end up getting a link like this: domain.com/artist/123/)

The problem is if I choose option 1 (123) and then choose option 2 (234) it actually spits out a link that says domain.com/artist/123/234/ when it should have just spit out domain.com/artist/234/.

I don't want it to stack the variable from #artist, but rather replace it with the correct id# each time I select a different option.

<script type="text/javascript">
$(function()  {

  $('.updategallerylink').click(function()  {
    var searchString = $('#artist').val();
    var searchLink = $(this).attr('href');
    $(this).attr('href', searchLink+searchString+'/');
  });

});
</script>

<select name="artist" id="artist" style="width: 200px; background: black;" class="required">
            <option value="123">Artist 1</option>
            <option value="234">Artist 2</option>
        </select>
<a href="/artist/" id="gallerylink" class="updategallerylink" title="Artwork Gallery" target="_blank">gallery</a>

Upvotes: 1

Views: 71

Answers (1)

Drakes
Drakes

Reputation: 23660

You could hold the original href as data, then only append the artist to the original href like so:

<script type="text/javascript">
$(function()  {

  $('.updategallerylink').click(function()  {
    if(!$(this).data('orig-href')) {
        // Store the original href
        $(this).data('orig-href', $(this).attr('href'));
    }

    var searchString = $('#artist').val();
    var searchLink = $(this).data('orig-href');
    $(this).attr('href', searchLink + searchString + '/');
  });

});
</script>

Demo: http://jsbin.com/gigami/4/

Upvotes: 3

Related Questions