Angus Grace
Angus Grace

Reputation: 13

How to get a selected option to change the href of a link using Jquery?

I'm trying to get a link to change when an option is selected using the code below, it works when I add the class to the select tag but not too the option tag. I think its probably a typo but not sure?

<script>

$(document).ready(function(){
  $(".pickau").click(function(){
    $("#trigger").attr("href", "https://www.location.com.au");
  });
});

$(document).ready(function(){
  $(".picknz").click(function(){
    $("#trigger").attr("href", "https://www.location.co.nz");
  });
});

</script> 

And my dropdown and the link I'm trying to change based on the location selected:

<label>What Country Are You In? (required)</label>
<select>
<option class="picknz">New Zealand</option>
<option class="pickau">Australia</option>
</select>  

<a href="http://www.location.co.nz/" id="trigger"><p>Location Link</p></a>

<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

Upvotes: 1

Views: 365

Answers (1)

Sameer
Sameer

Reputation: 5188

click event on option is invalid (In javascript too)

Use change event on select, also you can get value directly from option dynamically

One more thing, only one $(document).ready function is enough. You can wrap all of your code in that function

$(document).ready(function(){
  $("#mySelect").change(function(evt){
    $("#trigger").attr("href", evt.target.value);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>What Country Are You In? (required)</label>
<select id="mySelect">
<option value="https://www.location.co.nz">New Zealand</option>
<option value="https://www.location.com.au">Australia</option>
</select>  

<a href="http://www.location.co.nz/" id="trigger"><p>Location Link</p></a>

<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

Update If the second link is fixed as /help, then you can do something like

<a href="http://www.location.co.nz/help" id="triggerHelp"><p>Location Link</p></a>

$("#mySelect").change(function(evt){
 $("#trigger").attr("href", evt.target.value);
 $("#triggerHelp").attr("href", evt.target.value + '/help');
});

Upvotes: 2

Related Questions