I was able to resolve the display block issue, but I suspect there might be a mistake in my conditional statement

Looking for some help here - I want my user prompts to be displayed in block form, while the user story and error messages should remain hidden until the user enters their inputs. However, my script seems to be malfunctioning and I can't figure out what's wrong.

Edit: Thanks to everyone who helped me fix the display block issue. But now, when I added a condition to ensure all fields are filled before submission, the error message appears prematurely on the page. Any assistance with this would be greatly appreciated.

     const userprompts = document.querySelector("#prompts");
    const userstory = document.querySelector("#story");
    const usererror = document.querySelector("#error");

    const submit = document.querySelector("#submit");
    submit.addEventListener("click", completestory, false);

    const reset= document.querySelector("#reset");
    reset.addEventListener("click", resetPage, false);

    document.querySelector('#name').focus();

    const thename = document.querySelector("#name");
    const firstverb = document.querySelector("#firstverb");
    const firstnoun = document.querySelector("#firstnoun");
    const adjective = document.querySelector("#adjective");
    const secondnoun = document.querySelector("#secondnoun");
    const adverb = document.querySelector("#adverb");
    const place = document.querySelector("#place");
    const storyOutput = document.querySelector("#storyOutput");

    userprompts.classList.add("displayBlock");
    userstory.classList.add("displayNone");
    usererror.classList.add("displayNone");

    function checkStory() {
      if (thename.value == "" && firstverb.value == "" && firstnoun.value == "" && adjective.value == "" && secondnoun.value == "" && adverb.value == "" && place.value == "") {
        error.classname.add("displayBlock");
        return false;
      }
      else {
        return true:
      }
    }

    function completestory() {

      let finishedstory = "";
      finishedstory += "There once was a person named " + thename.value + ". ";
      finishedstory += "One day, " + thename.value + " was " + firstverb.value + " out in the "
      + firstnoun.value + ". ";
      finishedstory += "All of a sudden, " + thename.value + " saw a " + adjective.value +
      " dragon! " ;
      finishedstory += thename.value + " thought for a second and did the only thing that came to mind "
      + " and grabbed a " + secondnoun.value + ". " ;
      finishedstory += "With the " + secondnoun.value + " in hand, " + thename.value + " jumped up and " + adverb.value + " attacked the dragon.";
      finishedstory += " The dragon became very confused and left. Our hero returned to their ancestral home of " + place.value + " ." +  " The End?";

      storyOutput.innerHTML = finishedstory;

      userprompts.classList.add("displayNone");
      userstory.classList.add("displayBlock");
      usererror.classList.add("displayNone");
      userprompts.classList.remove("displayBlock");
      userstory.classList.remove("displayNone");
      usererror.classList.remove("displayBlock");

      if (checkStory == false); {
        return;
      }

    }

    function resetPage() {
      userprompts.classList.add("displayBlock");
      story.classList.add("displayNone");
      error.classList.add("displayNone");
      userprompts.classList.remove("displayNone");
      userstory.classList.remove("displayBlock");
      usererror.classList.remove("displayBlock");
      thename.value = "";
      firstverb.value = "";
      firstnoun.value = "";
      adjective.value = "";
      secondnoun.value = "";
      adverb.value = "";

      storyOutput.innerHTML = "";

      thename.focus();

    }
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link rel="stylesheet" href="Mod3Layout.css">
    <meta charset="utf-8">
    <title>Sean's Mad Lib</title>
  </head>
  <body>
    <h1> Sean's Wacky Mad Lib</h1><hr>

    <div id="prompts">
      <h3>Please enter your prompts here</h3>
      <p>Enter a name here:
        <input id="name" type="text" placeholder="name">
        </p>
        <p>Enter a verb here:
          <input id="firstverb" type="text" placeholder="verb 1">
          </p>
          <p>Enter a noun here:
            <input id="firstnoun" type="text" placeholder="noun 1">
            </p>
            <p>Enter an adjective here:
              <input id="adjective" type="text" placeholder="adjective">
             </p>
             <p>Enter another noun here:
               <input id="secondnoun" type="text" placeholder="noun 2">
             </p>
             <p>Enter an adverb here:
               <input id="adverb" type="text" placeholder="adverb">
             </p>
             <p>Finally, Enter a place here:
               <input id="place" type="text" placeholder="place"
               </p><br>
             <button id="submit" type="button">Submit</button>
             <p id="error">You did not answer all the questions. Please try
               again</p>
      </div>
      <div id="story">
        <p>Let's see what you wrote.</p>
        <p id="storyOutput">Hello Dave</p>
        <button id="reset" type="button" name="Reset">Reset</button>
        </div>

Answer №1

With the power of jquery, you have the ability to easily update CSS styles. Look at the example below

example code for updating CSS using jquery.

$("#prompts").css("background-color", "yellow");

example code for applying a class name with jquery.

$( "#prompts" ).addClass( "displayBlock" );

You can also remove and add classes simultaneously.

$( "#prompts" ).removeClass( "displayNone" ).addClass( "displayBlock" );

Answer №2

If you're working with vanilla JS, my suggestion would be to utilize the .style property for making changes in the CSS.

For instance:

document.getElementById("myDIV").style.display = "none";

Resource:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style https://www.w3schools.com/jsref/prop_style_display.asp

However, if you need to add a class in your specific scenario,

When it comes to adding a class in vanilla JS, I recommend using the classList method.

Example for addition:

const element = document.querySelector("#myDIV");
element.classList.add("mystyle");

Example for removal:

const element = document.querySelector("#myDIV");
element.classList.remove("mystyle");

Resource:

https://www.w3schools.com/howto/howto_js_add_class.asp https://www.w3schools.com/howto/howto_js_remove_class.asp

Answer №3

To implement user actions, you must add and remove classes accordingly. Addition can be done using element.classList.add(), while removal can be achieved with element.classList.remove(). Ensure that the necessary CSS properties are defined for the classes being manipulated. Feel free to test the provided code snippet.

const userprompts = document.querySelector("#prompts");
    const userstory = document.querySelector("#story");
    const usererror = document.querySelector("#error");

    const submit = document.querySelector("#submit");
    submit.addEventListener("click", completestory, false);

    const reset= document.querySelector("#reset");
    reset.addEventListener("click", resetPage, false);

    document.querySelector('#name').focus();

    const thename = document.querySelector("#name");
    const firstverb = document.querySelector("#firstverb");
    const firstnoun = document.querySelector("#firstnoun");
    const adjective = document.querySelector("#adjective");
    const secondnoun = document.querySelector("#secondnoun");
    const adverb = document.querySelector("#adverb");
    const place = document.querySelector("#place");
    const storyOutput = document.querySelector("#storyOutput");

    userprompts.classList.add("displayBlock");
    userstory.classList.add("displayNone");
    usererror.classList.add("displayNone");

    function checkStory() {

    }

    function completestory() {
      let finishedstory = "";
      finishedstory += "There once was a person named " + thename.value + ". ";
      finishedstory += "One day, " + thename.value + " was " + firstverb.value + " out in the "
      + firstnoun.value + ". ";
      finishedstory += "All of a sudden, " + thename.value + " saw a " + adjective.value +
      " dragon! " ;
      finishedstory += thename.value + " thought for a second and did the only thing that came to mind "
      + " and grabbed a " + secondnoun.value + ". " ;
      finishedstory += "With the " + secondnoun.value + " in hand, " + thename.value + " jumped up and " + adverb.value + " attacked the dragon.";
      finishedstory += " The dragon became very confused and left. Our hero returned to their ancestral home of " + place.value + " ." +  " The End?";

      storyOutput.innerHTML = finishedstory;

      userprompts.classList.add("displayNone");
      userstory.classList.add("displayBlock");
      usererror.classList.add("displayNone");
      userprompts.classList.remove("displayBlock");
    userstory.classList.remove("displayNone");
    usererror.classList.remove("displayBlock");
    }

    function resetPage() {
      userprompts.classList.add("displayBlock");
      story.classList.add("displayNone");
      error.classList.add("displayNone");
userprompts.classList.remove("displayNone");
    userstory.classList.remove("displayBlock");
    usererror.classList.remove("displayBlock");
      thename.value = "";
      firstverb.value = "";
      firstnoun.value = "";
      adjective.value = "";
      secondnoun.value = "";
      adverb.value = "";

      storyOutput.innerHTML = "";

      thename.focus();

    }
.displayBlock{
display: block;
}

.displayNone{
display: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link rel="stylesheet" href="Mod3Layout.css">
    <meta charset="utf-8">
    <title>Sean's Mad Lib</title>
  </head>
  <body>
    <h1> Sean's Wacky Mad Lib</h1><hr>

    <div id="prompts">
      <h3>Please enter your prompts here</h3>
      <p>Enter a name here:
        <input id="name" type="text" placeholder="name">
        </p>
        <p>Enter a verb here:
          <input id="firstverb" type="text" placeholder="verb 1">
          </p>
          <p>Enter a noun here:
            <input id="firstnoun" type="text" placeholder="noun 1">
            </p>
            <p>Enter an adjective here:
              <input id="adjective" type="text" placeholder="adjective">
             </p>
             <p>Enter another noun here:
               <input id="secondnoun" type="text" placeholder="noun 2">
             </p>
             <p>Enter an adverb here:
               <input id="adverb" type="text" placeholder="adverb">
             </p>
             <p>Finally, Enter a place here:
               <input id="place" type="text" placeholder="place"
               </p><br>
             <button id="submit" type="button">Submit</button>
             <p id="error">You did not answer all the questions. Please try
               again</p>
      </div>
      <div id="story">
        <p>Let's see what you wrote.</p>
        <p id="storyOutput">Hello Dave</p>
        <button id="reset" type="button" name="Reset">Reset</button>
        </div>

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

Implementing the map function in ReactJS to showcase data on the user interface

I seem to be facing an issue while attempting to utilize an array of data to display a <ul> element. Despite the console.log's working correctly in the code provided below, the list items fail to show up. <ul className="comments"&g ...

Using single quotation marks within a string can cause issues in javascript

I am curious about how to handle single quote marks and other symbols within user-generated text without causing issues with the JavaScript code. Currently, if a user enters a title like "I wouldn't", it breaks the JavaScript functionality. <a cl ...

Return an array with only emails included

Looking to sort through an array specifically for emails, I attempted the following action emails = emails.filter((x)=>(x !== (undefined || null || ''))) To remove any empty values, while still allowing non-email values. ...

Tips for passing multiple values with the same key in Axios as parameters

I need to develop a function that allows users to select multiple categories and subcategories, then send their corresponding ids as a query string using Axios. For example, if a user selects category IDs 1 and 2, along with subcategory IDs 31 and 65, the ...

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...

Understanding how to accurately pair specific data points with their corresponding time intervals on a chart

I'm currently working with apexcharts and facing an issue with timestamps. I have data for sender and receiver, each having their own timestamps. The x-axis of the graph is based on these timestamps, but I am struggling to map the timestamp with its r ...

Stopping Amazon Web Services Lambda functions from running on their own

I've implemented a Lambda function that is triggered whenever a new folder object is created in the root bucket. A unique identifier is generated for each folder object, such as 67459e53-20cb-4e7d-8b7a-10e4cd165a44 Within the root bucket, there is a ...

Unrestricted access to Fetch from Origin in Express.js is restricted by CORS policy

I'm trying to send data from a basic html form to an Express.js endpoint. However, when I attempt to post the data, I encounter the following error: "Access to fetch at 'https://samplesite.net/sample' from origin 'https://samplesi ...

NodeJS Fork - React each instance a new line is detected from the child process

I am currently working on creating a NodeJS function (on Windows7) that listens to a subprocess and handles each newline sent through the subprocess in Node. The following example demonstrates this: var express = require('express'); var app = ex ...

Exploring the magic of Hover effects using CSS and JQuery

I am exploring ways to enhance the display of an element when hovering over it. I have implemented a button and my objective is for the first click to activate the hover effect, while the second click will reset it. However, I am facing an issue where the ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

What is the process for retrieving an excel file from the backend to the frontend?

I am currently facing an issue where I want to initiate a browser download of an excel file that is generated in my backend. However, I am struggling to figure out how to pass this type of response. app.get('/all', function (req, res) { db.q ...

Checkbox click triggers a delayed update to the array

In my attempt to develop an array of user permissions that can be managed through a series of checkboxes, I encountered an issue. When I select a checkbox and use console.log() to display the array, it shows all the permissions I have checked. However, upo ...

Retrieve a collection of CSS classes from a StyleSheet by utilizing javascript/jQuery

Similar Question: Is there a way to determine if a CSS class exists using Javascript? I'm wondering if it's possible to check for the presence of a class called 'some-class-name' in CSS. For instance, consider this CSS snippet: & ...

Is it possible to extract a user's password from the WordPress database for use in a React application

Is it feasible to create a React application integrated with Postgres within Wordpress that operates on MySql? I am interested in leveraging Wordpress's built-in features for theming, posts, and user management accounts. However, I am unsure if I can ...

Protecting a Web Function

Suppose I have a C# MVC method to send emails using AJAX, like this: public class EmailController : Controller { SmtpClient mailserver = new SmtpClient("smtp.foo.com"); public string sendEmail(string from, string to, string subject = "", ...

Expanding a non-bootstrap navigation bar upon clicking the menu

I'm having some difficulty getting my navigation menu to show up when I click the navigation menu icon. HTML nav role="navigation" class="navbar"> <div class="nav-header"> <a href="#"><span style="font-family: 'Cab ...

Error in Node.js: attempting to invoke the 'use' method on an undefined object

Currently in the process of learning about node.js and encountering a perplexing error. app.use(morgan('dev')); //log request to console TypeError: Cannot call method 'use' of undefined at Object.<anonymous> (/root/authproject/se ...

Error in React Router when using TypeScript

Encountering errors while trying to set up router with React and TypeScript. https://i.sstatic.net/muSZU.png I have already attempted to install npm install @types/history However, the issue persists. Your assistance would be greatly appreciated. Thank y ...

Vue.js Ready event is not firing

In my Vue function, I have two methods. The first method, postStatus, is used to save a post when the user clicks on the save button. The second method, getPosts, is used to retrieve all previous posts from the database for that user. Below is the Vue.js ...