JavaScript function to change ID once

My challenge is to dynamically add new entries with a fadeIn effect after submitting a form. Each entry is created using javascript template literals, containing divisions with unique classes and ids. Currently, all entries share the same ID for animation, which I am aware is not ideal and I'm attempting to resolve.

In my javascript code snippet:

var enrolledStudents = [];

let form = document.getElementById("student-enrollment-form");

const getStudentDetails = (event) => {
    ...
}

const changeIds = () => {
    ...
}

I am unable to utilize any libraries or frameworks for this task. The issue arises when changing IDs in the function 'changeIds,' as only the first entry retains the new ID while subsequent entries remain unaffected.

What could be causing this problem?

For reference, here is a snippet of my HTML code:

<!doctype html>
...
<body>
   ...
    <nav class="navbar text-center">
        ...
    </nav>
          
    <div class="container">
      ...
      <form id="student-enrollment-form">
          ...
          <button type="button" class="btn btn-primary" onclick="getStudentDetails(event)">Enroll Student</button>

        
        </div>
          
      ...

 <script src="script_js.js"></script>
  </body>
</html>

Additionally, here is the CSS code relating to animations:

#right-col-header{
    text-align: center;
}
ul{
   ...
}
...
#student-id-image{
   ...
}

@keyframes fadeIn {
   ...
}

#student-id-details{
   ...
}

I would appreciate alternative solutions for implementing animations exclusively on new entries.

Answer №1

To implement the fade-in-animation class on a new entry, you need to apply it specifically to that element. The current logic applies the animation class to all list items.

I have made some minor updates to your code that should assist you in achieving this. Thank you

var enrolledStudents = [];

let form = document.getElementById("student-enrollment-form");

const getStudentDetails = (event) => {
    event.preventDefault();

    // This is the important check for form validity
    if (form.checkValidity() === false){
        form.reportValidity();   
        return; 
    }
    var skillsList = [];
    var name = document.getElementById("name-input").value;
    var email = document.getElementById("email-input").value;
    var website = document.getElementById("website-input").value;
    var imgLink = document.getElementById("imglink-input").value;
    var gender = document.querySelector('input[name="genderRadio"]:checked').value;
    var skills = document.querySelectorAll('input[type="checkbox"]');

    skills.forEach(item => {
        if (item.checked){
            skillsList.push(item.value);
        }
    })

    var student = {
        'name': name,
        'email': email,
        'website': website,
        'imageLink' : imgLink,
        'gender': gender,
        'skills': skillsList,
    }
    enrolledStudents.push(student)
    console.log(enrolledStudents);
    
    const studentList = document.getElementById('student-list');
    studentList.innerHTML = `${
        enrolledStudents.map((student, index) => {
            var passport = student.imgLink;
            return `
                <div class="row ${enrolledStudents.length === (index + 1) ? 'fade-in-animation' : ''}" style="border: 2px solid black;  border-top: none; height: 120px;">
                    <div class="col" style="padding-top: 10px; padding-bottom: 5px; height: 100px;">
                        <h6 class="card-title">${student.name}</h6>
                        <p class="card-text">${student.gender}<br />${student.email}<br />${student.website}<br />${student.skills} ${index}</p>
                        
                    </div>
            </div>
            `;
        }).join("")
    }`

    
    const studentImages = document.getElementById("student-images");
    console.log(enrolledStudents)
    studentImages.innerHTML = `${
        enrolledStudents.map((student, index) => {
            return `
                <div class="row ${enrolledStudents.length === (index + 1) ? 'fade-in-animation' : ''}" style="border: 2px solid black;  border-top: none; border-left: none; height: 120px">
                    <div class="col" style="padding-top: 10px; padding-bottom: 6px; height: 120px; align-items: centre;">
                        <img src=${student.imageLink}></img>
                    </div>
                </div>

            `
        }).join("")
    }`
}
#right-col-header{
    text-align: center;
}
ul{
    padding-left: 0;
    list-style-type: none;
}
p{
    font-size: 13px;
}
img{
    height: 6em;
    width: 6em;
}
#student-ids{
    height: 90%;
    overflow-x: auto;
}

@keyframes fadeIn {
    0% { opacity: 0; }
  100% { opacity: 1; }  
}


.fade-in-animation{
    animation: fadeIn 2s;
    -webkit-animation: fadeIn 2s;
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Student Enrollment</title>
    <link href="style.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
  </head>
  <body>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9As...
    
        <nav class="navbar text-center" style="background-color: #59CE8F;">
            <div class="container-fluid text-center">
              <span class="navbar-brand mb-0 h1 text-center" style="color: white;">Student Enrollment Form</span>
            </div>
          </nav>
          
    <div class="container">
      <div class="row">
        <div class="col" style="height: 35px;"></div>
      </div>

      <div class="row">

        <div class="col" style="border-right: 3px solid #59CE8F;"> 

          <form id="student-enrollment-form">
          <div class="row mb-3">
            <label for="name-input" class="col-sm-2 col-form-label">Name</label>
            <div class="col-sm-5">
              <input type="text" class="form-control" id="name-input"/>
            </div>
          </div>

          ...

</html>

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

Maintain the dimensions of the dragged object when moving it across another object in a React application

I'm currently developing an application that allows users to rank different sentences by using a drag and drop feature in React. However, I have encountered an issue where the size of the dragged items changes when they interact with other items of va ...

What is the best way to iterate through an object in Typescript? The element currently holds a type of 'any' due to the index expression not being of type 'number'

Obtaining Element implicitly has an 'any' type because the index expression is not of type 'number'. interface User { name: string; username: string; profileImage: string; } let user:User = { name: 'Alice', ...

Adding an Icon to a Tab in Ant Design - A Step-by-Step Guide

Is there a way to include an icon before the title of each open tab? I am currently using the antd library for tab creation, which doesn't provide a direct option for adding icons. Here is my code snippet along with a link to the jsfiddle https://jsfi ...

Managing web-based PDF documents with images that require authentication

Currently, I am generating PDF documents on the server side using wkhtmlpdf and nodejs. The HTML to be rendered is sent from the client side, which may contain img tags with a source. When the user previews the HTML in the browser, the images they have upl ...

Whenever I execute my nodejs script, I encounter the following error message: "TypeError: Cannot read property 'apply' of undefined."

I've encountered an issue in my node.js application where I have created a controller and a service. Every time I attempt to run the application, I consistently receive this error. The objective is to have a GET method that retrieves any table based o ...

Authentication with Laravel and Vue.js

After successfully implementing Laravel-Vue.js Authentication using Passport API, I am now able to obtain the token and send requests to api/user. Initially, I used the normal authentication process by sending data through a POST request to /login, which r ...

The functionality of ngToast's newestOnTop feature is not performing as anticipated

I've been attempting to stack the toast messages generated by ngToast on top of each other. After reading through the documentation at , I came across a parameter labeled "newestOnTop". I implemented it in my app.coffee file like this: ngToastProvide ...

Trouble with modifying style in Google Chrome and Internet Explorer prior to AJAX request

When utilizing AJAX, I have a common practice of setting up a loading indicator before each request to inform the user about the short wait. Usually, this is achieved by adding an animated loading gif. Interestingly, when performing this action in Firefox, ...

bootstrap 4.5 navbar spanning the entire width of the screen

I'm facing an issue with creating a basic navbar. It's not extending the full width of my page and not responding to color classes either. Here's the code for my header: <body> <div class="container-fluid"> <header> ...

Ways to showcase the refined object array upon clicking a button in Angular

I have been working on a project to create a task management system. The project consists of two main components: itemList and item. The itemList component takes input values for tasks and displays them in the item component. https://i.sstatic.net/SaRNMm. ...

"Please note that the function of the enter key to navigate between form fields is

When I use the enter key to move between form fields, it's not working as expected: The cursor doesn't move to another field in the form when I press the enter key. Removing the submit button allows the enter key to work properly. The issue se ...

Combining the Powers of JavaScript and ASP.NET

Describing the ASP.NET GridView control: <asp:GridView ID="gvReq" runat="server" AllowSorting="True" DataKeyNames="Req_ID,Approved,supervisor_login,Revised,Requested_Login,HasDocs" DataSourceID="objdsReq" AllowPaging="True" PageSize="30" > Within t ...

Encase a component with a personalized class of my own creation

X-editable showcases the use of default checkboxes, demonstrated in this example. My goal is to encapsulate the template responsible for creating the checklist within a custom class (<div class="...) that will style the elements according to my prefere ...

When transferring data from Django rest framework to a JavaScript array, there may be issues with missing

Struggling to retrieve data from my API endpoint using AJAX. During the iteration of the JSON object to populate my JavaScript array, I seem to be overlooking some values. Here's a breakdown: API data: HTTP 200 OK Allow: GET, HEAD, OPTIONS Conte ...

Exploring the method of finding the second lowest and second highest values within an array

Hey there fellow Stack users, Please excuse me if this question has already been asked or is too basic (I'm still new to Javascript). Recently, I've been working on some w3c js challenges: Create a JavaScript function that can identify the seco ...

Cannot retrace steps in file tree using ../

My website has a file structure set up like this: css style.css other files... templates index.html other files... I am attempting to reference the style.css file from my index.html document. My initial attempt was to navigate back a directory u ...

tips on locating the next immediate downloadable cell in a table

My table includes cells with colspan and rowspan attributes. <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table border=1 id="mytable" > <tr><td>A1</td> <td> A2 < ...

The scaling feature in CSS does not function properly in Internet Explorer 8

I've tried multiple approaches to transform the IE Matrix, but I'm facing an issue with the transform scale CSS not functioning in IE8. Code: .fture_box ul li.fture_img img{ width: 451px; height: 284px; display: block; margin: 0 0px 0 11px; pad ...

Loop through an array that holds another array in javascript

After making a post request, I am receiving the following object: "{\"Success\":false,\"Errors\":{\"Name\":[\"The Name field is required.\"],\"Id\":[&b ...

What is the best way to adjust the textfield's size proportionally to its parent accordion when the window is resized?

Inside an accordion, I placed a text field with specific widths and heights. However, when I resize the browser window, the accordion width changes proportionally to the window size while the text field width remains the same. This causes the text field to ...