Pardeep Pardeep - 3 months ago 10
HTML Question

javascript form validations

I am using javascript validations for required field. Here is my html

<form class="uk-form-stacked" name="myForm" action="<?php echo base_url(); ?>admin/pages/create_service" id="wizard_advanced_form" method="post" enctype="multipart/form-data" onsubmit="return myFunction(this)" novalidate>
<div data-uk-grid-margin="" class="uk-grid">
<div class="uk-width-medium-1-2">
<label for="service_title">Service Title<span class="req">*</span></label>
<input type="text" name="service_title" id="validd" class="md-input" />
<p id="demo"></p>
</div>
</div>
<div class="uk-grid">
<button type="submit" class="md-btn md-btn-primary md-btn-wave-light waves-effect waves-button waves-light" >Submit</button>
</div>
</form>


my javascript is

<script>
function myFunction(form) {
var x, text;
x = document.getElementById("validd").value;
if (x == null || x == "") {
text = "Input not valid";

}
document.getElementById("demo").innerHTML = text;
return false;

}
</script>


Now when my input field is empty and i submit form it shows me input not valid that is fine. but even when i fill some textin input then it shows me undefined in place of input not valid instead of submitting form.
please help..

Answer

You forgot to add an else where it would return true if the condition is not satisfied.

 <script>
        function myFunction(form) {
       var x, text;
       x = document.getElementById("validd").value;
       if (x == null || x == "") {
        text = "Input not valid";
        document.getElementById("demo").innerHTML = text;
         return false;
       }
        else{
          return true;
       } 
         }
 </script>