这两个功能完美地工作,但我只能一次使用一个,表单应该检查密码并根据所选的单选按钮将用户链接到其他页面。有没有办法让它发挥作用?
验证密码的功能。
function check()
{
var password=document.getElementById('password');
var confirm=document.getElementById('confirm');
if(password==confirm)
{
return true;
}
else
{
alert('Password do not match');
return false;
}
}
功能2:根据选择将用户引导至2个不同的html页面
function doSubmit(form)
{
var urls = form['url'];
var i = urls && urls.length;
while (i--)
{
if (urls[i].checked)
{
window.location = urls[i].value;
}
}
return false;
}
这是html代码(我只包括与这些功能相关的部分)
<form action="" onsubmit="return check()">
<label for="password">Password</label>
<input type="password" id="password" maxlength="20" size="10" required="true" pattern=".{7,}" title="Password should be atleast 7 characters long"/>
<br /><br />
<label for="confirm">Confirm Password</label>
<input type="password" id="confirm"" maxlength="20" size="10" required="true" />
<label for="mcq">MCQ</label>
Beginner<input type="radio" name="url" value="begin" id="rdbegin" value="beginner.html"required="true"/>
<br />
Expert<input type="radio" name="url" value="expert" id="rdexpert" value="expert.html"required="true"/>
<br /><br />
<button type="submit" id="submit">Submit</button>
</form>
答案 0 :(得分:0)
修改强>
尝试此操作以获取单选按钮值:
function doSubmit(form)
{
var urls = form['url'];
console.log(urls.value);
window.location = urls.value;
}
还可以使用.value
获取密码值:
var password=document.getElementById('password').value;
否则以下情况将始终为假:
if(password==confirm) // because you were comparing two html nodes
这是 working DEMO 。
您可以在验证后在第一个函数内调用第二个函数,如下所示:
function check()
{
var password=document.getElementById('password');
var confirm=document.getElementById('confirm');
if(password==confirm)
{
var form = document.getElementById('form'); //give id="form" to your form
doSubmit(form);
return true;
}
else
{
alert('Password do not match');
return false;
}
}
对于onSubmit()
函数,避免使用会导致无限循环的while
循环,因为i--
将始终为真,您可以这样做:
var urls = form['url'];
for(var i=0; urls[i]; ++i){
if(urls[i].checked){
console.log(urls[i].value); //try printing the url and see what it gets
window.location = urls[i].value; // also change this to urls[i]
break;
}
}