I attempted to shift my focus back to the input box, but for some reason, it doesn't want to cooperate

I'm having trouble getting the focus to return to the input box in my form after an invalid entry triggers an alert box. I've written what should be the correct code, but for some reason, it's not working as expected.

Here's the code snippet I've been using:

HTML:

<form name="myform" onsubmit="validate()"> 
            Amount   <input name="num" id="principal"gt;<br/>  </form>


        

JS:

function validate(){  
  var num = document.myform.num.value;  
  if (isNaN(num) || num == 0 || num < 0 || num == null) {  
    alert("Please enter a valid entry")
    document.getElementsById("principal").focus(); }
  else {  
    return true;  
    }  
  }  

I appreciate any help in identifying where I may have gone wrong. Thank you!

Answer №1

Have you noticed any error messages in your console? The correct method is "getElementById," not "getElementsById."

Additionally, it's important to add functionality to prevent the default submit behavior. Below is a modified and functional code snippet:

document.getElementById('submitbutton').addEventListener('click',function(event){
  event.preventDefault();
  validate();
});

function validate(){

  var num = document.myform.num.value;  
  if (isNaN(num) || num == 0 || num < 0 || num == null) {  
    alert("Please enter a valid entry")
    document.getElementById("principal").focus(); }
  else {  
    return true;  
    }  
  } 
<form name="myform" onsubmit="validate()"> 
  Amount   <input name="num" id="principal"><br/>  
  <button id="submitbutton">Submit</button>
 </form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JqueryUI Autocomplete functions flawlessly on JSFiddle but fails to work on the actual website

After spending hours working on it, I still can't seem to figure it out. The code functions perfectly on JSFiddle, but not on my own website. Here is the link to the JSFiddle: http://jsfiddle.net/x69chen/sbAR6/16/ I've also included the links ...

Point the direction to nextjs and react native expo web

I am currently working on redirecting a URL to another within my website, specifically in Next.js and Expo React Native Web. While I don't have an actual "About" page, I do have other pages nested under the "about" folder and am aiming to direct any ...

What is the reason for using a wrapper with fs.readFile when a callback is included as an argument?

Recently delving into Node.js, I encountered a perplexing scenario while using fs.readFile(). Initially, my attempt to read a file led me to use: fs.readFile("file.txt",function(err,data) { if(err) {throw err;} console.log(data); }); However, to ...

Choose the minimum price from the JSON response of the API

I have made an AJAX request to an API and received the following JSON response below. I am trying to extract the lowest 'MinPrice' from the 'Quotes' data but finding it challenging to determine the best approach. One method I am consid ...

I'm looking to include an icon in my TreeItem component in Material UI 4. How

I have a unique menu created using MATERIAL UI 4, consisting of a primary TreeItem for the main menu and a secondary TreeItem for the submenu sections. I am looking to assign a specific icon to each main menu label. How can I achieve this? Additionally, ...

Switch the checked status of an input dynamically using jQuery function

It seems like I might be overlooking something quite obvious, but I can't figure out why this jquery function is behaving inconsistently. HTML: <label id="income_this_tax_year"> <div class="left"> <p>Have you had Self-Employm ...

Transfer information from an HTML document to a Vue application that has been registered

I have a Vue application set up in the following manner: import { createApp } from 'vue'; import RecommendedJobsWidget from './RecommendedJobsWidget.vue' createApp(RecommendedJobsWidget).mount("#recommendedJobsWidgetInstance" ...

Is it possible to attach a mouse click event to styled text?

Is there a way to specify a mouse click event for an element with a decoration applied to the text, matched with regex? The option to specify a hoverMessage is available, but I would like to find a way to execute a function based on which decorated text ...

Sorting a list with anchor tags alphabetically using Javascript/JQuery

Here is a list of services: <ul id="demoOne" class="demo"> <li><a href='http://site/Service.aspx?shId=1154'>Copy service for files from folder 12</a></li> <li><a href='http://site/Service.aspx? ...

formBuilder does not exist as a function

Description: Using the Form Builder library for react based on provided documentation, I successfully implemented a custom fields feature in a previous project. This project utilized simple JavaScript with a .js extension and achieved the desired result. ...

Is it possible to use a pass-through or helper function to invoke Asynchronous Generators in Node.js?

Exploring New Territory Upon my discovery that the asynchronous generator pattern is relatively novel in JavaScript and currently only supported in Node.js starting from version 10, I delved deeper into its functionalities. Now, equipped with this knowled ...

How to use React hooks to flip an array

Is it possible to efficiently swap two items in an array using JavaScript? If we are dealing with a boolean, one could achieve this by: const [isTrue, setIsTrue] = useState(false); setIsTrue(!isTrue); However, what if we have an array? // Let's ...

Ways to obtain the chosen option from a drop-down menu using jQuery

I'm currently experiencing an issue where the selected value of a drop down is not being displayed correctly. Instead of selecting the dropdown value, it's adding another value to the list. Below is the code snippet I'm using: JQuery var ...

iOS device encounters failure with Ajax CORS request and redirect

I am experiencing an issue where a URL is being redirected to another domain by the server. My test code is very simple: $.ajax({ type:"GET", url:"{MYURL}", success:function(d){alert('response');} }) You can che ...

The visualization rendered by ChartJS is not displaying correctly when data is fetched using an AJAX call

When it comes to creating visualizations from static datasets using ChartJS, I have no problems. However, the issue arises when I try to use data fetched via an AJAX call - the visualization does not render properly. Surprisingly, no errors are thrown even ...

Locate all inputs containing a special attribute name, wherein a portion of the name corresponds to a JavaScript variable

$("td[id^='td' + myvar + '_']") Can someone help me with a solution to substitute the static value of 0 in this code snippet with the dynamic variable myvar? Thanks! ...

I continuously receive the error message "StripeInvalidRequestError: Insufficient funds in Stripe account" despite the fact that there are adequate funds available

I'm in the process of transferring funds from my test mode Stripe account to another connected Stripe account. The balance in my test mode account is sufficient and there are no pending funds. However, I keep encountering a "StripeInvalidRequestError: ...

Call getElementById upon the successful completion of an AJAX request

In the process of constructing a mini quiz, I am utilizing a variable quizScore to store the score. Each question in the quiz is displayed using AJAX. An individual AJAX call captures the ID of the button pressed (for example, on question 2, the button ID ...

Creating an array of strings using data from a separate array of objects in JavaScript/TypeScript

I want to generate a new array of strings based on an existing array of objects, with each object belonging to the Employee class and having a firstName field: assignees: Array<Employee>; options: string[]; I attempted to achieve this using the fol ...

Receiving array data in a Javascript function and storing it within a variable

Hello everyone, please take a look at my code below. I am attempting to pass PHP array values to a JavaScript function. When I run the script, I receive alerts for parameter0=1, parameter1=2, and parameter2=3 separately. What I am trying to achieve is to ...