0

I need to change a couple of href parameters using jQuery and driven by two form select options. The below example works perfectly but is driven from a text input and having problems converting it to work with a select.

https://stackoverflow.com/a/6540265/460322

I know this shouldn't be too hard but I have a stinking cold and brain is like mush this morning!

My code so far that doesn't work:

$(window).load(function(){

function updateNameValue() {
    $('#changelink').val($('#option1 option:selected').attr('href', function(i,a){
        return a.replace( /(field16=)[a-z]+/ig, '$1'.target.value ));
    });
});

$('#option1').change(updateNameValue);

updateNameValue();
});
Community
  • 1
  • 1
richardpixel
  • 291
  • 1
  • 4
  • 9
  • 1
    Richard, you didn't really show us what you tried so far :) Generally you would just use the $.attr("href","newlink") function on the specificc changed object to change its href attribute. – Shai Mishali Jan 09 '12 at 10:28
  • give some of your code portion that u tried. – TKV Jan 09 '12 at 10:31

2 Answers2

1

I ended up using the following code:

function changeHref(){
 arg1 = $('#o1').val();
 arg2 = $('#o2').val();
 if (!arg1)
    arg1 = 'default1';
 if (!arg2)
    arg2 = 'default2';
 link = "link.html?arg1=" + arg1 + "&arg2=" + arg2;
 $('#updateLink').attr("href",link)
}

$('.linkUpdater').change(function(){
 changeHref();  
});

changeHref();

With this HTML:

<select class="linkUpdater" id="o1">
    <option value="">Select</option>
    <option value="option1">Option 1</option>
    <option value="option2">Option 2</option>
</select>
<select class="linkUpdater" id="o2">
    <option value="">Select</option>
    <option value="optionA">Option A</option>
    <option value="optionB">Option B</option>
</select>

<a id="updateLink" href="link.html">Link</a>
richardpixel
  • 291
  • 1
  • 4
  • 9
0

EDIT: This should work - jsfiddle.net/9dGdC

First, set the value attribute of each option tag in the select field to the respective href value, as shown below.

<select>
 <option value="www.example.com">Option 1</option>
</select>

Then, use this code :

$('select').change(function(){
 $('.link').attr('href',$(this).val())
});

This will change the href attribute of the link!

Karthik Rao
  • 321
  • 3
  • 9
  • Thanks, but that's not what I'm after. I did have that working but I actually need to change parameters within a URL: /form/field16=REPLACETHIS&field18=REPLACETHIS – richardpixel Jan 09 '12 at 10:34
  • That looks like it will work. Will try integrating now and report back - thanks. – richardpixel Jan 09 '12 at 14:18