3 回答
TA贡献1797条经验 获得超6个赞
表单与元素名称一起使用
const
direction =
{
Option1: 'https://www.google.com"',
Option2: 'https://facebook.com',
Option3: 'https://www.instagram.com',
Option4: 'https://www.twitter.com',
Option5: 'https://www.stackoverflow.com',
Option6: 'https://www.w3cschools.com',
Option7: 'https://www.freecodecamp.org',
Option8: 'https://www.edabit.com',
Option9: 'https://www.scrimba.com"',
Option10: 'https://www.javascript.com'
}
, myForm = document.getElementById('my-form')
;
myForm.onsubmit=e=>
{
e.preventDefault()
if (myForm.option.value)
document.location = direction[ myForm.option.value ]
}
label, button {
display: block;
float: left;
clear: both;
width: 7em;
margin: .5em;
}
input[type=radio] {
float: right;
}
<form action="" id="my-form">
<label> Option 1 <input type="radio" name="option" value="Option1" > </label>
<label> Option 2 <input type="radio" name="option" value="Option2" > </label>
<label> Option 3 <input type="radio" name="option" value="Option3" > </label>
<label> Option 4 <input type="radio" name="option" value="Option4" > </label>
<label> Option 5 <input type="radio" name="option" value="Option5" > </label>
<label> Option 6 <input type="radio" name="option" value="Option6" > </label>
<label> Option 7 <input type="radio" name="option" value="Option7" > </label>
<label> Option 8 <input type="radio" name="option" value="Option8" > </label>
<label> Option 9 <input type="radio" name="option" value="Option9" > </label>
<label> Option 10 <input type="radio" name="option" value="Option10"> </label>
<button type="submit">submit</button>
</form>
TA贡献1831条经验 获得超9个赞
使用
value=""
选项属性停止使用内联
on*=""
属性,就像您(希望)不使用内联style=""
属性一样。它很难调试,JS 应该只放在一个地方,那就是你的脚本标签或文件。查看文档位置
看看 Event.preventDefault()
不要
for=""
在不需要的时候使用。:checked
在JS中使用伪选择器.querySelector()
const EL_finalForm = document.querySelector("#final_question");
EL_finalForm.addEventListener("submit", (ev) => {
ev.preventDefault();
const EL_checked = EL_finalForm.querySelector('input[name="option"]:checked');
if (!EL_checked) return alert("Select an option");
document.location = EL_checked.value;
});
<form id="final_question">
<div class="question-container">
<label class="form-box">
<span>Option 1</span>
<input type="radio" value="https://www.google.com" name="option">
</label>
<label class="form-box">
<span>Option 2</span>
<input type="radio" value="https://www.facebook.com" name="option">
</label>
<label class="form-box">
<span>Option 3</span>
<input type="radio" value="https://www.instagram.com" name="option">
</label>
<label class="form-box">
<input type="submit" class="final_question_submit">
</label>
</div>
</form>
TA贡献1998条经验 获得超6个赞
尝试使用:
window.open("https://your.url")
而不是使用:
document.getElementById('mysubmit').href = "https://www.javascript.com";
如果你想在同一个选项卡中打开窗口:
window.open("https://www.youraddress.com","_self")
添加回答
举报