Changing the href value when selecting a radio using the switch statement

Attempting to change the href link in a statement, depending on which camera 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

+4
source share
3 answers

You are using jQuery but not connecting it.
Settings → JavaScript
Add this link to https://code.jquery.com/jquery-3.1.0.min.js .

+1
source

You can just use $("#shopCart").attr("href","http://yahoo.com");etc.

+1
source

[0,1,2,3], switch .

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 indicate which element of the array I would like to replace.

This is more DRY and less redundant than your code.

+1
source

Source: https://habr.com/ru/post/1651231/


All Articles