[英]Redirect a user on form submit based on a value in a radio button in the form
我需要制作一个使用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>
这个想法是用我从选中的单选按钮获得的值打开窗口位置。 这可能是完全错误的方法。 没用... :-)
您的选择器有点关。 请尝试以下操作:
$('input[name="redirect"]:checked').val();
此JSFiddle可能会帮助:
你可以试试看
$( "#mychoice" ).submit(function( event ) {
event.preventDefault();
window.location = $('input[type="radio"]:checked').val();
});
使用按钮而不是提交
<input type="button" id="submit" value="Go"> </form>
<script>
$( "#submit" ).click(function( event ) {
window.location = $('input[type="radio"]:checked').val();
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.