user2781911
user2781911

Reputation: 79

Textarea did not focus but submit instead

I have a textarea which catch the keyphrase of characters' count. I also have a javascript codes in mine which return false if the textarea have no character typed in the field at all or at least 20 chars. This is my scripts:

Javascript

        function CheckLength() {
            var msg_area = document.getElementById("error2");
            msg_area.innerHTML = "";
            if (document.getElementById("staf_address").value.length < 20) {
                document.getElementById("error1").className = "par control-group error";
                document.getElementById("staf_address").focus();​
                msg_area.innerHTML = "YOU DID NOT ENTER ENOUGH INFORMATION";
                return false;
            } else document.getElementById("addstaf").submit();
        }

HTML

<form class="stdform stdform2" method="post" id="addstaf" action="index.php?site=addstafrev" onsubmit="return CheckLength()" />
    <div id="error1">
    <label for="staf_address">Address</label>
        <span class="field">
        <textarea cols="80" rows="5" name="staf_address" id="staf_address" class="span5 textarea2" maxlength="120" required /></textarea>
        <span class="help-inline" id="error2"></span>
        </span>
    </div><!--par-->
<button type="submit" class="btn btn-primary">Next</button>
</form>

There is no problem at all, at the beginning. The textarea will be not submitted if the characters in id=staf_address are less than 20 chars. The error will be displayed on id=error2. So, the textarea and the form work fine, no problem. The thing is that, it doesn't focus on text area during the form is submitted (if the textarea is less than 20 chars). So, I add a line of codes that is this line:

document.getElementById("staf_address").focus();​

After that, here comes the problem. The document won't check my javascript instead it submit the form eventhough the textarea only have 1 char. How to solve this?

Need just a plain javascript only.

Upvotes: 0

Views: 91

Answers (2)

bags
bags

Reputation: 1066

When I pasted your code into JS Fiddle I noticed a weird character after focus();

enter image description here

Deleting it seems to fix the problem.

preventDefault() is an event method so it can only be used if an event object is passed into the function. Ex: https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22395

When you press the button, your form is submitted. You need to prevent this with preventDefault() which will stop the submission, allowing you to perform functions and whatnot before manually submitting upon the proper submission.

Remember, a button inside a form tag defaults to a submit button!

Upvotes: 0

Related Questions