Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace href on select change

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?

like image 647
dingo_d Avatar asked Dec 19 '22 05:12

dingo_d


1 Answers

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);
});
like image 150
Alexey Avatar answered Dec 22 '22 00:12

Alexey