【发布时间】:2015-04-17 04:51:55
【问题描述】:
我需要制作一个使用 javascript 提交的简单表单,以将用户重定向到正确的页面。
它有一个单选按钮列表,提交时我需要将用户重定向到为每个单选按钮指定的页面 URL。
看起来像这样:
我找到了一个使用 jquery 来执行此操作的 javascript,但这是在单击单选按钮时触发的。我需要有一个提交按钮。
我认为这很容易做到,而且可能是,但不知何故我找不到解决方案。
这是我使用的代码(我在 SO 上的其他地方找到了该代码,并且可以正常工作。但是没有“提交”按钮。):
I value the most:
<form>
<input type="radio" name="redirect" value="http://example.com/food"><span>eating food</span><br>
<input type="radio" name="redirect" value="http://example.com/kids"><span>play with my kids</span><br>
<input type="radio" name="redirect" value="http://example.com/fishing"><span>go fishing</span><br>
<input type="radio" name="redirect" value="http://example.com/stackoverflow"><span>answer StackOverflow questions</span><br>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$('input[type="radio"]').on('click', function() {
window.location = $(this).val();
});
</script>
我应该可以使用这个:https://api.jquery.com/submit/ 但我不明白如何同时触发提交和获取正确的单选值,然后重定向。
我可以以某种方式使用上面的代码,还是需要用完全不同的方法来实现它?
我试过这个:
I value the most:
<form id="mychoice">
<input type="radio" name="redirect" value="http://example.com/food"><span>eating food</span><br>
<input type="radio" name="redirect" value="http://example.com/kids"><span>play with my kids</span><br>
<input type="radio" name="redirect" value="http://example.com/fishing"><span>go fishing</span><br>
<input type="radio" name="redirect" value="http://example.com/stackoverflow"><span>answer StackOverflow questions</span><br>
<input type="submit" value="Go">
</form>
<script>
$( "#mychoice" ).submit(function( event ) {
window.location = $('input[type="radio"]:checked').val();
});
</script>
这个想法是用我从选中的单选按钮中获得的值打开窗口位置。这可能是完全错误的方法。没用... :-)
【问题讨论】:
-
你为什么使用表格?您想将数据发布到这些地址吗?如果没有,为什么不直接使用锚标签?
-
是我的客户指定他们想要这样。他们希望它看起来和行为像带有单选按钮的常规表单。他们不希望在用户实际点击提交按钮之前提交。
-
你只需要阻止默认的提交事件。在提交事件处理程序中尝试
event.preventDefault()。
标签: javascript jquery