Javascript onclick提交按钮,检查输入是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32655327/
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-08-23 14:03:20  来源:igfitidea点击:

onclick submit button, check if an input is empty

javascript

提问by Kalif Vaughn

I've searched and tried just about everything and nothing works. I'm just trying to have this happen:

我已经搜索并尝试了几乎所有的东西,但没有任何效果。我只是想让这种情况发生:

onclick a submit button --> check to see if a text field is empty --> if it is, alert an error and do not advance to the next page (if not, advance but only if the values are between 0 - 100 numerically.

onclick 提交按钮 --> 检查文本字段是否为空 --> 如果是,则警告错误并且不要前进到下一页(如果不是,则前进但仅当数值在 0 - 100 之间时) .

Here's what I've got right now (other code I've found that works):

这是我现在所拥有的(我发现其他有效的代码):

<form name="agencytrial">
    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" onchange="handleChange(this)"; />
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="checkField()";  />
    </div>
</form>

<script>
    function handleChange(input) {
        if (input.value < 0) alert("Value should be between 0 - 100");
        if (input.value > 100) alert("Value should be between 0 - 100");
    }
</script>

The above code works fine, and ifsomeone types something into the field, and ifit is not between 0 - 100, then it will alert and error and NOT advance the page.

上面的代码工作正常,如果有人在字段中输入了一些东西,如果它不在 0 - 100 之间,那么它会发出警报和错误,而不是推进页面。

But if no one types anything, they can just click the submit button and advance the page, and the above code does nothing to stop that. So I tried to use something like the following (one of many attempts):

但是如果没有人输入任何东西,他们只需点击提交按钮并前进页面,上面的代码并没有阻止它。所以我尝试使用以下内容(许多尝试之一):

<script type = "text/javascript">
    function checkField(){
        var x = document.getElementById("AgencyField");
        if (var x = ""){
            alert("Value should be between 0 - 100");
            return false;
        }else{
            return true;
        }
</script>

The above code fails, and they can just click the submit button and advance without typing anything into the field.

上面的代码失败了,他们只需单击提交按钮即可前进,而无需在该字段中输入任何内容。

Any help would be majorly appreciated!

任何帮助将不胜感激!

------------EDIT--------------

- - - - - - 编辑 - - - - - - -

Based on everyone's comments, I've rewritten my code and it's very close. BUT HERE'S WHAT I DON'T GET:

根据大家的评论,我已经重写了我的代码,并且非常接近。但这是我没有得到的:

When I input number > 100, it alerts message and DOES NOT ADVANCE.

当我输入数字 > 100 时,它会提示消息并且不会前进。

When I leave it blank, it alerts message and ADVANCES.

当我将其留空时,它会提醒消息和 ADVANCES。

Why the difference?

为什么会有差异?

<form name="agencytrial">
    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value=""   autocomplete="off" class="forceNumeric" onchange="handleChange(this)"/>
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="handleChange()">
    </div>
</form>

<script>
  function handleChange(input){
  var x = document.getElementById("AgencyField").value;
    if (x < 0 || x > 100 || x === "") alert("Value should be between 0 - 100");
    }
</script>

-------EDIT #2--------

-------编辑#2--------

Here's all my code below. I am just using "form onsubmit" and the "onclick" codes now, as the onchange code was not going to stop the key or the button from being clicked with the form being empty (i.e., never modified).

下面是我所有的代码。我现在只使用“form onsubmit”和“onclick”代码,因为onchange代码不会阻止键或按钮在表单为空(即从未修改)的情况下被点击。

I've got the alert popping up with either or the button being clicked, but the page always advances after I close the alert.

我已经通过单击或单击按钮弹出警报,但是在我关闭警报后页面总是前进。

<?php
    $compTime = 8;                  // time in seconds to use for 'computer' timing
    if ($text === '') { $text = 'How likely was it that you caused the tone to occur?|Type your response on a scale from 0-100.'; }
    $texts = explode('|', $text);
    $mainText = array_shift($texts);
?>
<!DOCTYPE html>
<html>
<form onsubmit="return handleChange();">
    <div class="textcenter">
        <h3><?php echo $mainText; ?></h3>
        <?php
            foreach ($texts as $t) {
                echo '<p>' . $t . '</p>';
            }
        ?>
    </div>

    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric"/>
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="return handleChange()"/>
    </div>
</form>

<style type="text/css">
img {
    display: block;
    position: relative;
    bottom: -40px;
    left: -21px;
    max-width:520px;
    max-height:520px;
    width: auto;
    height: auto;
}
</style>

<body>
<img src="/tapa/Experiment/images/scale.jpg"</img>
</body>
</html>


<script type="text/javascript">
function handleChange(input) {
    var x = document.getElementById("AgencyField").value;
    if (x === "" || x < 0 || x > 100) {
        alert("Value should be between 0 - 100");
        return false;
    }
   return true;
}
</script>

*****EDIT*****

*****编辑*****

I have solved the problem using a new script. Thanks to everyone and the solutions provided would usually work, but just not in my case for reasons not entirely clear to me but not worth explaining.

我已经使用新脚本解决了这个问题。多亏了所有人,所提供的解决方案通常会奏效,但就我而言并非如此,原因我不完全清楚但不值得解释。

采纳答案by acdcjunior

Updated question:

更新的问题:

When I input number > 100, it alerts message and DOES NOT ADVANCE.

当我输入数字 > 100 时,它会提示消息并且不会前进。

When you input a number > 100and click submit, it will trigger the onchange. It won't even trigger the submit button.

当您输入一个数字 >100并单击 时submit,它会触发onchange. 它甚至不会触发提交按钮。

When I leave it blank, it alerts message and ADVANCES.

当我将其留空时,它会提醒消息和 ADVANCES。

It advances because you don't tell it not to. To do that, you have to return falseon the onclickevent (see fix below).

它进步是因为你没有告诉它不要。要做到这一点,你必须返回falseonclick事件(见下文修复)。

Fix:

使固定:

Add returnto #FormSubmitButton's onclick:

添加return#FormSubmitButtononclick

<input class="button" id="FormSubmitButton" type="submit"
                                            value="Submit" onclick="return handleChange()">
                                                                    ^^^^^^-- add this

Add returns to the JavaScript function:

return在 JavaScript 函数中添加s:

function handleChange(input) {
    var x = document.getElementById("AgencyField").value;
    if (x < 0 || x > 100 || x === "") {
        alert("Value should be between 0 - 100");
        return false;
    }
    return true;
}

Check updated demo fiddlehere.

在此处检查更新的演示小提琴



Original question

原始问题

Several issues:

几个问题:

var x = document.getElementById("AgencyField");

This way, x only gets a reference to the #AgencyFieldelement. You don't want that, you want its value: var x = document.getElementById("AgencyField").value;

这样, x 只获得对#AgencyField元素的引用。你不想要那个,你想要它的价值:var x = document.getElementById("AgencyField").value;

Also, you are doing an assignment in your if, not a comparison:

此外,您正在您的 中进行赋值if,而不是比较:

if (var x = ""){

This line should be if (x === ""){.

这条线应该是if (x === ""){

Your function checkField() {also is missing an ending }.

function checkField() {也缺少一个结局}

Most important, and subttle, is:

最重要和微妙的是:

<input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="checkField()"; />

You should have a returnthere (also remove that ;):

你应该有一个return(也删除那个;):

<input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="return checkField()"/>

All in all, check an updatedworking fiddle here. There are more changes, they all are shown below (in the comments).

总而言之,在这里检查更新的工作小提琴。还有更多变化,它们都显示在下面(在评论中)。

Fixed JavaScript:

固定 JavaScript:

function handleChange(input) {
    if (input.value.length < 0) { // added .length
        alert("Value should be between 0 - 100");
        return false; // added this
    }
    if (input.value.length > 100-1) { // added .length AND added -1
        alert("Value should be between 0 - 100");
        return false; // added this
    }
    return true; // added this
}

function checkField() {
    var x = document.getElementById("AgencyField").value; // added .value
    if (x === "") { // if (var x = "") -> if (x === "")
        alert("Value should be between 0 - 100");
        return false;
    } else {
        return true;
    }
} // added this }

Fixed HTML:

固定 HTML:

<form name="agencytrial">
    <div class="textcenter">
        <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" onkeypress="return handleChange(this)" ; />
        <input class="button" id="FormSubmitButton" type="submit" value="Submit" onclick="return checkField()" />
    </div>
</form>
<!-- Changes to HTML elements:
#FormSubmitButton
- removed ; at the end
- added return to onclick
#AgencyField
- changed onchange to onkeypress
- added return
-->

回答by Tommyixi

You should be using the === sign (not the "=" sign). Right now you are conditionally setting x equal to an empty string, not checking if a value exists.

您应该使用 === 符号(而不是“=”符号)。现在您有条件地将 x 设置为一个空字符串,而不是检查值是否存在。

if (var x = ""){

But it should look like

但它应该看起来像

if (x === ""){

回答by adrield

Try this:

尝试这个:

<script>
    function handleChange(input) {
        if (input.value < 0 || input.value > 100 || isNaN(input.value)) {
           alert("Value should be between 0 - 100");
        }
    }
</script>

Why:

为什么:

isNan()is a Javascript function that returns if given parameter is a number. If it's less than 0 OR more than 100 OR not a number, than the message shows up!

isNan()是一个 Javascript 函数,如果给定的参数是一个数字,它就会返回。如果它小于 0 或大于 100 或不是数字,则会显示消息!

回答by adrield

Try onsubmit handler:

尝试提交处理程序:

var validate = function(form) {
  var agency = +(form.AgencyField.value) || '';
  if (!agency) {
    alert('Agency has to numeric !');
    return false;
  } else if (0 > agency || 100 < agency) {
    alert('Agency must be between 0 - 100');
    return false;
  } else {
    return true;
  }
};
<form name="agencytrial" onsubmit="return validate(this);">
  <div class="textcenter">
    <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" />
    <input class="button" type="submit" value="Submit" />
  </div>
</form>

回答by Rokt33r

This is my solution.

这是我的解决方案。

            <form name="agencytrial" onsubmit="return checkField()">
            <div class="textcenter">
                <input name="AgencyRating" id="AgencyField" type="text" value="" autocomplete="off" class="forceNumeric" onchange="handleChange(this)">
                <input class="button" id="FormSubmitButton" type="submit" value="Submit">
            </div>
            </form>

            <script>
            function handleChange(input) {
              if (!(parseInt(input.value) >= 0 && parseInt(input.value) <= 100)) alert("Value should be between 0 - 100");
            }
            function checkField(){
              var input = document.getElementById("AgencyField");

              if (!(parseInt(input.value) >= 0 && parseInt(input.value) <= 100)) {
                alert("Value should be between 0 - 100")
                return false
              }
              return true
            }
            </script>
  1. I use onsubmitinstead of onclick.
  2. onsubmitmust return false if you want to do nothing.
  3. parseIntmakes validation easy.
  1. 我使用onsubmit代替onclick.
  2. onsubmit如果您什么都不做,则必须返回 false。
  3. parseInt使验证变得容易。

Have a nice day.

祝你今天过得愉快。