An extremely basic inquiry regarding JavaScript form validation

Is there a way to add a simple icon next to a form field when users type in their name or email address? I only want the icon to show if even one character is typed. The icon should change based on whether the field has content (success) or not (fail). Looking for a basic JavaScript solution, everything I've found so far seems too complex and feature-heavy.

Answer №1

What do you think of this solution?

const inputField = document.getElementById('myFormField');
const icon = document.getElementById('myIcon');

inputField.onchange = function(){
    icon.src = this.value ? 'success.png' : 'fail.png';
};

(I have not had the chance to try this out yet)

In simple terms, this code instructs the browser to check the value of a form field upon user input. If the field is empty, the icon displayed will change accordingly.

For different types of form fields like select menus, you may need to use a different property instead of value. With jQuery, you can simply utilize .val().

To improve this functionality, consider adding more complex validation such as checking for whitespaces in the field's value.

Answer №2

1) To start, make sure to include jquery on your website for easier javascript functionality and a smaller file size when minified.

2) The basic HTML structure assumed in this scenario would be:

<input type="text" name="name" id="edit-name" class='text-field' />
<img src='something' id='edit-name-succeed' style="display: none;" />
<img src='something' id='edit-name-fail' style="display: none;" />
<input type="text" name="email" id="edit-email' class='text-field' />
<img src='something' id='edit-email-succeed' style="display: none;" />
<img src='something' id='edit-email-fail' style="display: none;" />

3) The corresponding javascript code would look like this:


$('input.text-field').change(function() {     
  if ($(this).text()) {  
    $('#' + $(this).attr('id') + '-fail').hide();  
    $('#' + $(this).attr('id') + '-succeed').show();
  }   
});  
$('input.text-field').blur(function() {
  if (!($(this).text())) {  
    $('#' + $(this).attr('id') + '-fail').show();  
    $('#' + $(this).attr('id') + '-succeed').hide();    
  } 
});

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

Unable to send multiple onChange AJAX requests

Why do I keep getting the error Notice: Undefined index: provinsi when trying to retrieve values from tahun and provinsi using this code? If I remove provinsi from the code and only use tahun, I am able to successfully fetch data from my database. func ...

Ways to clear an individual form field using element-ui

I'm currently learning VueJS and incorporating the Element-UI framework into my project. One issue I'm facing is that when there's a validation error upon submitting the login form, I'd like to automatically clear the password field. A ...

Vue Charts.js failing to render charts post data retrieval

Here is an example of a JSON response: [[61,57,34],[1,1,3]]. I would like to use the first array for labels and the second array for data. If I manually set labels and data inside the app, it works fine. For example: labels: ["q", "w", "e"] data: [1, 5, ...

"Common Errors Encountered When Running 'npm start'

Each time I attempt to initiate my react project, it presents me with these errors npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\Mohamed Badrawy\Desktop\reactjs-basics-master\package.json npm ERR! errno -4058 n ...

The import error states that the object 'useHistory' is not available for export from the module 'react-router-dom'

Struggling with importing useHistory from 'react-router-dom' and encountering the error message: import error: 'useHistory' is not exported from 'react-router-dom'. Despite searching for solutions like Attempted import error: ...

The presence of MongoDB dot character in the key name

When working with MongoDB, I ran into an issue where keys with a dot (.) or dollar sign ($) are not allowed for insertion. However, while using the mongoimport tool to import a JSON file that contained a dot in it, surprisingly it worked without any proble ...

Creating identical height columns with uniform inner elements is a problem that needs to be solved with caution. The proposed solution

Issue: I need to create a responsive layout with 5 columns, each containing an image, title, and text. The goal is to align the images separately, titles together, and texts individually while ensuring that all elements in a row have the same height. Solu ...

Ways to implement form validation with JavaScript

I'm currently working on a project for my digital class and I'm facing an issue with my booking form. I have two functions that need to execute when a button is clicked - one function validates the form to ensure all necessary fields are filled o ...

Getting the output from AJAX when the onreadystatechange event occurs

Struggling with retrieving a value from a function and storing it in a variable? Getting an "undefined" result due to JavaScript's asynchronous nature? Unsure how to fix this using "callbacks" or "promises"? Check out the code snippet below. The goal ...

Jquery Visualization Chart not displaying

I am struggling to get the jquery visualization to work properly. Although the table and caption appear fine, there is no data showing up in the chart. I've carefully followed the example and searched for any issues, but I can't identify what&apo ...

"Upon pressing the submit button in the router.post function, a null value appears

In my form, I am attempting to redirect the page to the home URL after clicking the submit button. However, using res.redirect('/home') is not achieving the desired result. I have also tried using console.log("testing");, but that is not working ...

Developing real-time chat functionality in React Native with node.js and Socket.io

I'm on the lookout for resources to help me navigate both server-side (mostly) and client-side development. I recently came across a resource called Simple Real Time chat app but unfortunately, it did not yield significant results. I tried locally ho ...

NPM is complaining about the absence of a start script

Apologies for any language barriers in my English. I'm currently facing an issue while trying to deploy an app on Heroku using the heroku local web command in the terminal. The error message ERR! missing script: start keeps popping up, even though the ...

Item 'unreachable' displayed in Firefox console

I am working with several divs that have the class='class_name'. I have also defined var A = document.getElementsByClassName('class_name'); console.log(A[0]); Upon checking in the Chrome console, it displays: <div class="class_n ...

Exploring the utility of promise.race()

When it comes to promise, there are two main options that I am aware of: promise.all() promise.race() I have a good grasp on what promise.all() does. It runs promises simultaneously, and upon successful resolution, the .then method provides you wit ...

Terminate all dormant MySQL pool connections using Node.js

In my project involving node.js and connection pooling, I have noticed that despite releasing connections after each query as shown below: return new Promise((resolve, reject) => { sql.getConnection(function (err, conn) { if (err) { ...

An error occurred when trying to access the 'getHours' property of an undefined variable

I have been working on creating a basic bar chart using financial data in JSON format. An error message keeps appearing when I try to utilize my parsed time data. Despite console logging the data and verifying that it has been parsed correctly, I encounte ...

Error occurred while attempting to access querystring values

Is there a reason why 2 out of the 3 querystring parameters have values, while one is undefined? <li class="@ViewBag.ShowNext">@Html.RouteLink("Next »", "Search", new { page = @ViewBag.NextPage, q = @ViewBag.TextClean, Option = @ViewBag.Option }, n ...

Step-by-step guide to implementing onClick functionality within a component

Currently, I am utilizing https://github.com/winhtaikaung/react-tiny-link to showcase posts from various blogs. While I am able to successfully retrieve the previews, I am facing an issue with capturing views count using onClick(). Unfortunately, it appear ...

How can I use an input array to filter data in mongodb?

When receiving input from the front-end, it looks like this: { "options":[ { "optionId":"5ebbe0f56b197f36fc472168" }, { "optionId":"5ebbe1aa6b197f36fc47216e" } ] } The goal is to filter the data in a way that ...