Build an interactive phone directory with the power of JavaScript!

Does anyone know the best way to implement this code snippet for user input and output tables using JavaScript? Take a look here

This is what I have tried so far:

/*index.html*/
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css" />
</head>

<body onload="createTable()">
    <div class='box'>
        <h4>New Contact</h4>
    <form>
        <div class="form-group">
            
            <label for="formGroupExampleInput">Name<span class="required">*</span></label>
            <input type="text" class="form-control" id="formGroupExampleInput">
        </div>
        <div class="form-group">
            <label for="formGroupExampleInput2">Phone<span class="required">*</span></label>
            <input type="text" class="form-control" id="formGroupExampleInput2">
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
    </div>
    <div>
        <p>
            <input type="button" id="addRow" value="Add New Row" onclick="addRow()" />
        </p>
        <div id="cont"></div>   <!--the container to add the table.-->
        <p><input type="button" id="bt" value="Submit Data" onclick="submit()" /></p>
    </div>
    

    

    
</body>

<!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>

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

</html>

/*style.css*/

body {
    background-color: lightsteelblue;
}
h4{
    text-align: center;
}
.required {
    color: red;
  }

.box {
    width: 300px;
    border: 15px solid white;
    border-radius: 25px;
    padding: 50px;
    margin: 20px;
    background-color:white;
  }

I'm struggling with creating the right side table that should only appear when all data is entered on the left side. Once 'Add' is clicked, the row should be added to the right side table with an auto-numbered ID column. Additionally, there should be an 'Action' button on each row to delete it.

I would really appreciate any help as my knowledge of JavaScript is limited.

Answer №1

Discover the code snippet below to meet your specific requirements. Customize the HTML format according to your needs.

var rowIndex = 1;
    function addRow() {
       var tableElement = document.getElementsByClassName('table')[0];
       var newRow = document.createElement('tr');
       newRow.id = rowIndex;
       var nameValue = document.getElementById('formGroupExampleInput').value.trim();
       var phoneValue = document.getElementById('formGroupExampleInput2').value.trim();
       
        var cell1 = createHtmlElement('', 'td', rowIndex);
        var cell2 = createHtmlElement('', 'td', nameValue);
        var cell3 = createHtmlElement('', 'td', phoneValue);
        var cell4 = createHtmlElement('', 'td', '');
        
        var button = createHtmlElement('btn' + rowIndex, 'button', 'Remove');
        button.value = 'Remove';
        button.onclick = function() { onClickRemoveRow(this); };
        
         newRow.appendChild(cell1);
         newRow.appendChild(cell2);
         newRow.appendChild(cell3);
         newRow.appendChild(cell4);
         cell4.appendChild(button);
         
         rowIndex = rowIndex + 1;
         
         tableElement.appendChild(newRow);
         
         return false;
    }
    
    function onClickRemoveRow(event) {
        rowIndex = event.id.replace('btn','');
         var currentRow = document.getElementById(rowIndex);
       alert(rowIndex);
       if (currentRow != null) {
            
        var tableElement = document.getElementsByClassName('table')[0];
            tableElement.removeChild(currentRow);
       }
    }
    
        function createHtmlElement(id, tagname, content) {
          var newTag = document.createElement(tagname);
          newTag.id = id;
          newTag.innerText = content;
          if (tagname =='button') {
            newTag.type = 'button';
          }
          
          return newTag;
        }
  
    
    <div class="row">
      <<div class="col-md-4">
         <form>
        <div class="form-group">
            
            <label for="formGroupExampleInput">Name<span class="required">*</span></label>
            <input type="text" class="form-control" id="formGroupExampleInput">
        </div>
        <div class="form-group">
            <label for="formGroupExampleInput2">Phone<span class="required">*</span></label>
            <input type="text" class="form-control" id="formGroupExampleInput2">
        </div>
        <input type="button" onclick="return addRow()" class="btn btn-primary" value="Add"/>
    </form>
      </div>
      <div class="col-md-8">
              <table class="table">
                  <thead>
                    <tr>
                      <th scope="ID">#</th>
                      <th scope="col">Name</th>
                      <th scope="col">Phone</th>
                      <th scope="col">Removed</th>
                    </tr>
                  </thead>
                  <tbody>
                  </tbody>
                  </table>
    
      </div>
    </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

Automatically assigning a FormData key/value pair upon clicking using Puppeteer in NodeJS

While working on a NodeJS project, I am using Puppeteer to fill out a form. So far, the regular type and click functions work perfectly. After clicking the "submit" button, a POST request is sent to the server with some form data. I want to add a key/value ...

When rotating, the SVG ellipses move towards the upper left corner

Why does my animated lp end up in the top left corner instead of centering? I've tried using transform-origin: center; but it's not working. Any help would be greatly appreciated. Thank you in advance. #Component_6_2{ -webkit-transform-orig ...

Next.js encountered a Runtime Error: Trying to access properties of undefined (specifically 'status') and failing

For those interested in viewing the code, it can be found here During the creation of a portfolio website using Next.js, I encountered an error. I am utilizing the latest version of Next.js (next 13.4.16) and incorporating the app router into my project. ...

React Form Hook: restoring uniform width to selectors once more

Looking to create a form using React form hooks and Material UI? Check out this link to codesandbox to see the code in action. In the CreateEmployee.tsx file under components\execute folder, you'll find the necessary code. There's also a UI ...

Convert the value of the <textarea> element to HTML encoding

Is there a way to fetch the most recent updated value entered in a textarea and encode it in HTML format? I usually use this code snippet to retrieve the value: $('textarea').val(); // works consistently across browsers However, if the value c ...

Is there a way to extract all the class names from a JavaScript file?

I am currently working on developing a code to showcase all the public properties of a class that are available in a JavaScript file. As of now, the user has to manually input the name of the class in a text box. However, my goal is to enhance user experie ...

Is it possible to extract around 10 variables from a JavaScript code, then display them on a webpage after execution?

I have just completed writing a Javascript code with around 3,000 lines. This code contains over 60 variables, but there are a few specific variables that I would like to display on my main HTML page. These variables include: totalTime longitudinalAcceler ...

Each time the page is refreshed, the objects in Three.js load in varying positions due to the OBJMTLloader

My scene is populated with various objects: var objectInfo = [ {"objURL":"3D/Barrel/barrel.obj", "mtlURL":"3D/Barrel/barrel.mtl","xPOS":0,"yPOS":-2,"zPOS":-260,"xROT":0,"yROT":0,"zROT":0,"scaleX":0.6,"scaleY":0.6,"scaleZ":0.6}, {"objURL":"3D/Sofa/sofa.obj ...

Update the message displayed in MUI DataTables when there are no matching records found

Whenever the data array in my MUIDataTable is empty, a default message pops up stating: "Sorry, no matching records found". I'm looking to personalize this message and input my own text. Any assistance would be greatly appreciated. ...

Is it recommended for Protractor Page Objects to reveal ElementFinder?

Our team is currently debating whether or not to prohibit the exposure of "ElementFinder" and "ElementArrayFinder" in our Page Objects. The main point of contention is a quote by Simon Stewart. Page Objects Done Right - selenium conference 2014 (page.7) ...

What is the most efficient way to extract dynamically generated JavaScript content from a webpage?

Currently, my method involves using selenium alongside PhantomJS to scrape dynamic content generated by JavaScript on a website. Although it provides me with the desired results, the process is quite slow as I have to wait for the entire page to load befor ...

spaces between sections with no padding or borders

I came across the following layout on the web and noticed that the divs do not align perfectly. The top of a lower div does not touch the bottom of the div above it when borders are removed, although they do when borders are added. There seems to be an i ...

The jQuery Deferred feature on Ajax is failing to properly pass the array in the data option as an array, instead converting

I am facing an issue in my application where I want to use jQuery deferred to handle Ajax success and error uniformly from a central location. It works perfectly fine when I pass strings in the data option, but when I try to pass an array, it gets sent as ...

Creating custom outlines for CSS shapes

Exploring the world of CSS shapes has left me wondering - is it possible to give them solid, dotted, or dashed borders? I came across some examples of shapes that caught my eye (shapes), but making them stand out with different border styles posed a challe ...

What is the best way to transmit data via $router.push in Vue.js?

I am currently working on implementing an alert component for a CRUD application using Vue.js. My goal is to pass a message to another component once data has been successfully saved. I attempted to achieve this by passing the data through $router.push lik ...

Customizing Magnific Popup: Changing showCloseBtn and closeOnBgClick settings during display

Is there a way to customize the behavior of an open instance of a magnific popup? I want to have different settings for when the popup is closable and when it should be prevented from closing. It appears that these options are only available during initial ...

Incorporate a JavaScript message using C# code in the backend

I am looking for a code snippet to execute a JavaScript function called recordInserted() that displays an alert, within the add_Click method in my code-behind file. Here is the relevant section of my code: protected void add_Click(object sender, EventArgs ...

What are the steps for implementing pytesseract on a node.js server?

While working on my node.js server, I encountered an issue when using child-process to send an image to a python script. Although I can successfully read the image in the python script, I encounter an error when attempting to convert it to text using pytes ...

An error occurred while attempting to run the npm installation command

When trying to run the npm install command, I keep encountering this error: npm ERR! code 1 npm ERR! path /Users/alex/Documents/serviceName/node_modules/platform-tracer/node_modules/ls-trace npm ERR! command failed npm ERR! command sh -c node scripts/post_ ...

Sending back an Observable from a rejected Promise

I am currently investigating whether I can convert a Promise rejection into a typed Observable. Within my login component, I have a function that looks like this... login() { const login$ = this.authenticationService.login(this.loginForm.value) login$ ...