Home > front end >  Changing multiple text with the same class with one button
Changing multiple text with the same class with one button

Time:07-03

So I want a text to show up under every input field(don't mind the 'iii', it's a dummy text) when it's empty. I have no idea why it's not working. I could do that by having every text as a different class but the code would look terrible. When I click a button, nothing happens. I know it's something simple but I can't pin point what it is. Thanks in advance for help.

const wrongDisplay = document.querySelectorAll('.wrongInfo');
const formData = document.querySelector('.formData');
const formInput = document.querySelectorAll('.formInput')
const firstPassword = document.querySelector('#firstPassword')
  const passwordConfirm = document.querySelector('#passwordConfirm')
const submitButton = document.querySelector('.submitButton')

submitButton.addEventListener('click', () => {
  formInput.forEach(el => {
       if(el.value === '') {
            wrongDisplay.textContent = 'required field'
       }
  });
});
<!DOCTYPE html>
<html lang="en">
    <head>
<meta charset="UTF-8">
<title> ol jeaa</title>
<link rel="stylesheet" href="./styles/style.css">
<body>

<!--Image on the left side of the page-->
<div >
    <img src="./images/pexels-marvin-machler-11127092.jpg">
</div>

<!--Main text on the page-->
<div >
    <main >
     
        <p>
          Start your online business journey today!
          All you have to do is sign up and post offers of items you want to sell!
    </main>


    <!-- Signup container -->
    <form action="#" method="get" >
    <fieldset >
      <div >
        <span>Let's do this!</span>

      <div >
        <label for="FirstName"  >First Name</label>
        <input type="text" id="FirstName" name="FirstName"  required>
        <span >iiii</span>
      </div>

      <div >
        <label for="email"  >Email</label>
        <input type="email" id="email" name="email"  id="emailInvalid" required>
        <span >iiii</span>
      </div>

      <div >
        <label for="password" >Password</label>
        <input type="password" id="firstPassword" name="password"  required >
        <span >iiii</span>
      </div>
    </div>


      <div >
        <span>Let's do this!</span>

      <div >
        <label for="LastName" >Last Name</label>
        <input type="text" id="LastName" name="LastName"  required>
        <span >iiii</span>
      </div>

      <div >
        <label for="phoneNumber" >Phone Number</label>
        <input type="tel" id="phoneNumber" name="phoneNumber"  required>
        <span >iiii</span>
      </div>
      
      <div >
        <label for="passwordConfirm" >Confirm Password</label>
        <input type="password" id="passwordConfirm" name="passwordConfirm"  required >
        <span >iiii</span>
      </div>
    </div>
    </fieldset>
    <div >
<button type="submit" >Create account</button>
</div>
</form>
  <script src="./scripts/script.js"></script>
</body>
    </head>
</html>

CodePudding user response:

Two things are wrong here.

First, and most important:
You are using wrongDisplay.textContent = 'required field' to set the field, but you declared wrongDisplay as the array of form inputs. You probably want

el.textContent = 'required field'

which will set the individual span's text content.

Second:
You declared required properties on the forms which won't allow the button to fire unless they're filled out. This is up to you on if you want these or not, or you could always move the submit button out of the form and handle your submit logic your way. Or you should instead, attach the listener to the form, on event "submit" as opposed to "click" and override default behavior with event.preventDefault(). Your choice.

CodePudding user response:

A few things to fix:

  • add novalidate attribute in form to prevent native HTML5 validation
  • add e.preventDefault() in click() handler to prevent form submission without validation
  • you were trying to set textContent to document.querySelectorAll('.wrongInfo'); as if it was a single element like document.querySelector('.wrongInfo');
  • you can use el.nextElementSibling instead, and you need to check if value is empty or not to remove "required field" when input has value after being invalid
  • your HTML isn't correct, fixed for you

const formInput = document.querySelectorAll('.formInput')
const submitButton = document.querySelector('.submitButton')

submitButton.addEventListener('click', e => {
  e.preventDefault();
  formInput.forEach(el => el.nextElementSibling.textContent = el.value === '' ? 'required field' : '');
});
<!--Image on the left side of the page-->
<div >
  <img src="./images/pexels-marvin-machler-11127092.jpg" />
</div>

<!--Main text on the page-->
<div >
  <main >
    <p>
      Start your online business journey today! All you have to do is sign up
      and post offers of items you want to sell!
    </p>

    <!-- Signup container -->
    <form action="#" method="post"  novalidate>
      <fieldset >
        <div >
          <span>Let's do this!</span>

          <div >
            <label for="FirstName" >First Name</label>
            <input
              type="text"
              id="FirstName"
              name="FirstName"
              
              required
            />
            <span >iiii</span>
          </div>

          <div >
            <label for="email" >Email</label>
            <input
              type="id"
              ="email"
              id="email"
              name="email"
              
              required
            />
            <span >iiii</span>
          </div>

          <div >
            <label for="password" >Password</label>
            <input
              type="password"
              id="firstPassword"
              name="password"
              
              required
            />
            <span >iiii</span>
          </div>
        </div>
        <div >
          <span>Let's do this!</span>

          <div >
            <label for="LastName" >Last Name</label>
            <input
              type="text"
              id="LastName"
              name="LastName"
              
              required
            />
            <span >iiii</span>
          </div>
          <div >
            <label for="phoneNumber" >Phone Number</label>
            <input
              type="tel"
              id="phoneNumber"
              name="phoneNumber"
              
              required
            />
            <span >iiii</span>
          </div>
          <div >
            <label for="passwordConfirm" 
              >Confirm Password</label
            >
            <input
              type="password"
              id="passwordConfirm"
              name="passwordConfirm"
              
              required
            />
            <span >iiii</span>
          </div>
        </div>
      </fieldset>
      <div >
        <button type="submit" >Create account</button>
      </div>
    </form>
  </main>
</div>

CodePudding user response:

I needed to close multiple unclosed tags so that I could start debugging the code. There’s this nifty websites where you can paste your html code and check for errors It’s called: W3Validator:

You also had duplicated attribute id's in one line #38 where only one ID is allowed. Classes on the other hand may have multiple but they are both defined once per attribute:

<p ></p>

but only one ID

<p id="theonlyId" >1</p>

Then into the code. I see you want to register a user, but that shouldn't be done by

<form method="get"> but use: method ="post"> instead.

I have also added an enctype to your html form: https://www.w3schools.com/TAGs/att_form_enctype.asp , it is up to you to decide which one you need.

The following code works upon copy/paste:

const wrongDisplay = document.querySelectorAll('.wrongInfo');
const formData = document.querySelector('.formData');
const formInput = document.querySelectorAll('.formInput');
const firstPassword = document.querySelector('#firstPassword');
const passwordConfirm = document.querySelector('#passwordConfirm');
const submitButton = document.querySelector('.submitButton');


// when you click on submitButton  then:
submitButton.addEventListener('click', function(e) {
 e.preventDefault();
// wrongDisplay is a NodeList, try opening a console in the webbrowser and type: wrongDisplay[0] and or wrongDisplay[1] on a new line, then access those properties by, for example: wrongDisplay[0].innerText
// if i, which is 0, is smaller then the total amount of classes named 'wrongInfo'', then increment by one
 for(let i=0; i <wrongDisplay.length; i  ){
  // so for each time the i, increments, the following line is printed on a new line and updates itself
   wrongDisplay[i].innerText= "required field";
   // innerText is safer to use then innerHTML
  }
});



// submitButton.addEventListener('click', () => {
//   formInput.forEach(wrongDisplay => {
//        if(el.value === '' || el.value === null) {
//             wrongDisplay.innerText = 'required field';
//        }
//   });
// });
<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title> ol jeaa</title>
  <link rel="stylesheet" href="./styles/style.css">
 </head>

  
 <body>

 <!--Image on the left side of the page-->
 <div >
     <img src="./images/pexels-marvin-machler-11127092.jpg" alt="description of the image when its not loaded">
 </div>

 <!--Main text on the page-->
 <div >
     <main >
      
         <p>
           Start your online business journey today!
           All you have to do is sign up and post offers of items you want to sell!
         </p>
     </main>


      <!-- the following div wasn't closed before, it might be possible that it should be closed at line #86-->
</div>
 <!-- the previous div wasn't closed before, it might be possible that it should be closed at line #86  -->

     <!-- Signup container -->
  <!-- <form action="#" method="post"  enctype=""> -->
   <form action="#" method="post"  enctype="application/x-www-form-urlencoded" novalidate>
   <fieldset >
     <div >
       <span>Let's do this!</span>

     <div >
       <label for="FirstName"  >First Name</label>
       <input type="text" id="FirstName" name="FirstName"  required>
       <span >iiii</span>
     </div>

     <div >
       <label for="email"  >Email</label>
       <input type="email" id="email" name="email"  required>
       <span >iiii</span>
     </div>

     <div >
       <label for="password" >Password</label>
       <input type="password" id="password" name="password"  required >
       <span >iiii</span>
     </div>

   </div>

    <div >
       <span>Let's do this!</span>

     <div >
       <label for="LastName" >Last Name</label>
       <input type="text" id="LastName" name="LastName"  required>
       <span >iiii</span>
     </div>

     <div >
       <label for="phoneNumber" >Phone Number</label>
       <input type="tel" id="phoneNumber" name="phoneNumber"  required>
       <span >iiii</span>
     </div>
     
     <div >
       <label for="passwordConfirm" >Confirm Password</label>
       <input type="password" id="passwordConfirm" name="passwordConfirm"  required >
       <span >iiii</span>
     </div>
   </div>
  </fieldset>

   <div >
  <button type="submit" >Create account</button>
  </div>
  </form>

 <script src="./scripts/script.js"></script>

 </body>
   
</html>

I hope this has helped you and if not please do notify :)

  • Related