Retrieve all the values from a form with identical names using angularjs

I have a form with two text boxes, one for entering a name and the other for an email. There is also a button to add a new row with these two text boxes. I am attempting to retrieve the values of Name and Email using AngularJS, but I am new to Angular.

Below is my code snippet:

JavaScript

function addrow() {
    var table = document.getElementById("emp");
    var row = table.insertRow(2);
    var name = row.insertCell(0);
    var email = row.insertCell(1);
    name.innerHTML = "<input id='Name' type='text' value='' name='ename' ng-model='data.ename'>";
    email.innerHTML = "<input type='text' value='' name='Email' id='email' ng-model='data.email'>";
}

HTML

    <form name="employees" ng-submit="emp()">
    <table id="emp">
        <tr>
            <td>Employee Name
            </td>
            <td>Employee Email
            </td>
        </tr>
        <tr>
            <td>
                <input type="text" id="Name" name="ename" ng-model="data.ename" />
            </td>
            <td>
                <input type="email" id="email" name="email" ng-model="data.email" />
            </td>
        </tr>
    </table>
<button class="btn btn-primary" onclick="addrow();">Add new</button>
        <input type="submit" class="btn" />
    </form>

AngularJS

var model1Controller = ["$scope", "$http", function ($scope, $http) {
$scope.data = [];

$scope.emp = function () {
    alert($scope.data.ename);
    }
}]

Answer №1

If you only require some entries to be editable, you can implement @Brian's method. However, if you wish for all of them to be editable, you can simply employ ng-repeat to encapsulate the input fields:

<form name="employees" ng-submit="emp()">
    <table id="emp">
        <tr>
            <td>Employee Name</td>
            <td>Employee Email</td>
        </tr>
        <tr ng-repeat="emp in employees">
            <td><input ng-model="emp.ename" /></td>
            <td><input type="email" ng-model="emp.email" /></td>
        </tr>
    </table>
    <button class="btn btn-primary" ng-click="addrow()">Add new</button>
    <input type="submit" class="btn" />
</form>

 

var model1Controller = ["$scope", "$http", function ($scope, $http) {
    var employees = $scope.employees = [];
    $scope.addrow = function() { employees.push({ /* nothing needed here */ }); };
    $scope.emp = function () {
        console.log(employees);
    }
};

Answer №2

To optimize your code, consider moving your addrow() function from a separate file into your controller and using the ng-repeat filter instead. Check out the ngRepeatDocs for more information.

The main purpose of Angular in this scenario is to handle element and DOM binding automatically, eliminating the need to manually scrape values and insert HTML. If you're unsure whether your submit action is meant to add a person to the form or submit all form data (since you mentioned a button that isn't visible in your code), here's a guideline to display every employee in your data model and add them to the form upon submission:

<form name="employees" ng-submit="addrow()" ng-controller="model1Ctrl">
<table id="emp">
    <tr ng-repeat="emp in data">
        <td> {{ emp.ename }}
        </td>
        <td>{{ emp.email }}
        </td>
    </tr>
    <tr >
        <td>
            <input type="text" id="Name" name="ename" ng-model="ename" />
        </td>
        <td>
            <input type="email" id="email" name="email" ng-model="email" />
        </td>
    </tr>
</table>

Your Controller:

var model1Ctrl = ['$http','$scope',function($http,$scope){

    $scope.data = [];

    $scope.addrow = function () {
       var newEmp = {
             ename: $scope.ename,
             email: $scope.email
           }

      $scope.data.push(newEmp); //adds the new employee as an object into your data set
      // which ng-repeat will automatically know about, and display in your table

       //clear the scope of your inputs so they can be used again
       $scope.ename = '';
       $scope.email = '';

    }
}]

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

The vertical tabs in JQueryUI lost their functionality when a few seemingly unrelated CSS styles were added

Check out the JsFiddle demo here I embarked on a mission to craft JQueryUI Vertical tabs by following the guidance provided in this example. The source code within the aforementioned link contains specific CSS styles: .ui-tabs-vertical { width: 55em; } ...

Create a basic cache within an AngularJS service to store data retrieved from HTTP requests, ensuring that the cache returns an object

Looking to implement a simple caching mechanism in an AngularJS service for data retrieved from HTTP requests. The goal is to always reference the same object to avoid duplicating requests. Below is an example code snippet showcasing the issue at hand. Li ...

injecting javascript dynamically using jquery

I am attempting to conditionally load a script in the case that the browser being used is IE8. To achieve this, I have employed jQuery's .getScript function as it allows me to execute certain actions after the script has been loaded. The issue lies in ...

Utilize Google Maps API to showcase draggable marker Latitude and Longitude in distinct TextFields

I am currently utilizing the Google Maps example for Draggable markers. My objective is to showcase the latitude and longitude values within separate TextFields, where the values dynamically change as I drag the marker. Once the user stops dragging the mar ...

Testing Restful API Endpoints and Code Coverage with Node.js using Mocha

My time in Istanbul has been delightful, and I've been dabbling in different Node.js coverage libraries. However, I'm facing a challenge. Most of my unit tests involve making HTTP calls to my API, like this: it('should update the custom ...

What is the best way to design a Global Navigation menu for websites?

For example, I am looking to integrate a Navigation menu into my website using just one file. I have considered using PHP or creating an HTML frame, but I am wondering what the current industry standard is for professionals. Any insights? ...

Modifying dynamic input fields based on the selected input field type

Seeking advice on a challenge I'm facing while testing a website. My task is to mask input fields in screenshots after executing tests because we share data with other teams. I've tried using JS before the script by changing the input type to &ap ...

"Encountering a 'Cannot GET' error message while utilizing Rest API in Node.js

Currently, I am developing a project using nodejs along with the expressjs framework. My focus right now is on setting up and running a "Rest Api," but I seem to be encountering an error message that reads: Cannot GET /published Let me share my routes fil ...

What could be causing my CSS transitions to fail when using jQuery to add classes?

I'm currently working on a website and I'm facing an issue with the transition not functioning as expected. The problem persists even when the 7.css stylesheet is removed and interestingly, the transition works fine when using window:hover. My a ...

Having trouble getting the Next.js Image component to work with Tailwind CSS

Recently, I've been working on transitioning a React project to Next.js and encountered some issues with the next/Image component that seem to be causing some problems. <div className=" flex flex-col items-center p-5 sm:justify-center sm:pt-9 ...

Manipulate a JSON object with JavaScript

Struggling to find a solution on my own. In my hidden field, I have some JSON data stored. To retrieve this data, I'm using the following syntax: $(document).ready(function() { var data = $("#result").text(); var j = JSON.parse(data); j.my_item.to ...

Executing a Component function within an "inline-template" in VueJS

VueJS version 1.9.0 app.js require('./bootstrap'); window.Vue = require('vue'); Vue.component('mapbox', require('./components/mapbox.js')); const app = new Vue({ el: '#app' }); components/mapbox.js ...

The admin-ajax.php file in WordPress consistently fails to return any value other than

I developed a WordPress ajax plugin, but I am facing an issue where admin-ajax.php always returns 0 and the plugin doesn't work as expected. Here is the code I have implemented: add_action( 'wp_ajax_example_ajax_request', 'example_aja ...

Instructions for inserting an anchor tag into the middle of a <p> element utilizing document.createElement("p")

When generating elements dynamically with JavaScript using document.createElement("p"), I am looking to create a paragraph element <p></p> that includes an anchor tag in the middle, creating a clickable link within the text. I aim to use JavaS ...

How can I implement Jquery ajax calls in various JavaScript functions?

I'm encountering an issue with a particular function in my code function readComm(){ $.post("something.php", {read:"read"}, function(data){ retVal = $.trim(data).toString(); console.log(retVal); return retVal; }); } T ...

What is the mechanism by which a Node.js server handles incoming requests?

Suppose I am working with this code snippet. I am using ExpressJS, although the server part doesn't seem much different from vanilla Node.js. var express=require('express'); var settings=JSON.parse(fs.readFileSync('settings.json' ...

Using SASS variables in JavaScript: A guide

My JavaScript file contains a list of color variables as an Object. export const colors = [ { colorVariable: "$ui-background" }, { colorVariable: "$ui-01" }, { colorVariable: "$ui-02" }, ... ] The Object above is derived from a scss file whic ...

Retrieving a value attribute from the isolated controller of a directive

I have a directive that reads and writes attributes, but I'm having trouble getting it to work as expected. The issue seems to be with the controller inside main-directive.js, which is empty, while the actual action is happening in the isolated direct ...

The repetition of the react nodejs page load occurs when the get method is utilized

I've successfully set up a page and function for loading the customer list. However, I'm facing an issue where adding the get method to my code results in it being called every time information is received from the URL and the page is rendered. i ...

Angular: How can objects be efficiently stored in a service for display in the view and use of CRUD functions to interact with the server?

I am exploring different options for creating a service that retrieves relational data from the server. I have two potential approaches in mind, but I am having trouble deciding between them. The first option involves returning the data as a multidimensio ...