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.
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.
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.
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.
Change your submit button to type="submit". The form is never getting submitted so the validate function isn't being called.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With