Guide to including a class within an "else" statement in JavaScript

function check_empty() {
if (document.getElementById('CompanyName').value == "" || document.getElementById('ContactName').value == "" || document.getElementById('Address').value == "" || document.getElementById('PhoneNumber').value == "" || document.getElementById('Email').value == ""){
alert("Fill All Fields !");
} else {
/*add new class "my" */
alert("Form Submitted Successfully...");
}
}

/*html code*/
<a href="javascript:%20check_empty()" class="my">Submit to download</a>

Upon clicking the link "Submit to download", the function "check_empty()" is triggered. If all fields are empty, a message will prompt saying "Fill All Fields !". Otherwise, we want to include a class called "my", which is currently defined on the HTML element. How can we add it in JavaScript?

Answer №1

Update:

I believe the solution you are seeking involves utilizing the attributes placeholder, required, and autofocus. There is no need for JavaScript to validate if the inputs are empty. Here is an example of how you can set up your form:

<form>
    <input id=CompanyName type=text placeholder=CompanyName required autofocus />
    <input id=ContactName type=text placeholder=ContactName required />
    <input id=Address type=text placeholder=Address required />
    <input id=PhoneNumber type=text placeholder=PhoneNumber required />
    <input id=Email type=text placeholder=Email required />
    <input type=submit value=send />
</form>

After setting up the form, you can perform actions when the form is submitted:

function sendMyForm(event){
    alert("Form Submitted Successfully...");
}

var sendForm = document.querySelector("form");

sendForm.addEventListener("submit", sendMyForm, false);
<form>
    <input id=CompanyName type=text placeholder=CompanyName required autofocus />
    <input id=ContactName type=text placeholder=ContactName required />
    <input id=Address type=text placeholder=Address required />
    <input id=PhoneNumber type=text placeholder=PhoneNumber required />
    <input id=Email type=text placeholder=Email required />
    <input type=submit value=send />
</form>

Additionally, you can use the classList property:

document.querySelector("#CompanyName").classList.add('my');

Your code could be enhanced with this approach:

function check_empty() {
   if (document.getElementById('CompanyName').value == "" || document.getElementById('ContactName').value == "" || document.getElementById('Address').value == "" || document.getElementById('PhoneNumber').value == "" || document.getElementById('Email').value == ""){
      alert("Fill All Fields !");
   } else {
      /* Adding a class "my" */
      document.querySelector("#CompanyName").classList.add('my');
      
alert("Form Submitted Successfully...");
   }
}

Answer №2

Do you need help with calling two javascript functions with a single click?

If that's the case, you can use the following code:

<a href="javascript:void()" onClick="return check_empty() ? my() : false"> Click here to download </a>

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

Iterating through AJAX response using jQuery on Button Click

I am a newcomer to the world of coding and have been struggling for hours to solve this particular issue: After making an AJAX call, I receive a Json two-dimensional array jqXHR[][]. The first index represents each product ID, while the second one contain ...

Obtain the URL value using jQuery and place it inside a <span> element

How can I insert a href value into the span tag like this? <p class="name"> <a download="adja-lo.pdf" title="adja-lo.pdf" href="http://localhost/MatrixDRSnews/apps/Matrix/server/php/files/adja-lo.pdf">adja-lo.pdf</a> </p> ...

What is the best way to extract text using Selenium in Java?

My goal is to extract the text $1.00 from the HTML code snippet below (I already have the xpath, so no need to worry about that). Let's assume the xpath is //*[@id="price-string"] <strong id="price-string">$1.00</strong> ...

Can you help me with correcting the URL and making the necessary links?

<?php $res=$comments->result_array(); $i=1; $ar=array(); foreach($res as $row){ $a=array($i,$row['title'],$row['date_post'], $row['date_edit'], '<a href="edit_ ...

The transition feature is not functioning properly in Firefox

I have a basic HTML and CSS setup below. It seems to be working fine in Chrome, but I'm having trouble with the transition effect in Firefox. I am currently using Firefox version 18. I tried looking up solutions on Google and Stack Overflow, but none ...

saving the hash key in a separate array

Currently, I have a collection of key-value pairs that need to be stored in another array. However, I am facing difficulties with the logic as I am unable to keep track of which keys-values have already been assigned while iterating over the list of object ...

click events in backbone not triggering as expected

It's puzzling to me why this is happening. The situation seems very out of the ordinary. Typically, when I want an action to be triggered on a button click, I would use the following code snippet: events:{ 'click #button_name':'somefun ...

What is the significance of rendering models with a blade-colored using Three.js?

https://i.sstatic.net/BlZ6E.png Hey there, I've imported my model (obj + mtl + texture) but it appears with a different color. It's supposed to look like this: https://i.sstatic.net/9BwS9.png Currently, here's the scene configuration cod ...

Utilizing JSON to transfer PHP array data for display using JQuery

Currently, I am working on a jQuery script that is responsible for fetching a PHP array from the MySQL database and converting it into a JSON object. The process is functioning correctly, as I can successfully output the raw JSON data along with the keys. ...

Is it possible to conceal the mapbox access token during the map initialization process?

I have successfully integrated the mapbox API to create an interactive map on my website. To ensure the security of my access token, I have set up a proxy to handle the API requests externally. However, I am facing a challenge when it comes to hiding the a ...

Reducing div size when clicked - Using JQuery version 1.9

I am looking to make a specific div shrink in size, while keeping all the data visible, each time a user clicks on a certain icon with the class legend-icon. For example, I want the div with the ID #Chart to shrink when clicked. This is the HTML code: &l ...

Utilizing Node JS to transfer information from an array of objects into a Postgres table

After spending the entire day trying to work with JSON data and Postgres, I still can't figure out what's causing the issue. This is a snippet of my dataset, consisting of around 1000 objects: { avgHighPrice: null, highPriceVolume: 0, ...

Creating a dynamic feature in React where multiple icons change color individually when hovered over, all implemented

I'm looking to customize the icons in my footer by changing their colors when users hover over them. I have already created a CSS class with the necessary hover effects, but now I want to pass a parameter in my JSX file that specifies which color shou ...

The CSS styling is not being rendered correctly on the AngularJS HTML page

Encountering a puzzling situation here. Our angular controller is successfully delivering data to the page, but we are facing an issue with rendering a table due to an unknown number of columns: <table border="1" ng-repeat="table in xc.tables"> ...

What could be causing the delay in response times from these unpredictable APIs within the Express server?

We are currently experiencing performance issues with our Express.js server and MongoDB database. Randomly, some API requests are taking too long to respond or timing out throughout the day. Our application is in production, hosted on two AWS instances wit ...

Error encountered: `TypeError: Unable to access undefined properties (specifically, '0') within the Simple React Project`

Currently in the process of learning React and working on a simple photo application. Encountering an issue: Collection.jsx:6 Uncaught TypeError: Cannot read properties of undefined (reading '0') Why is this happening? Everything was functioni ...

The value selected is not being shown using uib-typeahead in the user interface

Within my AngularJS application, I am utilizing uib-typeahead to provide auto-suggestions in a text box. As I start typing, I can see the suggestions appearing. However, when I select one of the options, it does not display in the text field (ng-model). I ...

What methods can be used to secure Next.js API routes and prevent them from being directly accessed through the URL

I am seeking a solution for concealing the response data of next.js API routes when accessed through URL. I need to protect certain sensitive information from direct access by users. ...

Change a variable on the fly without needing to reload the page

<!DOCTYPE html> <!-- To update your slot machine images without refreshing the page, you can use JavaScript to dynamically change the images on click. Here's a simple example using JavaScript: <html> <head> <title& ...

What is the best way to hide a background bottom line using bootstrap-4?

After creating my header and using an SVG to divide the section, I noticed a line appearing below the SVG. To try and cover it up, I added an empty white background line using :: after in CSS with the content empty, but the issue persisted. You can see th ...