How to Set Focus on an Element in an HTML Form Using JavaScript

How can I set focus on an element in an HTML form using JavaScript?

Do this.

If your element is something like this..

<input type="text" id="mytext"/>

Your script would be

<script>
function setFocusToTextBox(){
document.getElementById("mytext").focus();
}
</script>

Set focus on HTML form element using JavaScript

input.value.focus();

Just needs to be

input.focus();

Javascript, I'm not being able to set focus to html form element

Your JavaScript looks correct. You should be able to focus on the input element with the following code:

document.getElementById("input-sign-in-id").focus()

There are a lot of CSS classes on that input element that may be affecting the focus styles of that element. Also, there may be ID-specific CSS affecting too.

Try removing all of the classes and if see if it works. Then slowly add them back one by one, until you find the culprit.

set focus in next html input after editing and clicking enter

As Nitin mentions in the comment above, the Enter key is mainly used as a button press or submitting the form. Anyway, try this example for your solution.

const inputs = document.querySelector('.dws-input');
const formControl = document.querySelectorAll('.form-control');

formControl[0].focus();

function keyPressFunction(ev) {
if (ev.code !== 'Enter') return;
if (ev.target.value === '') return;

for (const i of formControl) {
if (i.value === '') {
i.nextElementSibling.focus();
break;
}
}
}

inputs.addEventListener('keydown', keyPressFunction);
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous" />

<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name="username" placeholder="Логин:" autofocus />
<label for="tLogin">Login:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name="text" placeholder="Номер стола:" />
<label for="tTable">Table:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name="text" placeholder="Заказ:" />
<label for="tOrder">Order:</label>
</div>
</div>
</form>
</div>

How to set focus in an input element after submit and reset form?

Thanks for sharing the jsbin link.

Here is the updated solution after submitting it is focusing on nameInput now.

https://jsbin.com/xilitewabi/2/edit?html,js,output

 else if ([price === '""']) {
messageEl.textContent = '"Значение поля не может быть пустым"';
nameInput.focus();
}

The issue was in your else if statement. After submitting you were focusing on priceInput instead of nameInput

How to set focus on element

When you submit a form, the page reloads. Consider adding focus to the form when the page loads (Which gives the advantage of being ready for the user the first time they visit the page). Change your field to include an id:

<input type="text" name="mon_am" id="mon_am">

And in your script tag, add:

window.onload = function() {
document.getElementById("mon_am").focus();
};

How do I set the focus to the first input element in an HTML form independent from the id?

You can also try jQuery based method:

$(document).ready(function() {
$('form:first *:input[type!=hidden]:first').focus();
});

how to set focus on an input field when an error occurred during the form submission

You should use focus() function, check working example bellow.

Hope this helps.


function validateform() {var fullname = document.registration.name.value;var emailadd = document.registration.email.value;var company = document.registration.company.value;var project = document.registration.project.value;var message = document.registration.message.value;
if (fullname === null || fullname === "") { resetErrorMsg();
document.getElementById('f_error_msg').innerHTML = "Please enter Full Name"; document.registration.name.focus(); document.getElementById('f_error_msg').style.display = "block"; return false;}else{ document.getElementById('f_error_msg').style.display = "none";}
var atposition = emailadd.indexOf("@");var dotposition = emailadd.lastIndexOf(".");
if (atposition < 1 || dotposition < atposition + 2 || dotposition + 2 >= emailadd.length) { resetErrorMsg();
document.getElementById('e_error_msg').innerHTML = "Please enter a valid e-mail address \n atpostion:" + atposition + "\n dotposition:" + dotposition; document.registration.email.focus(); document.getElementById('e_error_msg').style.display = "block"; return false;}else{ document.getElementById('e_error_msg').style.display = "none";}
if (company === null || company === "") { resetErrorMsg();
document.getElementById('c_error_msg').innerHTML = "Please enter your company name"; document.registration.company.focus(); document.getElementById('c_error_msg').style.display = "block"; return false;}else{ document.getElementById('c_error_msg').style.display = "none";}
if (project === null || project === "") { resetErrorMsg();
document.getElementById('p_error_msg').innerHTML = "Please enter your project name"; document.registration.project.focus(); document.getElementById('p_error_msg').style.display = "block"; return false;} else{ document.getElementById('p_error_msg').style.display = "none";}
if (message === null || message === "") { resetErrorMsg(); document.getElementById('m_error_msg').innerHTML = "Please enter your message here."; document.registration.message.focus(); document.getElementById('m_error_msg').style.display = "block"; return false;} else{ document.getElementById('m_error_msg').style.display = "none";}
}
function resetErrorMsg(){document.getElementById('f_error_msg').style.display = "none";document.getElementById('e_error_msg').style.display = "none";document.getElementById('c_error_msg').style.display = "none";document.getElementById('p_error_msg').style.display = "none";document.getElementById('m_error_msg').style.display = "none";}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/><script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script><form name="registration" id="form" action="contact.php" method="post" onsubmit="return validateform();">        <div class="form-group">            <div class="input-group col-xs-12 text-left">                <label for="InputName">Full Name:<span style="color:red;">*</span></label>                <input type="text" name="name" id="name" class="form-control" placeholder="Name">                <br>                <span id="f_error_msg"></span>            </div>            <div class="input-group col-xs-12 text-left">                <label for="InputEmail">Email Address:<span style="color:red;">*</span></label>                <input type="email" name="email" id="email" class="form-control" placeholder="Email">                <br>                <span id="e_error_msg"></span>            </div>            <div class="input-group col-xs-12 text-left">                <label for="InputCompany">Company:<span style="color:red;">*</span></label>                <input type="text" name="company" id="company" class="form-control" placeholder="Company">                <br>                <span id="c_error_msg"></span>            </div>            <div class="input-group col-xs-12 text-left">                <label for="ProjectDescription">Project Description:<span style="color:red;">*</span></label>                <input name="project" id="project" type="text" class="form-control" placeholder="Project Description">                <br>                <span id="p_error_msg"></span>            </div>            <div class="input-group col-xs-12 text-left">                <label for="InputMessage">Message:<span style="color:red;">*</span></label>                <input type="text" name="message" id="message" class="form-control" placeholder="I love a team that...">                <br>                <span id="m_error_msg"></span>            </div>        </div>        <div class="form-group">            <input type="submit" name="submit" class="btn btn-success btn-block" value="Go">        </div>    </form>

How to set focus on an input field after rendering?

You should do it in componentDidMount and refs callback instead. Something like this

componentDidMount(){
this.nameInput.focus();
}

class App extends React.Component{  componentDidMount(){    this.nameInput.focus();  }  render() {    return(      <div>        <input           defaultValue="Won't focus"         />        <input           ref={(input) => { this.nameInput = input; }}           defaultValue="will focus"        />      </div>    );  }}    ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script><div id="app"></div>

How can you set focus to an HTML input element without having all of the HTML?

This has worked well for me:

<script>
function getLastFormElem(){
var fID = document.forms.length -1;
var f = document.forms[fID];
var eID = f.elements.length -1;
return f.elements[eID];
}
</script>


<input name="whatever" id="maybesetmaybenot" type="text"/>
<!-- any other code except more form tags -->

<script>getLastFormElem().focus();</script>


Related Topics



Leave a reply



Submit