-1

I would like to do with HTML or Javascript not with PHP an error message when the text is empty. I have created the code ,it is a part of my code form that has a text name.I have seen tutorials or same answers here but I wasn't able to do this.

<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery-1.7.1.min.js"></script>
    <script>
   function ValidateForm() {
    if($("#onoma").val()=="") {
        $("#error_msg").html("Field needs filling");
    }              
}

    </script>

in the body parts I have this code :

<label  class="required"  for="onoma">Όνομα</label>
    <input type="text" id="onoma" name="firstname" placeholder="Your name..">
ADyson
  • 57,178
  • 14
  • 51
  • 63
ek.Nik
  • 185
  • 1
  • 8
  • when do you call ValidateForm and where is error_msg element in the body. – Mohammadreza Mohammadi Dec 08 '21 at 11:59
  • @ADyson my bad! – Babis.amas Dec 08 '21 at 12:01
  • See answer below for an easier alternative...but if you're going to use jQuery please don't use such an old, unsupported version. I guess you just copied off an old tutorial or something. Check the jQuery site for up to date info. Also, you don't even really _need_ jQuery for most simple stuff these days, vanilla JS has improved a huge amount since jQuery was invented. If you're new to this stuff you might be better to concentrate your energy on that. – ADyson Dec 08 '21 at 12:01
  • Does this answer your question? [Set custom HTML5 required field validation message](https://stackoverflow.com/questions/13798313/set-custom-html5-required-field-validation-message) – yivi Dec 09 '21 at 07:11

1 Answers1

0

One option is:

If your input textbox is inside a <form> (as it probably should be) you can just put required on the textbox and it'll validate automatically when you try to submit the form, without needing any kind of script.

Demo:

<form>
  <label class="required" for="onoma">Όνομα</label>
  <input type="text" id="onoma" name="firstname" placeholder="Your name.." required>
  <button type="submit" name="submit">Submit</button>
</form>

Documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required

There is a variety of other built-in validation functionality in HTML5 too - see https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation for an overview.

ADyson
  • 57,178
  • 14
  • 51
  • 63