2011-09-18 59 views
1

我碰到过很多次(我不想在这里使用'输入类型按钮')为什么哦'onclick'为什么没有不调用函数check(); ?即使字段为空,页面仍然会提交。谢谢您的意见。'onclick'似乎没有用'submit'按钮调用函数

的Javascript:

function check() { 
    var name = document.getElementById('username_res'); 
    var passw_old = document.getElementById('passw_reset_old'); 
    var passw_new = document.getElementById('passw_reset'); 
    var button_res = document.getElementById('sub_res'); 

    if ((name.val() == "") && (passw_old.val().length == "") && (passw_new.val().length == "")) { 
     button_res.disabled = true; 
    } else { 
     button_res.disabled = false; 
    } 
} 

HTML:

<form id="passw_res" name="passw_res" method="post" action="pass_reset.php"> 
<fieldset style="width:300px"><br/> 
<legend id="pass_legend" align="left">Password reset</legend><br/> 
<input type="text" id="username_res" name="username_res" maxlength="50" /> 
<input type="password" id="passw_reset_old" name="passw_reset_old" maxlength="16"/> 
    <input type="password" id="passw_reset" name="passw_reset" maxlength="16" /> 
    <input type="submit" value="submit" id="sub_res" name="sub_res" onclick="check();"/> 
</fieldset> 
    </form> 

所以...页面不应该空字段提交 - 为什么它提交?谢谢..

+3

你不能使用'onsubmit'事件的原因吗? – FishBasketGordo

+0

使用'onsubmit'。并在函数中返回false;以防止在必要时提交。 –

回答

5

改变你的函数将此:

function check() { 

    var name = document.getElementById('username_res').value; 
    var passw_old = document.getElementById('passw_reset_old').value; 
    var passw_new = document.getElementById('passw_reset').value; 

    return ((name != '') && (passw_old != '') && (passw_new != '')); 

} 

你其实不必onclick事件更改为的onsubmit ,只需将其更改为onclick="return check();"即可。您需要将false返回到onclick事件以防止被触发。

您可能想要添加一些视觉增强功能来指明未提交表单的原因。否则它会让访问者感到困惑。

+0

即将编辑,但没有incase我错过了一些东西。你的var是对象,但是你可以将它们与字符串进行比较。 –

+0

你说得对。回答更新,本地测试。 – CodeCaster

+0

谢谢!是的...似乎现在工作 - onclick ='返回检查();'是正确的...我也改变了值(name.value ==“”)|| (....)改为(name.val()==“”).. –

0

您需要将按钮的类型从type =“submit”更改为type =“button”,然后在check()函数中如果一切都通过,您需要获取表单对象并提交它。

所以类似的document.getElementById( 'formID')提交()

+2

是的,对于没有启用javascript的访问者来说很棒:他们将无法发布表单。 – CodeCaster

+0

对不起,但我个人认为,不使用JavaScript糟透了...你现在怎么不使用JavaScript?我可以理解有人不想使用Flash(仍然想知道为什么'cuz Flash无论如何都可以)但JS?来吧...Facebook也一直在构建它;] –

0

你可以尝试,而不是使用表单的onsubmit功能

<form id="passw_res" action="pass_reset.php" onSubmit="check()"> 
+0

谢谢大家! –

0

页面提交,因为没有什么在你的check()脚本,将来自阻止它。您的脚本仅在验证时禁用该按钮,但到那时单击/提交已经发生,因此表单将提交。

因此,使用onsubmit='return check();',而不是禁用,根据您的验证返回true或false。如果check()返回false,那将'停止'提交操作,如果返回true,则会提交提交。

1

你正试图在stand javascript变量上调用jquery方法。

试试这个

if ((name.value == "") && (passw_old.value == "") && (passw_new.value == "")) { 
    return false; 
} else { 
    return true; 
} 

你提交按钮应该是

<input type="submit" value="submit" id="sub_res" name="sub_res" onclick="return check();"/> 
+0

谢谢 - 真我在这里混合了jQuery ... –

相关问题