I have a select element with options with values that are some numbers (some id's).
<select id="select">
<option value="21">Random<option>
<option value="23">Random 2<option>
<option value="25">Random 3<option>
<option value="27">Random 4<option>
</select>
Next to it is a submit button that will preform some kind of submit.
<a class="button" href="www.random.org">Click me!</a>
I need to add the ?id=
to that link, with the id value of the select. I created the code, but the issue is that it just appends the ?id=
every time I change the select the option
var id;
$('#select').on('change', function(){
id = $(this).val();
var new_href = $('.button').attr('href') + '?id=' + id;
$('.button').attr('href', new_href);
});
So when I click on first option I get, for the href
www.random.org?id=21
But if I click on second one (or any for that matter) I get
www.random.org?id=21?id=23
It appends the id. How to 'clear' the previous id on change, and replace with the selected one? What am I doing wrong?
This should work.
var id;
var original_link = "www.random.org";
$('#select').on('change', function(){
$('.button').attr('href', original_link);
id = $(this).val();
var new_href = $('.button').attr('href') + '?id=' + id;
$('.button').attr('href', new_href);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With