选择单选按钮后重定向到特定页面

时间:2019-05-03 14:17:18

标签: javascript html redirect

我想重定向到两个页面之一,其中包含两个单独的Java基本数学函数。页面应链接到给出的两个单选按钮之一,并在用户单击“确定”按钮后重定向。

function myFunction() {
  var x = document.getElementById("x");
  var y = document.getElementById("y")

  if (x.checked = true); {
    //* redirect link when Okay button is click 
  } else(y.checked = true); {
    //* redirect link when Okay button is clicked
  }
}
<!DOCTYPE html>
<html>

<body>

  <p>What would you like to convert?</p>

  <form action="/action_page.php">
    <input type="radio" name="converter" value="grams" id="x">Grams to ounces
    <br>
    <input type="radio" name="converter" value="ounces" id="y">Ounces to grams
    <br>
    <br>
    <input type="button" onclick="myFunction()" value="Okay!">
    <br>
  </form>


</body>

</html>

3 个答案:

答案 0 :(得分:3)

您应该使用选择框,这样对您来说会更容易

<select id="myChoice">
  <option value="grams">grams</option>
  <option value="ounces">ounces</option>
</select>

和您的JS

 function myFunction() {
  var theChoice = document.getElementById("myChoice")

  switch (theChoice.value){
    case 'grams':
         //redirect;
         break;
    case 'ounces':
         //redirect
         break;
}

答案 1 :(得分:1)

很简单,只需创建类型为a的元素,放置属性并模拟click()进行重定向

这是笔示例: https://codepen.io/lucassoomago/pen/YbKwJx

下面的示例不重定向,因为不允许堆栈溢出,如果您想查看重定向,请使用上面的链接

      function myFunction() {
        var x = document.getElementById("x");
        var y = document.getElementById("y")

        var a = document.createElement("a");

        if (x.checked == true)
        {
          a.setAttribute('href', 'https://www.google.com');
          a.setAttribute('target', 'blank');
        }else if (y.checked == true)
        {
          a.setAttribute('href', 'https://www.youtube.com');
          a.setAttribute('target', 'blank');
        }
      
        a.click()
      }
     <p>What would you like to convert?</p>

    <form action="/action_page.php">
       <input type="radio" name="converter" value="grams" id="x">Grams to 
        ounces<br>
       <input type="radio" name="converter" value="ounces" id="y">Ounces to 
        grams<br>
       <br>
       <input type="button" onclick="myFunction()" value="Okay!">
       <br>
       </form>

答案 2 :(得分:0)

以下内容将检查是否选中了该复选框,然后将您重定向到您定义的URL。我使用else if是因为else将在示例中未选中任何复选框的情况下将您重定向到位置y。

<form action="/action_page.php">
    <input type="radio" name="converter" value="grams" id="x">Grams to
    ounces<br>
    <input type="radio" name="converter" value="ounces" id="y">Ounces to
    grams<br>
    <br>
    <input type="button" onclick="myFunction()" value="Okay!">
    <br>
</form>
<script>
  function myFunction() {
  var x = document.getElementById("x");
  var y = document.getElementById("y")

  if (x.checked)
  {
     window.location.replace("url");
  }
  else if (y.checked)
  {
     window.location.replace("url");
  }
  }
  </script>