Form-linked Progress Bar

This is a little project I created (for fun and learning purposes, even though it may not be the most optimized solution).

If you're interested, here's the link to the code: https://codepen.io/paschos/pen/xxGXMQb

I'm currently seeking assistance with the following JavaScript code:

class App extends React.Component {

validate () {
    event.preventDefault();
    var name = document.getElementById("documentName").value;
    var email = document.getElementById("email").value;
    var re = /\S+@\S+\.\S+/;
    var type = document.getElementById("documentType");
    var typeChosen = type.options[type.selectedIndex].value;
    var category = document.getElementById("category");
    var categoryChosen = category.options[category.selectedIndex].value;

    if (name.length < 2 || name.length > 32) {
        alert("Invalid name length.");
    }
    else if (typeChosen === "" || categoryChosen === "") {
        alert("Please select a value from the dropdown list.");
    }
    else if (email.length > 128) {
        alert("Email exceedes character length.")
    }
    else if (re.test(email) === false) {
        alert("Invalid email address.");
    }

}
getValue () {
    return "";
}

fillBar () {
    return (<progress max="100" value = {this.getValue()} id="progress">
            </progress>);
}

  render() {
    return (
        <form onSubmit = {this.validate}>
         <div className = "form-progress-bar">
         {this.fillBar()}
        </div>
        <label htmlFor="documentName">Input the document name:</label>
        <br />
          <input id = "documentName"
          type="text" 
          placeholder="Document Name" 
        />
        <br />
        <label htmlFor="documentType">Select document type:</label>
        <br />
        <select className = "dropdown" id = "documentType">
        <option defaultValue = ""> </option>
        <option value = "Plain" label = "Plain" />
        <option value = "PDF" label = "PDF" />
        </select> 
        <br />
        <label htmlFor="category">Select document category:</label>
        <br />
        <select className = "dropdown" id = "category">
        <option defaultValue >  </option>
        <option value = "Audit" label = "Audit" />
        <option value = "Application" label="Application" />
        <option value = "Other" label = "Other" />
        </select>
        <br />
        <label htmlFor="email">Input your email address:</label>
        <br />
        <input id = "email"
          type="text" 
          placeholder="Email" 
        />
        <br />
        <button id = "button">Submit</button>
      </form>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

One thing I'm struggling with is how to increment the progress value by 25 each time a field in the form is filled.

The code pen includes HTML and CSS snippets as well.

I'll greatly appreciate any kind of help!

Answer №1

To track whether a field is filled or not, you could implement a change handler to update the state accordingly. Then, in the get value function, you can calculate the total sum of truthy values in the state.

For instance:

state = {
    (each field)
    emailFilled: false,
}

handleChange = (stateKey) => (event) => {
    const value = event.target.value;
    this.setState({
        [stateKey]: Boolean(value),
    });
}

getValue = () => {
    let value = 0;
    if(this.state.emailFilled) {
        value += 0.25;
    }
}

...
render(){
    ...
    <input id="email"
        type="text"
        placeholder="Email"
        onChange={this.handleChange('emailFilled')}
    />
    ...
}

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

Utilize ReactJS and NextJS to seamlessly upload files to your drive

I have been utilizing the https://github.com/rpldy/drive-uploady library for updating files. However, I noticed that the only example provided involves uploading files from a local source. If I have a file (base64 url) or a blob (obtained from a pdf file p ...

Why is the editor not displaying the correct line number when the enter key is pressed repeatedly in JavaScript?

I am currently working on developing an editor using JavaScript. My goal is to display a line count (e.g., 1, 2, 3) whenever the user presses 'Enter' to change lines. I have successfully managed to count the line changes upon pressing 'Enter ...

Why am I unable to utilize methods in Vue.js?

Hey everyone, I'm currently working on a website that includes a home page and a specific 'Brazil' component. To switch between the two, I am using vue router. Within the Brazil component, there is a calculator feature that should take a gra ...

Eliminate list items with a keyboard stroke

I am currently developing a straightforward todo list application using JavaScript. The main functionality I am trying to implement is the ability to add new items from an input field to a list, as well as the option to remove items from the list. While ...

Developing a GraphQL search feature in a React Native application

I am struggling to create a search feature that can search by name or category. I require assistance with the backend part, specifically configuring the resolver and index, as I am unsure if my current setup is correct. Resolver.js //search for single use ...

React render remains consistent despite Button function call

After clicking the login or register button in this React code snippet, I'm encountering an issue where the renderView() function does not display the Login (or Register) component on the page. Interestingly, when I log the value of e.currentTarget.va ...

How to obtain the height of the parent screen using an iframe

Imagine a scenario where a div contains an image that is set to perfectly fit the height of the screen. This setup works flawlessly, with one exception - when placed within an iframe, the height of the div adjusts to match the content's height rather ...

Placing an exit button beside an image for easy navigation

Here is a snippet of my code: <style type="text/css"> .containerdiv { position:relative;width:100%;display:inline-block;} .image1 { position: absolute; top: 20px; left: 10px; } </style> <div class="containerdiv"> <ima ...

I was able to efficiently reverse the transition using JavaScript, but I'm puzzled as to why my alternate approach is not functioning correctly

Check out my demo on jsfiddle I am trying to implement a reverse transition when clicking the <li> again. The commented code did not work, but the code below worked perfectly: let dbclickre = true; function flipped() { if (db ...

Audio issues plaguing audio playback on Discord

After spending two exhausting days, I am still trying to figure out what is going on. I am currently working on a Bot for my Discord Channel that should play an audio.mp3 file when a specific command, like !laugh, is entered. However, despite trying variou ...

Updating and deleting Firebase data from an HTML table: A guide

I am struggling to make the onClick function work in order to update and delete already retrieved data from an HTML table view. Despite trying different approaches, I can't seem to get it right. var rootRef = firebase.database().ref().child("prod ...

React with TypeScript: The struggle of getting LocalStorage to work

Currently, I am dealing with persistence in a todo application developed using React and TypeScript. To achieve the desired persistence, I have implemented localStorage. Allow me to share some code snippets: const [todos, setTodos] = useState<todoMod ...

Updating a value using jQuery AJAX techniques

Using jQuery AJAX, I am loading the content of a page in this way: $(document).ready(function(){ $('#next').click(function(event){ $.ajax({ url: "load.php?start="+$('#lastid').text(), success: function(html){ $("#results"). ...

Tips for passing input fields from a React Function component to a function

How can I retrieve the values from 4 input fields in my react functional component using a function called contactMeButtonPressed? The inputs include name, email, company name, and message when the contact me button is clicked. Do I need to implement stat ...

Conceal your password using HTML techniques

My goal is to hide passwords from being visible unless a user hovers directly over them. I've tried using the code below, but the hover effect isn't working as expected - either the password disappears completely or remains visible at all times. ...

Can someone provide guidance on creating a JavaScript function that locates an image within an <li> element and sets that image as the background-image property in the li's CSS?

Let's dive deeper into this concept: <li class="whatever"> <img src="/images/clients/something.jpg"> </li> <li class="whatever"> <img src="/images/clients/whatever.png"> </li> He ...

Issues verifying the selected value for the ajax request

One of the challenges I'm facing is related to a form that requires specific user selections. If the user chooses a value of 1, the form can be submitted without any additional steps. However, if they select values 2 or 3, they must then choose an opt ...

Matching patterns with regular expressions in Javascript

There's a string that goes like this: |Africa||Africans||African Society||Go Africa Go||Mafricano||Go Mafricano Go||West Africa|. I'm attempting to craft a regular expression that will only match terms containing the word Africa or any variation ...

Filtering Dropdown List in AngularJS with a Text Input Field and a Submit Button for Filtering Option Values

After exploring , I discovered a feature that enables users to type in a text box and filter results in a pseudo-dropdown. My goal is to enhance this functionality or come up with a better approach for users to type and filter select box options, ultimate ...

Webpack is ejected from watch mode

Currently, I am in the process of learning React and have decided to use webpack alongside it. However, I seem to be facing an issue with webpack when it comes to the watch mode. It builds the files once but then halts. The console output reflects the foll ...