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

Is it acceptable to assign a value to exports.new?

In my venture with Node.js and Express, I am aiming for simplicity. Drawing from my experience with Rails, I am following the RESTful structure typical in Rails applications. In setting up my controllers (or routes), I want them to resemble this: // route ...

Prevent Purchase Button & Implement Modal on Store Page if Minimum Requirement is not Achieved

On my woocommerce shop page, I am facing an issue where all items are added to the mini-cart without meeting the minimum order requirement. This results in users being able to proceed to checkout without adding enough items to meet the minimum order amount ...

Verify if a <select> element exists inside the main div

Is there a way for me to check if a <select> element is present within the parent div and display certain content based on its existence? Appreciate any assistance! ...

An error in TypeScript has occurred, stating that the type 'IterableIterator<any>' is neither an array type nor a string type

Hey there! I'm currently working on an Angular project and encountering an error in my VS Code. I'm a bit stuck on how to fix it. Type 'IterableIterator<any>' is not an array type or a string type. Use compiler option '- ...

Problem encountered while extracting data from HTML structure using indexing

My current task involves scraping data from a specific html structure found on 30-40 webpages, such as the one below: https://www.o2.co.uk/shop/tariffs/sony/xperia-z-purple/: <td class="monthlyCost">£13<span>.50</span></td> ...

Is there a way to view the contents of a file uploaded from <input type="file" /> without the need to send it to a server?

Having trouble uploading a JSON file from my local disk to Chrome storage. Whenever I use the <input type="file"> tag and useRef on the current value, it only returns the filename prefixed with 'C:\fakepath...' ImportExport Component: ...

ngSwitchCase provider not found

While following a tutorial and trying to implement what I learned, I encountered an error that I'm having trouble understanding. The browser console shows an error message stating [ERROR ->]<span *ngSwitchCase="true">, but I can't figure ...

Unable to output value in console using eventListener

Hey everyone, I'm new to JavaScript and trying to deepen my understanding of it. Currently, I am working on an 8 ball project where I want to display the prediction in the console. However, I keep getting an 'undefined' message. const predi ...

Integrate Ruby parameter into JavaScript in Rails

I have a div that I want to turn into a link to another page. Typically, we achieve this using link_to link. <% for item in @items %> <%= link_to "Item", item %> # -> or <%= link_to(item) %> <% end %> However, I need the ent ...

What is the process for inserting HTML content into the body of an iframe?

Is there a way to insert HTML content into the body of an iframe instead of using the src attribute to call a page's URL? I am looking for a code that is compatible with all browsers and works perfectly. ...

What is the best way to customize the color of the border and icon in an outlined MaterialUI input field

I'm a newcomer to materialUI and I have a question regarding customizing an outlined input field with an icon. Due to my dark background, I need the icon, border, and text color to be lighter, such as grey. Can someone please advise on the materialUI ...

transition from mapStateToProps to using hooks

Just dipping my toes into the world of React (hooks) and learning by writing code. I'm grappling with converting MapStateToProps to hooks, specifically stuck on one part just before 'currentItem'. Here's the original code snippet: co ...

Is there a way to rearrange my divs in the mobile display?

Is there a way to make the image column stack below the text info column in mobile view? I've tried using flexbox without success, so any help would be greatly appreciated. Thank you! <div class="container"> <div class="row"> ...

Alter the class of the div element every three seconds

Greetings, I trust everyone is doing well. I am in need of some assistance from your brilliant minds. I have a circular div along with three CSS classes, and my objective is to switch the div's class and update the label text every 3 seconds. Any insi ...

Selecting radio button does not update corresponding label

I am having an issue with setting a radio button as checked. In the example snippet, it works perfectly fine but on my localhost, it is not working. Even though the input gets checked, the label does not change. Surprisingly, if I set another radio button ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

Why can't the file upload button locate its CSS styles?

Check out this jFiddle demonstrating the issue. Some of the Angular code may appear broken in the example, but that's just due to it being pasted into jFiddle; it's not an actual problem I'm facing. The CSS styles aren't working on the ...

FullCalendar dayClick event fails to trigger any action

I'm having trouble implementing the dayClick function in my fullCalendar. Despite setting up the calendar correctly, nothing happens when I click on a day. Here is the code I am using : var calendar; $(document).ready(function(){ app.init(); ...

What are some methods for preventing JavaScript function calls from the browser console?

In the process of developing a web application using HTML and JavaScript, I'm looking for a way to prevent users from accessing functions through their browser console in order to maintain fairness and avoid cheating. The functions I want to protect a ...

Encountered an issue with locating the module 'webpack-cli/bin/config-yargs' while attempting to run webpack-dev

Encountering an error while trying to start the webpack dev server with the command provided below. Despite suggestions that it could be due to outdated webpack versions, I am confident that all components are up to date: [email protected] [email ...