简体   繁体   English

提交前确保输入字段具有值

[英]Make sure an input field has a value before submit

I want to make sure that the input has value before submit but when I use "" or 'null', it, null will not disable it and "" will keep it disabled no matter what. 我想确保输入在提交之前具有值,但是当我使用“”或“ null”时,null不会禁用它,而“”将使其保持禁用状态。 Here is my code: 这是我的代码:

 var prevScrollpos = window.pageYOffset; $(window).scroll(function() { var currentScrollPos = window.pageYOffset; if (prevScrollpos > currentScrollPos) { $("#container").fadeIn(); } else { $("#container").fadeOut(); } prevScrollpos = currentScrollPos; }); if (document.getElementById("m").value === null) { document.getElementById("send").disabled = true; } else if (document.getElementById("m").value !== null) { document.getElementById("send").disabled = false; } else { $(function() { var socket = io(); $('form').submit(function() { socket.emit('chat message', $('#m').val()); $("#m").val(""); return false; }); socket.on('chat message', function(msg) { $('#messages').append($('<li>').text(msg)); }); }); } 
 <script src="/socket.io/socket.io.js"></script> <script src="https://code.jquery.com/jquery-1.11.1.js"></script> <div id="msgs"> <ul id="messages"></ul> </div> <form action=""> <div id="container"> <input id="m" autocomplete="off" /><button id="send">Send</button> </div> </form> 

thanks! 谢谢!

You might consider using the new required attribute in HTML5: 您可以考虑在HTML5中使用新的required属性:

<input id="m" autocomplete="off" required/>

For more information: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#The_required_attribute 有关更多信息: https : //developer.mozilla.org/zh-CN/docs/Learn/HTML/Forms/Form_validation#The_required_attribute

This answer is just like an alternative technique for form data validation, cuz we have many ways to implement form data validation, from basic to advance. 这个答案就像表单数据验证的另一种方法一样,因为我们有很多方法可以实现表单数据验证,从基础到高级。

您可以使用值的长度

if (document.getElementById("m").value.length>0) concole.log('input not empty');

Im not Jquery expert and I can't understand why would you use it anyway but your problem is you don't have event listener to the elements you changing. 我不是Jquery专家,我也不明白为什么仍要使用它,但是您的问题是您没有事件监听器来更改您的元素。 It means - Javascript remember the values you had in your elements on run time, later when you change it , it cant read the new values without proper listener. 这意味着-Javascript记住运行时元素中的值,以后在更改它时,如果没有适当的侦听器,它将无法读取新值。 Therefor , "" will keep it disabled. 因此, ""将使其保持禁用状态。 read https://api.jquery.com/change/ about the change listener of Jquery 阅读https://api.jquery.com/change/有关Jquery的change侦听器

I don't think required is a good way since I can easily disable it by just taking a look at the html code. 我认为不是必需的一种好方法,因为我可以通过查看html代码轻松地禁用它。

So what you should do instead is add an event listener. 因此,您应该做的是添加一个事件侦听器。 Each time your user types something you check if the input is empty or not. 每次用户键入内容时,您都会检查input是否为空。 If it is you disable the button, if it isn't you activate the button. 如果是,则禁用该按钮,如果不是,则激活该按钮。

And also: Always check in the backend aswell!!! 还有:总是还要检查后端!!!

please use if (document.getElementById("m").value == '') instead of yours 请使用if(document.getElementById(“ m”)。value =='')代替您的

 <div id="msgs">
                    <ul id="messages"></ul>
                </div>
                <form action="">
                    <div id="container">
                        <input id="m" autocomplete="off" /><button id="send">Send</button>
                    </div>
                </form>
            </body>
            <script src="/socket.io/socket.io.js"></script>
            <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
            <script>

                var prevScrollpos = window.pageYOffset;
                $(window).scroll(function () {
                    var currentScrollPos = window.pageYOffset;
                    if (prevScrollpos > currentScrollPos) {
                        $("#container").fadeIn();
                    } else {
                        $("#container").fadeOut();
                    }
                    prevScrollpos = currentScrollPos;

                });
    runcheck();  
    $("#m").keyup(function(){
    runcheck();
    });





    function runcheck(){
    if (document.getElementById("m").value == '') {
                    document.getElementById("send").disabled = true;
                }
                else if (document.getElementById("m").value != null) {
                    document.getElementById("send").disabled = false;
                }  else {
                    $(function () {
                        var socket = io();
                        $('form').submit(function () {
                            socket.emit('chat message', $('#m').val());
                            $("#m").val("");
                            return false;
                        });
    socket.on('chat message', function (msg) {
                    $('#messages').append($('<li>').text(msg));

                });

                    });
                }
    }


            </script>

Problem 问题

In your example code, I can see several problems. 在您的示例代码中,我可以看到几个问题。

  1. It does not seem as if you have a listener for changes on the imput 好像您没有听众了解输入的更改
  2. Your value checking is wrong 您的价值检查不正确
    • You can check if fields have values by doing just if(document.getElementById("m").value) no need for === null . 您可以通过执行if(document.getElementById("m").value)不需要=== null来检查字段是否具有值。

Solution

Just use the required attribute on your html element. 只需在html元素上使用required属性即可。 That will add basic html form validation and prevent submission when the input is empty. 这将添加基本的html表单验证,并在输入为空时阻止提交。 As long as it is in a form element. 只要是表单元素即可。 See MDN Docs on required attribute for more info. 有关更多信息,请参见必填属性上的MDN文档

<input id="m" autocomplete="off" required/>

Then to toggle the disabled status you could check for the validity in JavaScript. 然后,要切换禁用状态,您可以检查JavaScript的有效性。 Here is an untested pseudocode: 这是未经测试的伪代码:

const sendButton = document.querySelector('#send');  // grab the button
const mInput = document.querySelector('#m');  // grab the input

sendButton.disabled = true;  // disable it by default

mInput.addEventListener('change', event => {  // as soon as the input value changes
  sendButton.disabled = !event.target.checkValidity();  // set the disabled state based on the validity of the input field (event.target is the input field) (the little exclamation mark before the validity check means "not". !true === false and !false === true
});

Note that in most browsers the change listener only triggers when the focus changed to another element. 请注意,在大多数浏览器中, change侦听器仅在焦点更改为另一个元素时触发。 So you might want to check on keyup or something like that. 因此,您可能需要检查keyup或类似的内容。 Check out the events here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener (on the left side menu under "events") 在此处查看事件: https : //developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener (在“事件”下的左侧菜单上)

PS: Generally. PS:通常。 Looking at your code. 查看您的代码。 I would advise taking some absolute beginner courses on web development, in particular, html+css+javascript. 我建议您参加一些有关Web开发的绝对入门课程,尤其是html + css + javascript。 I guess codecademy is a good place to start. 我想codecademy是一个不错的起点。

required is not a good solution because you can just turn it of in browser console I recommend: 必需不是一个好的解决方案,因为您可以在浏览器控制台中将其关闭,我建议:

if (document.getElementById("m").value == '') { //code here... }

You can check this LINK for more info 您可以检查此链接以获取更多信息

I hope this will help you 我希望这能帮到您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM