javascript Javascript检查空表单元素,如果为空则拒绝提交,发送警报消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14248398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:08:30  来源:igfitidea点击:

Javascript to check for empty form elements, deny submit if empty, send alert message

javascriptformsalert

提问by jddg5wa

So I've been looking around at code and seeing what is possible through javascript. I have a code that currently checks if a form has empty elements and denies it to be submitted if any are empty. The thing is I tried to add an alert if the elements were empty and an alert if the elements were not empty but it did not work. I don't seem to know enough about java script to go about editing it.

所以我一直在环顾代码,看看通过 javascript 有什么可能。我有一个代码,当前检查表单是否有空元素,如果有空元素则拒绝提交。问题是我尝试在元素为空时添加警报,如果元素不为空则添加警报但它不起作用。我似乎对 Java 脚本了解得不够多,无法进行编辑。

Here is the form. Ignore the weird class and div names, they are set that way because the form submits to a google doc spreadsheet.

这是表格。忽略奇怪的类和 div 名称,它们是这样设置的,因为表单提交到 google doc 电子表格。

<form class="quickemailform" action="https://docs.google.com/spreadsheet/formResponse?formkey=dGp3YUxCTGtWd251ZXVfOEtwc1hhWVE6MQ&amp;ifq" method="post" target="hidden_iframe" onsubmit="submitted=true;" id="ss-form" name="frm1" onsubmit="InputChecker()">
        <br>
        <div class="errorbox-good">
            <div class="ss-item ss-item-required ss-text">
                <div class="ss-form-entry">
                    <label class="ss-q-title" for="entry_0">
                    <font class="formtitles">FULL NAME:</font>
                    </br>
                    <label class="ss-q-help" for="entry_0"></label>
                    <input type="text" name="entry.0.single" value="" class="ss-q-short" id="entry_0" size="42">
                </div>
            </div>
        </div>
        <div class="errorbox-good">
            <div class="ss-item ss-item-required ss-text">
                <div class="ss-form-entry">
                    <label class="ss-q-title" for="entry_1">
                        <font class="formtitles" id="compnam">COMPANY NAME:</font>
                        </br>
                    <label class="ss-q-help" for="entry_1"></label>
                    <input type="text" name="entry.1.single" value="" class="ss-q-short" id="entry_1" size="42">
                </div>
            </div>
        </div>
        <div class="errorbox-good">
            <div class="ss-item ss-item-required ss-text">
                <div class="ss-form-entry">
                    <label class="ss-q-title" for="entry_2">
                        <font class="formtitles"  id="emailadd">EMAIL ADDRESS:</font>
                        <br>
                    <label class="ss-q-help" for="entry_2"></label>
                    <input type="text" name="entry.2.single" value="" class="ss-q-short" id="entry_2" size="42">
                </div>
            </div>
        </div>
        <div class="errorbox-good">
            <div class="ss-item ss-item-required ss-paragraph-text">
                <div class="ss-form-entry">
                    <label class="ss-q-title" for="entry_3">
                        <font class="formtitles"  id="request">Your Request:</font>
                        <font class="fineprint">( SUMMARIZE IMPORTANT DETAILS )</font>
                        <br>
                    </label>
                    <label class="ss-q-help" for="entry_3"></label>
                    <textarea name="entry.3.single" cols="32" rows="10" class="ss-q-long" id="entry_3"></textarea>
                </div>
            </div>
        </div>
            <input type="hidden" name="pageNumber" value="0">
            <input type="hidden" name="backupCache" value="">

        <div class="ss-item ss-navigate"><div class="ss-form-entry">
                <input class="submitbuttons" type="submit" name="submit" value="&nbsp;" src="" border="0" onclick="myFunction()"  />
            </div>
        </div>
    </form>

Here is the javascript that denies the form to be submitted if any fields are empty. I got this code online, I did not write it myself. It is tested and works but I want it to do more than just deny submission.

如果任何字段为空,这是拒绝提交表单的javascript。这段代码是网上找的,不是我自己写的。它已经过测试并且有效,但我希望它做的不仅仅是拒绝提交。

<script type="text/javascript">

              (function() {
        var divs = document.getElementById('ss-form').
        getElementsByTagName('div');
        var numDivs = divs.length;
        for (var j = 0; j < numDivs; j++) {
        if (divs[j].className == 'errorbox-bad') {
        divs[j].lastChild.firstChild.lastChild.focus();
        return;
        }
        }
        for (var i = 0; i < numDivs; i++) {
        var div = divs[i];
        if (div.className == 'ss-form-entry' &&
        div.firstChild &&
        div.firstChild.className == 'ss-q-title') {
        div.lastChild.focus();
        return;
        }
        }
        })();
    </script>

If possible I want to know how I can add an alert for when the form is denied or accepted. Also if the form is denied I would like to have it so that I have something like

如果可能,我想知道如何为表单被拒绝或接受时添加警报。另外,如果表格被拒绝,我想拥有它,以便我有类似的东西

<font class="asterick" div="your_name_ast">*</font>   or   <font class="asterick" div="company_name_ast">*</font>

and have the asterick show up next to each empty element if the form is denied not submitted. Such as having the form check each element to be empty or not. If the script finds the element to be empty an alert would pop up saying "Form is not filled. Please look over all elements with a *." and then it would have the asterisk appear.

如果表单被拒绝未提交,则在每个空元素旁边显示星号。例如让表单检查每个元素是否为空。如果脚本发现元素为空,则会弹出一个警告,提示“表单未填写。请查看所有带有 * 的元素。” 然后它会出现星号。

Thanks to anyone that has read this far.

感谢任何读到这里的人。

EDIT: Doing some looking around more and it seems that alerts are considered bad practice. Is this true? Is there some other way I might go about letting users know if the elements are empty?

编辑:做一些环顾四周,似乎警报被认为是不好的做法。这是真的?我是否可以通过其他方式让用户知道元素是否为空?

采纳答案by El Cas

You could use jQuery Validate (or similar) like EdSF mention or you could just change the submit button into a regular button that when click it calls a function to validate your fields and if non are empty submit the form. I haven't tested the following code, but you get the idea.

您可以使用像 EdSF 提到的 jQuery Validate(或类似的),或者您可以将提交按钮更改为常规按钮,单击时它会调用一个函数来验证您的字段,如果非空提交表单。我还没有测试以下代码,但你明白了。

function validateForm(){
  var isValid = true;

  var elements = document.getElementById('ss-form').getElementsByTagName('input');

  for(var i=0; i < elements.length; i++){
    if(elements[i].value.length < 1){
      isValid = false;
    }
  }

  if(isValid){
    document.getElementById('ss-form').submit();
  }
  else {
    alert('Please fill all required fields');
  }
}

回答by ROY Finley

Using jQuery you could accomplish everything you want to do. jQuery is very easy to learn. Here is a sample of your code using jQuery:

使用 jQuery,您可以完成您想做的一切。jQuery 非常容易学习。以下是使用 jQuery 的代码示例:

This is a very minimal example of what you can do.

这是您可以做什么的一个非常小的例子。

 <!DOCTYPE html>
<html lang="en">
  <head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){

$('#entry_0').blur(function()
{
var Fullname = $(this).val();
$('#nameresult').css("display","none");
if(Fullname.length>0)
    {
    $('#nameresult').css("display","inline-block");
    $('#nameresult').css("color","#00BB00");
    $('#nameresult').html("Valid")
    return true;
    }
    $('#nameresult').css("display","inline-block");
    $('#nameresult').css("color","#ff0000");
    $('#nameresult').html("Input Needed")
    $(this).focus();
    return;    
    });


$('#entry_1').blur(function()
{
var Companyname = $(this).val();
$('#companyresult').css("display","none");
if(Companyname.length>0)
    {
    $('#companyresult').css("display","inline-block");
    $('#companyresult').css("color","#00BB00");
    $('#companyresult').html("Valid")
    return true;
    }
    $('#companyresult').css("display","inline-block");
    $('#companyresult').css("color","#ff0000");
    $('#companyresult').html("Input Needed")
    $(this).focus();
    return;    
    });

  });

</script>
  </head>
  <body>
<form >
FULL NAME:<input type="text" name="entry.0.single" value="" class="ss-q-short" id="entry_0" size="42">
<div id="nameresult" style="display: none;"></div>
<br>

COMPANY NAME:<input type="text" name="entry.1.single" value="" class="ss-q-short" id="entry_1" size="42">
<div id="companyresult" style="display:none;"></div>
<br>

EMAIL ADDRESS:<input type="text" name="entry.2.single" value="" class="ss-q-short" id="entry_2" size="42"><br>

Your Request:<textarea name="entry.3.single" cols="32" rows="10" class="ss-q-long" id="entry_3"></textarea><br><br>

<input class="submitbuttons" type="submit" name="submit" value="SUBMIT" src="" border="0" />

    </form>
  </body>
</html>

Please forgive the code formatting, I typed it up very quickly.

请原谅代码格式,我输入的很快。

Here is a link to jQuery

这是jQuery的链接

回答by DanDel

Here is a working model that I've used on an email encrypting site: http://jsfiddle.net/2b6d5/46/

这是我在电子邮件加密站点上使用的工作模型:http: //jsfiddle.net/2b6d5/46/

Feel free to add to it, change it... post any forks/updates here. :)

随意添加,更改它......在这里发布任何分支/更新。:)

/*
 * validate an e-mail address by leveraging the HTML5
 * input element with type "email"
 */

function validate() {
  var input = document.createElement('input');
  input.type='email';
  input.value=document.getElementById('valid').value;

  if (input.checkValidity()) {
    document.getElementById('address').style.background = 'green';
  } else {
    document.getElementById('address').style.background = 'red';
  }

  return false;
}

function val2(){
      var input = document.createElement('input');
  input.type='email';
  input.value=document.getElementById('valid').value;
    if (input.checkValidity()) {
    return true;
  } else {
    alert("Not a valid e-mail address");  
    return false;
}
}