Sean
Sean

Reputation: 59

Change href value when selecting radiobutton using a switch statement

Trying to alter the href reference in the statement depending upon which radiobutton is selected

        <ul class="size_selector">
                        <li class="top"><input type="radio" class="radioselect" name="id" id="test1" value="test1" /><label for="test1">1</label></li>
                        <li class="top"><input type="radio" class="radioselect" name="id" id="test2" value="test2"/> <label for="test2">2</label></li>
                        <li class="top"><input type="radio" class="radioselect" name="id" id="test3" value="test3"/> <label for="test3">3</label></li>
                        <li class="top"><input type="radio" class="radioselect" name="id" id="test4" value="test4"/> <label for="test4">4</label></li>
        </ul>
<a id="shopCart" href="#">
    Take me to your leader
</a>

Jquery

$("input[type='radio']").change(function(){

switch($(this).val()) {
  case "test1" :
    document.getElementById("shopCart").href="http://yahoo.com"; 
    break;
  case "test2" :
    document.getElementById("shopCart").href="http://bing.com"; 
    break;
  case "test3" :
    document.getElementById("shopCart").href="http://google.com"; 
     break;
  case "test4" :    document.getElementById("shopCart").href="http://stackoverflow.com";
    break;
  };

});

http://codepen.io/homogenizer/pen/xOrzgZ

Upvotes: 4

Views: 864

Answers (3)

Malachi
Malachi

Reputation: 3221

if you change the Value of the inputs to [0,1,2,3] you could put the links into an array and get rid of the switch statement all together and simplify your code.

HTML

<ul class="size_selector">
    <li class="top"><input type="radio" class="radioselect" name="id" id="test1" value="0" /><label for="test1">1</label></li>
    <li class="top"><input type="radio" class="radioselect" name="id" id="test2" value="1"/> <label for="test2">2</label></li>
    <li class="top"><input type="radio" class="radioselect" name="id" id="test3" value="2"/> <label for="test3">3</label></li>
    <li class="top"><input type="radio" class="radioselect" name="id" id="test4" value="3"/> <label for="test4">4</label></li>
</ul>
<a id="shopCart" href="#">
    Take me to your leader
</a>

JavaScript

var links = ["http://yahoo.com", "http://bing.com", "http://google.com", "http://stackoverflow.com"]

$("input[type='radio']").change(function(){
    $("#shopCart").attr("href", links[$(this).val()]);
});

I used the value to specify which element of the array that I wanted to take the place of the link.

This is more DRY and less redundant than your code.

Upvotes: 1

Hari Babu
Hari Babu

Reputation: 244

You can simply use
$("#shopCart").attr("href","http://yahoo.com");
and so on..

Upvotes: 1

Steven B.
Steven B.

Reputation: 9362

You're using JQuery but don't have it linked in.
Settings -> JavaScript
Add this link in https://code.jquery.com/jquery-3.1.0.min.js.

Upvotes: 1

Related Questions