How to make an ‘s string/content its value?

Here’s the code: HTML:

<input type="text" id="name" name="name" placeholder="Your Name" onblur="namerr()">
<br>
<label id="name_labl">This field is required.</label>

CSS:

#name_labl {
    display: none;
}

JavaScript:

var nameForm = document.getElementById("name").value.length;
function namerr() {
                if (nameForm < 1) {
                  document.getElementById("name_labl").style.display="block";
                  document.getElementById("name").style.borderColor="red";
            } else {
                  document.getElementById("name_labl").style.display="none";
                  document.getElementById("name").style.borderColor="black";
            }


I tried using numerous methods, ranging from using var name_form = document.forms["mailSender"]["name"].value.length; instead of document.getElementById("name").value.length; to if (nameForm==null || nameForm=="") instead of nameForm<1.

None worked.
You see, whatever I do, I always get the actual value of the <input />, like so – <input type="text" value="some value" />. However, instead of value, I’m using placeholder.
No matter what is the text inside the form, I will always get either “0” or simply nothing in case of value.length or just .value, respectively.

So I decided to make the contents of the <input type="text" /> its value and then measure the length of it to determine whether the form has been filled or not.

Any ideas about how to do that?

Answer

The value does not update automatically when it changes after you read it. You need to read it inside the function to get the newest value.

function namerr() {
    var nameForm = document.getElementById("name").value.length;
    if (nameForm < 1) {
         document.getElementById("name_labl").style.display="block";
         document.getElementById("name").style.borderColor="red";
    } else {
          document.getElementById("name_labl").style.display="none";
          document.getElementById("name").style.borderColor="black";
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *