admin管理员组

文章数量:1400375

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. 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=".11.1.js"></script>
<div id="msgs">
  <ul id="messages"></ul>
</div>
<form action="">
  <div id="container">
    <input id="m" autoplete="off" /><button id="send">Send</button>
  </div>
</form>

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. 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./jquery-1.11.1.js"></script>
<div id="msgs">
  <ul id="messages"></ul>
</div>
<form action="">
  <div id="container">
    <input id="m" autoplete="off" /><button id="send">Send</button>
  </div>
</form>

thanks!

Share Improve this question edited Oct 5, 2018 at 16:08 Sivakumar Tadisetti 5,0517 gold badges38 silver badges61 bronze badges asked Oct 5, 2018 at 13:02 Michael ChenMichael Chen 371 silver badge8 bronze badges 5
  • 3 just add a required in input tag! – chintuyadavsara Commented Oct 5, 2018 at 13:08
  • 2 <input type="text" required /> – chintuyadavsara Commented Oct 5, 2018 at 13:09
  • You can also try this way stackoverflow./questions/16125255/… – Tarun Commented Oct 5, 2018 at 13:10
  • You can also try it this way Refer to this Post on stackoverflow – Tarun Commented Oct 5, 2018 at 13:13
  • In case you are looking for customised validations on your page Please refer stackoverflow./questions/19839952/… This enables you to check for all the falsey values instead of a lengthy if statement. – Nagama Inamdar Commented Oct 5, 2018 at 13:17
Add a ment  | 

7 Answers 7

Reset to default 4

You might consider using the new required attribute in HTML5:

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

For more information: https://developer.mozilla/en-US/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.

You can use length of value

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. 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. Therefor , "" will keep it disabled. read https://api.jquery./change/ about the change listener of Jquery

I don't think required is a good way since I can easily disable it by just taking a look at the html code.

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. 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

 <div id="msgs">
                    <ul id="messages"></ul>
                </div>
                <form action="">
                    <div id="container">
                        <input id="m" autoplete="off" /><button id="send">Send</button>
                    </div>
                </form>
            </body>
            <script src="/socket.io/socket.io.js"></script>
            <script src="https://code.jquery./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
    • you’ll need to add an event listener on your html element to know if there is any change. See https://developer.mozilla/en-US/docs/Web/API/EventTarget/addEventListener then based on the event you get you can check for the value using event.target.value.
  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.

Solution

Just use the required attribute on your html element. That will add basic html form validation and prevent submission when the input is empty. As long as it is in a form element. See MDN Docs on required attribute for more info.

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

Then to toggle the disabled status you could check for the validity in 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. So you might want to check on keyup or something like that. Check out the events here: https://developer.mozilla/en-US/docs/Web/API/EventTarget/addEventListener (on the left side menu under "events")

PS: Generally. Looking at your code. I would advise taking some absolute beginner courses on web development, in particular, html+css+javascript. I guess codecademy is a good place to start.

required is not a good solution because you can just turn it of in browser console I remend:

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

You can check this LINK for more info

I hope this will help you

本文标签: javascriptMake sure an input field has a value before submitStack Overflow