Reputation: 77
I am trying to put focus() on nameInput field after submitting the form but instead focus is on priceInput field, how can I fix this ?
purchaseForm.onsubmit = (evt) => {
evt.preventDefault();
const name = nameInput.value;
const price = Number(priceInput.value);
if (name !== '' && price !== '' && price > 0) {
purchases.push({
id: nextId++,
name: name,
price: price,
});
createElement(name);
nameInput.focus();
purchaseForm.reset();
}
if (name === '') {
messageEl.textContent = '"Input field can't be empty"';
nameInput.focus();
} else if (price === '') {
messageEl.textContent = '"Input field can't be empty"';
priceInput.focus();
} else if (price < 0) {
messageEl.textContent = ''"Input field can't be empty"';
priceInput.focus();
} else if ([price === '""']) {
messageEl.textContent = '"Input field can't be empty"';
priceInput.focus();
}
if (price > 0) {
messageEl.textContent = '';
}
};
Upvotes: 1
Views: 2825
Reputation: 314
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
Upvotes: 1
Reputation: 155
You definitely have a problem here:
messageEl.textContent = '"Input field can't be empty"'; //sets the error message if name input is string and puts focus on the name input field.
nameInput.focus();
} else if (price === '') { //sets the error message if price input is empty and puts focus on the price input field.
messageEl.textContent = '"Input field can't be empty"';
priceInput.focus();
Mind your ' and "" first of all. Your error string is terminated in the middle of the string.
I have taken your code and it works actually
purchaseForm.onsubmit = (evt) => {
evt.preventDefault();
const name = nameInput.value;
const price = Number(priceInput.value);
if (name !== '' && price !== '' && price > 0) {
purchases.push({
name: name,
price: price,
});
nameInput.focus();
}
}
When I submit form the focus is on name input.
About your conditions. Some of them do not make sense at all. I've narrowed them and again it works
purchaseForm.onsubmit = (evt) => {
evt.preventDefault();
const name = nameInput.value;
const price = priceInput.value;
if (name !== '' && price !== '' && price > 0) {
purchases.push({
name: name,
price: Number(price),
});
nameInput.focus();
}
if (name === '') {
messageEl.textContent = "Input field cannot be empty ";
nameInput.focus();
} else if (price === '') {
messageEl.textContent = "Input field cannot be empty ";
priceInput.focus();
}
}
Upvotes: 0