如果复选框启用,如何定向到其他 URL



根据这个论坛的一些建议,当我在文本框中输入时,下面的代码对我有用,它将定向到一个URL。

<script src="jquery.min.js"></script>
<script>
function test() {
if(jQuery('#inputtext').val() == 'google'){
// alert('Input can not be left blank');
window.location.href = "https://www.google.com/";
}
if(jQuery('#inputtext').val() == 'yahoo'){
// alert('Input can not be left blank');
window.location.href = "https://www.yahoo.com/";
}
else if(jQuery('#inputtext').val() == ''){
alert('Input can not be left blank');
}else if(jQuery('#inputtext').val() != ['google'||'yahoo']){
alert("INVALID Entry");
}
}
</script> 
<form id="main" name="main"><input type="text" name="inputtext" id="inputtext" placeholder="type here"/><input type="button" value="submit" onClick="test();"></form>

是否可以添加一个复选框,如果选中了带有文本输入的复选框,它应该指向另一个 URL。

例如:现在,如果我输入谷歌它指向 google.com,如果选中复选框,则需要,如果输入为谷歌,它应该定向到 gmail.com

表格如下

<form id="main" name="main">
<input type="text" name="inputtext" id="inputtext" placeholder="type here"/>
<input type="checkbox" name="inputcheckbox" id="inputcheckbox">Redirect
<input maxlength="10" type="button" value="submit" onClick="test();" ></form>

恳请指教..

对于 jQuery 1.6+:

您可以使用$('#inputcheckbox').prop('checked'))来检查复选框是否被选中。

对于 jQuery <1.6 :

$('#inputcheckbox').attr('checked')).

我正在使用change事件来检查条件,因此如果您想在提交单击时检查条件,您可以将其中的代码复制到您的提交事件/函数中。 下面是我的示例代码。

$(function() {
$('#inputtext,#inputcheckbox').change(function() {
if ($('#inputtext').val() == 'google' &&
$('#inputcheckbox').prop('checked')) {
alert('redirecting to google...')
window.location.href = "https://www.google.com/";
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="main" name="main">
<input type="text" name="inputtext" id="inputtext" placeholder="type here" />
<input type="checkbox" name="inputcheckbox" id="inputcheckbox">
<input maxlength="10" type="button" value="submit" onClick="AddPrinter();">
</form>

我不确定我是否理解您的问题,但是当用户键入"google"并选中复选框时,您似乎想将重定向URL更改为 www.gmail.com。

您可以通过以下方式实现此目的:

if($('#inputtext').val() == 'google' && $('#inputcheckbox').isChecked) {
window.location.href = "https://www.gmail.com/";
}

PS:您可以在代码中使用$而不是jQuery,它具有相同的效果并保持代码更简洁。

添加具有不同ID的复选框

<input type="checkbox" id="isAgeSelected"/>

然后使用脚本

if(document.getElementById('isAgeSelected').checked) {
window.location.href = // Some URL
}

另一种方式是

$('#isAgeSelected').click(function() {
window.location.href = // Some URL
});
<script>
function test() {
if(jQuery('#inputtext').val() == 'google' && jQuery('#inputcheckbox').isChecked){
// alert('Input can not be left blank');
window.location.href = "https://www.google.com/";
}
if(jQuery('#inputtext').val() == 'yahoo' && jQuery('#inputcheckbox').isChecked){
// alert('Input can not be left blank');
window.location.href = "https://www.yahoo.com/";
}
else if(jQuery('#inputtext').val() == ''){
alert('Input can not be left blank');
}else if(jQuery('#inputtext').val() != ['google'||'yahoo']){
alert("INVALID Entry");
}
}
</script> 

我希望我的回答对您有所帮助。

最新更新