Michael Chen
Michael Chen

Reputation: 37

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

Upvotes: 1

Views: 3095

Answers (7)

chitzui
chitzui

Reputation: 4098

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.

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" autocomplete="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.org/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.

Upvotes: 1

J.vee
J.vee

Reputation: 619

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

Upvotes: 0

Abhishek Gupta
Abhishek Gupta

Reputation: 109

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

Upvotes: 1

Aaron3219
Aaron3219

Reputation: 2215

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

Upvotes: 1

obiwankenoobi
obiwankenoobi

Reputation: 1582

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.com/change/ about the change listener of Jquery

Upvotes: 1

Evgeniy Belov
Evgeniy Belov

Reputation: 358

You can use length of value

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

Upvotes: 1

Tu Nguyen
Tu Nguyen

Reputation: 10179

You might consider using the new required attribute in HTML5:

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

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

Upvotes: 4

Related Questions