JavaScript for Verifying Phone Numbers

After extensive research and tutorials, I am still unable to figure out what is going wrong with my work.

I have a button that looks like this:

Despite Stack Overflow causing some trouble for me, please ignore the missing class as it is there. This is not the issue where I am stuck.

When the button is clicked, it triggers a JavaScript code like this:


$(document).on("click", "#create_account", function(evt)
{
    /* This code is not mine; I found it in an online tutorial and it works on JSFiddle, so I know this isn't the problem */
    function phonenumber(inputtxt)
    {
        var phoneno = /^\d{10}$/;
        if(inputtxt.value.match(phoneno))
        {
            return true;
        }
        else
        {
            alert("Not a valid Phone Number");
            return false;
        }
    }
});

I suspect the reason why this isn't working is because I am not calling that specific function to run. However, after some tests, I do know that it is hitting the onclick aspect of it.

My goal is to validate the phone number to be 10 digits (for now). I have set the input type as text with the ID "input_phone". I plan to modify this further for more than just 10 numbers later on, but I am currently struggling to execute this function and trigger that alert message.

Thank you in advance for any tips or help!

Answer №1

One reason it's not working is because you're defining a function within the click event instead of calling it. To fix this, move the function body outside of the event callback and simply call the function from inside.

Here is an example code snippet to demonstrate the correct approach:

$(document).on("click", "#create_account", function(evt)
{
    phonenumber($('#create_account').val()); // enter input value here
})

function phonenumber(inputtxt)
{
  var phoneno = /^\d{10}$/;
  if(inputtxt.value.match(phoneno))
  {
      return true;
  }
  else
  {
     alert("Not a valid Phone Number");
     return false;
  }
}

$(document).on("click", "#create_account", function(evt) {
  console.log(phonenumber($('#in').val()) ? 'Valid' : 'Invalid');
})

function phonenumber(inputtxt) {

  var phoneno = /^\d{10}$/;
  if (inputtxt.match(phoneno)) {
    return true;
  } else {
    alert("Not a valid Phone Number");
    return false;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="in" />
<button id="create_account">Create Account</button>


Plain JS Version

document.getElementById('create_account').addEventListener('click', function(evt) {
  console.log(phonenumber(document.getElementById('in').value) ? 'Valid' : 'Invalid');
})


function phonenumber(inputtxt) {

  var phoneno = /^\d{10}$/;
  if (inputtxt.match(phoneno)) {
    return true;
  } else {
    alert("Not a valid Phone Number");
    return false;
  }
}
<input type="text" id="in" />
<button id="create_account">Create Account</button>

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

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

Retrieving Information from Website Components in JavaFX Web View

I am currently developing a Java FX program that loads a folder containing HTML/CSS/JS files with 3 different websites. While the websites are displaying correctly in the webview, I am looking for a way to capture user interactions, such as checkbox selec ...

Arranging an Array of Objects in JavaScript by dual criteria

In my JavaScript code, I have an object structured like this: myArray[0] -> 0:"62", 1:8, 2:0, 3:"11" myArray[1] -> 0:"62", 1:8, 2:0, 3:"15" myArray[2] -> 0:"48", 1:8, 2:0, 3:"04" myArray[3] -> 0:"48", 1:8, 2:0, 3:"01" myArray[4] -> 0:"62", ...

Issue with Laravel ReactJs: My changes in the ReactJs file are not being reflected on the website

I've been utilizing Reactjs within Laravel. Recently, I made some modifications to my React Component and upon refreshing my browser, the changes did not reflect. Here are the files involved: resources/views/welcome.blade.php <!doctype html&g ...

Encountered an import error when using "npm run build", but it runs successfully with "npm start"

My React app is running smoothly with npm start, but I encounter an error when trying to build it using npm run build. The error message I receive is: `Creating an optimized production build... Failed to compile. Attempted import error: './parseq-lan ...

The functionality of XPATH does not seem to be properly executed with JQuery

<html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("[href!='http://w ...

The function .classList.remove() is effective when applied to one element, but fails to work on a different element

I am facing an issue where only one element is getting affected when trying to remove classes from multiple elements if certain email input requirements are met. Can someone help me understand why this is happening? Here is the code snippet: const emailI ...

Master the art of using Insertion Sort in javascript with the help of Khan Academy

Seems like I am almost there with solving this problem, but my code isn't running as expected. Can someone offer some feedback and point out where I went wrong? var insert = function(array, rightIndex, value) { for(var j = rightIndex; j & ...

Trouble with custom font updates in Hugo using Blogdown

Recently, I've been immersing myself in Blogdown to create my own personal data blog: Using the academic theme as a base, I successfully tweaked the color scheme without any hiccups. However, despite making adjustments in my params.yaml file, none o ...

Leaving a message on someone else's Facebook wall by sharing a link to a website

I've been trying to figure this out, but I honestly have no idea where to start. Twitter has a feature that allows a link to open a box where users can write a tweet and post it directly to their chosen feed: It's really simple, just changing t ...

Updating the User Interface in ReactJS based on changes in the state

I am relatively new to ReactJS and I am currently working on building a Sudoku Solver. My goal is to update the state in real-time so that the user can visually see how the algorithm is progressing. However, my current code only updates the UI at the end ...

When the parent element is already set to justify its content with flexbox, you can ensure equal heights for CSS classes by utilizing

Within my design, I have several rows with 3 columns each. Every column contains a main content section labeled SavedSearchBox-content (with various permutations that affect its height) and a footer labeled SavedSearchBox-footer. To structure this layout, ...

Error encountered when uploading mp3 file to S3 node due to size limitation

Currently, I am utilizing Node to transmit mp3 files to Amazon S3. However, after uploading the file, it shows a size of 9.0 Bytes and when attempting to play the audio from the public URL, it does not work as expected. Here is my current code snippet: rou ...

Tutorial on creating a loop for a function based on a specific condition

I have created two different div classes named box and box2. The box2 class can be dragged and dropped into any of the three box classes. Each box contains randomly chosen values from an array, while box2 contains its corresponding image for display. When ...

Utilizing jquery and ajax to submit a form seamlessly without the need to refresh the web page

I've been struggling to submit a form without refreshing the entire page. I integrated some source code that I found, but for some reason, it's not working! Here is the HTML form I'm trying to submit: <form method="POST" action="" name= ...

Managing ajax requests, failing to retrieve information

I am struggling to configure my client-side ajax calls to send data to a node express server. I want the ajax request to be triggered "onclick" of an href link. My goal is to pass the ID of the link as a variable to the server, but unfortunately, the serv ...

Utilize the power of Nuxt and Vue 3 to create sortable columns in a table, with the ability to only change the icons on the sorted column

I am facing a challenge with my sortable table icons. Whenever I click on an icon to sort a column, all the other icons also change direction. I understand that this is happening because I am toggling the visibility of icons based on the currentSortDir sta ...

Resolving Route Problems in Node.js with Express

Currently, I am in the process of developing a website using Express and NodeJS. One issue that I have encountered is related to routing. In my app.js file, I have defined a route that expects a parameter like so: app.get(['/purchase/:purchaseID&apos ...

Verify the security of form authentication on the client-side

For my ASP.NET website, I am utilizing Form Authentication and need to verify the user's authentication status before initiating a callback on the client-side. What is the best way to accomplish this using JavaScript/jQuery? ...

Looking for assistance with PHP if statement and troubleshooting iFrame issues

Using the PHP if statement below on my website: <?php if(empty($_GET['tid'])) echo '<iframe src="http://tracking.mydomain.com/aff_goal?a=33&goal_id=47" scrolling="no" frameborder="0" width="1" height="1"></iframe>'; ...