-2

I have a form element and I'm doing a small validation. I want my text box to be focused if it is invalid.

This is my HTML

<form id="frm" name="form1" onsubmit="validate()">
    Name: <input type="text" id="t1" name="txtBox">
    <input type="submit" value="submit">
</form>

This is my script: I want to focus the form element from else part

<script>
    function validate(){
        var inp = frm.getElementsByTagName("input");
        var arr=[];
        var i;
        for(i=0;i<inp.length;i++){
            arr[i]=inp[i].getAttribute("id");
            //document.write(arr[i]);
        }
        //alert(inp[0].value);
        if(form.validateText(inp[0],arr[0])){
            return true;
        }
    }

    var form = {
        validateText : function(f,i){
            var input = document.getElementById(i);
            var reg = /^[a-zA-Z]$/;
            //var 
            var x = f;
            if(x.value.match(reg)){
                return true;
            }
            else{
                alert("invalid text");
                input.value.focus();
            }
        }
    };
</script>
Sivaprakash
  • 455
  • 1
  • 8
  • 22
  • Does this answer your question? [How can I set focus on an element in an HTML form using JavaScript?](https://stackoverflow.com/questions/17500704/how-can-i-set-focus-on-an-element-in-an-html-form-using-javascript) – Flimm Jul 28 '20 at 16:12

5 Answers5

4

input.value.focus();

Just needs to be

input.focus();

haxtbh
  • 3,467
  • 1
  • 21
  • 22
1

use this:since you can have multiple input decide the one to focus.

document.getElementById("t1").focus();

you can do it as:

<script>
function setFocusToInput(){
    document.getElementById("t1").focus();
}
</script>

<body onload='setFocusToInput()'>
<form id="frm" name="form1" onsubmit="validate()">
    Name: <input type="text" id="t1" name="txtBox">
    <input type="submit" value="submit">
</form>
</body>
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
1

You are trying to use the focus method on the value property, and that's not going to happen!

Focus the element itself:

input.focus();
Vitor Rigoni
  • 573
  • 4
  • 14
0

try this:-

First u check manually.

$('#t1').focus();

is this working or not other wise

input.focus()

enuogh but first check

Wajihurrehman
  • 567
  • 3
  • 15
  • 29
-1

Use the pattern attribute on the input element it takes a regex and use the required attribute takes nothing just put required

<input type="text" id="t1" name="txtBox" pattern="^[a-zA-Z]$" required>
Edwin Reynoso
  • 1,511
  • 9
  • 18