Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking text field value length

Tags:

javascript

I am trying to see if the text field length is at least a certain length. here is my code:

<form name="form2" id="form2" onsubmit="return validate()">
length 4: <input type="text" name = "t" id="t" />
<input type="button" name="submit" value="submit" />
</form>

<script>
function validate() {
    document.write("good");
    submitFlag = true;
    if(document.form2.t.value.length!=4){
        submitFlag=false;
        alert("ivalid length - 4 characters needed!");
    }
    return submitFlag;
}
</script>

when I click submit, nothing happens.

like image 232
droidus Avatar asked Apr 18 '12 19:04

droidus


People also ask

How do you find the input length of text?

To get the length of an input textbox, first we need to use access it inside the JavaScript by using the document. getElementById() method. const textbox = document.

How do you show value in textfield?

We can get the value of the text input field using various methods in JavaScript. There is a text value property that can set and return the value of the value attribute of a text field. Also, we can use the jquery val() method inside the script to get or set the value of the text input field.

How can get input field length in jQuery?

We can find the length of the string by the jQuery . length property. The length property contains the number of elements in the jQuery object. Thus it can be used to get or find out the number of characters in a string.


2 Answers

Change your submit button to type="submit". The form is never getting submitted so the validate function isn't being called.

like image 189
Geoff Warren Avatar answered Sep 30 '22 07:09

Geoff Warren


The input type needs to be "submit"

<form name="form2" id="form2" onsubmit="return validate()">
   length 4: <input type="text" name = "t" id="t" />
    <input type="submit" name="submit" value="submit" />  <!--INPUT TYPE MUST BE SUBMIT -->
    </form>

    <script>
    function validate() {
        document.write("good");
        submitFlag = true;
        if(document.form2.t.value.length!=4){
            submitFlag=false;
            alert("ivalid length - 4 characters needed!");
        }
        return submitFlag;
    }
</script>
like image 40
daker Avatar answered Sep 30 '22 07:09

daker