Not able to verify if input field is empty or not after clicking the sumbit button
I am basically checking to see if the input field(fullName) is empty or not. If it is empty, then I want to disable the submit button, and forcing the user to add text in the FullName field.
To achieve this scenario, I did the following(code below), but when testing, I am still able to click the submit button, even if the FullName field is empty. I am not sure, what I am doing wrong with the JavaScript code.
I am doing all of this inside an .htm file.
function checkform(form) { if (form.FullName.value == "") { alert("Please enter your name!"); form.FullName.focus(); return false; } return true; }
<fieldset> <div class="form-group"> <label class="" for="FullName">Name <span class="required">*</span></label> <input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1"> </div> </fieldset>
Answer
Your JS is ok. There are some changes –
First, wrap the form content in a form
with a name attribute of form
.
Next, fire the checkform
function on clicking the submit button.
Check the snippet below-
function checkform(form) { if (form.FullName.value == "") { alert("Please enter your name!"); form.FullName.focus(); return false; } return true; }
<div id="Wrapp" class="container"> <div id="MyName" class="center"> <button id="btn_MyNamebutton" class="btn btn-namebtn">Sign In</button> <form name="form"> <fieldset> <div class="form-group"> <label class="" for="FullName">Name <span class="required">*</span> </label> <input id="FullName" name="FullName" type="text" class="form-control" placeholder="Your Name" tabindex="1"> </div> <!-- Button --> <div class="form-group"> <button id="btn_sumbit" type="submit" class="btn btn-namebtn" onclick="checkform(document.form)">Sign up</button> <button id="btn_clear" type="reset" class="btn">Cancel</button> </div> </fieldset> </form> </div> </div>