【问题标题】:jQuery Input ValidationjQuery 输入验证
【发布时间】:2015-03-23 21:41:48
【问题描述】:

我正在尝试确保表单上的输入不为空。我正在使用 jQuery 检查输入,但它没有检查输入。提交按钮允许它通过:

<form id="preenrollment-airlines" name="preenrollment-airlines" class="tn-form-conversion" method="post" action="#" onSubmit="return(validate());">
<div class="form-col">
    <input id="firstName" name="firstName" onFocus="if (this.value=='firstName') this.value = ''" type="text" placeholder="First name*">
</div>
<div class="form-col">
    <input id="lastName" type="text" name="lastName" onfocus="if (this.value=='lastName') this.value = ''" type="text" placeholder="Last name*" />
</div>
<div class="form-col">
    <input id="addr" type="text" name="address" onfocus="if (this.value=='address') this.value = ''" type="text" placeholder="Address*" />
</div>
<div class="form-col">
    <input id="city" type="text" name="city" onfocus="if (this.value=='city') this.value = ''" type="text" placeholder="City*" />
</div>
<div class="form-col">
    <input id="zip" type="text" name="postalCode" onfocus="if (this.value=='postalCode') this.value = ''" type="text" placeholder="Postal Code*" />
</div>
<div class="form-col">
    <input id="dm" type="text" name="dm" onfocus="if (this.value=='dm') this.value = ''" type="text" placeholder="DM # * (Bottom left corner of your letter)" id="dm" />
</div>
<div class="form-col">
    <input id="email" type="text" name="email" onfocus="if (this.value=='email') this.value = ''" type="text" placeholder="Email*" />
</div>
<div class="form-col">
    <input type="text" name="digits" onfocus="if (this.value=='digits') this.value = ''" type="text" placeholder="Last 4 digits of current BMO AIR MILES World credit card*" id="digits" />
</div>
</div>
<div class="clear"></div>
<input type="hidden" name="formName" id="formName_id" value="preenrollment-airlines" />
<div style="clear: both;">
    <br />
    <div style="text-align: center;">
        <input id="submit" style="margin-top: 25px;" class="primary button" type="submit" value="Submit" />
    </div>
</div>

这是我目前拥有的 javascript:

$(文档).ready(函数() { $('#preenrollment-airlines 输入').blur(function () { if ($(this).val().length === 0) { $(this).parents('input').addClass('warning'); } }); });

我不知道从这里去哪里。我不能使用任何插件来进行验证,所以我需要检查输入是否为空,然后我可以添加一个类。

【问题讨论】:

  • 你试过没有.parents('input')吗?你已经选择了input,所以你不会有任何input类型的祖先。

标签: javascript html forms input


【解决方案1】:

您想要捕获 Submit 事件以防止发送表单。在此函数中,您可以检查以确保输入全部有效。

有关提交事件以及如何使用 jQuery 捕获它的更多信息, view the docs here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多