Learn how to manipulate the DOM by dynamically creating elements and aligning them on the same line

Providing some context for my page:

The section I have always contains a single input field. Below that, there is an "add" button which generates additional input fields. Since only one field is required on the screen, the following fields come with a "delete" button to remove the corresponding input field.

Check out this screenshot:

On the screenshot, you can see that the buttons with "-" are positioned after each input box. I need them to be aligned just to the right. I've attempted using display:inline on the "-"/delete button without success.

Sample Code:

function addField(count) {

    if (count<=4){
    count++;
    var id = "tag"+count;
    var newField = document.createElement("input");
    newField.setAttribute('type', 'text');
    newField.setAttribute('class', 'field');
    newField.setAttribute('id', id);

    var place = document.getElementById("tags");
    inputContainer.appendChild(newField);

    var removeId = "remove"+count;
    var remove = document.createElement("input");
    remove.setAttribute("type", "button");
    remove.setAttribute("value", "-");
    remove.setAttribute('class', 'remove');
    remove.setAttribute('id', removeId);

    remove.onclick = function () { 
        var targetInput = document.getElementById(id);
        var targetRemove = document.getElementById(removeId);
        targetInput.remove();
        targetRemove.remove();
     };

    inputContainer.appendChild(remove);
    return count;
    } 
}

Answer №1

You are presented with two choices:

  1. Enclose each row within its own <div>:

    <div><input type="text"><button>-</button></div>
    
  2. Add a <br> tag after each row:

    <input type="text"><button>-</button><br>
    

If you choose the first option, you will need to modify your JavaScript code to create the <div> tags first and then insert the input elements into them. With the second option, you can simply append all the elements as you generate them, including the <br> tags.


var div = document.createElement('div');
var input = document.createElement('input');
var button = document.createElement('button');

button.innerText = '-';

div.appendChild(input);
div.appendChild(button);
inputContainer.appendChild(div);

View a demonstration showcasing both examples: http://jsfiddle.net/7UaAh/1/

Answer №2

After analyzing your issue, I have devised a solution that may be helpful :

JS Fiddle Demo

HTML:

<div id="containerInput">
<div class="inputFieldWithBtn">
<input type="text" />
<button onclick="addInput();">+</button>
</div>
</div>

JS:

var identifier = 1;
function addInput()
{
    var itemIdentifier = 'element'+identifier;
    document.getElementById("containerInput").innerHTML += "<div id='"+itemIdentifier+"' class='inputFieldWithBtn'><input type='text' /><button onclick='clearContent("+itemIdentifier+")'>-</button></div>";
    identifier++;
}

function clearContent(_itemIdentifier)
{
    document.getElementById(_itemIdentifier.id).remove();
}

I trust this information proves useful.

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

What is the best way to replicate the orange outline when focused?

I am in the process of creating a series of divs that can be navigated by the user using the tab key. I would like to incorporate the standard orange focus outline for these elements. Is there anyone who can provide guidance on how to achieve this? I unde ...

Tips for safeguarding the security of my PHP API when accessed through Ajax using OAuth2

I've developed a cross-origin ajax application that utilizes some personal APIs I created. Now, I'm looking to enhance the security measures so only my application has access to the API. After researching, I came across OAuth2 at OAuth2. I foll ...

Step-by-step guide on integrating node.js and MySQL to store data from an online form in a database

Currently, I am attempting to insert data into a MySQL database using node.js by clicking the submit button. However, an error message has appeared and despite understanding it somewhat, I am unsure of how to proceed. Any assistance would be greatly apprec ...

What is the best method for implementing click functionality to elements that share a common class using only pure JavaScript

I am struggling to figure out how to select specific elements with the same classes using only pure JavaScript (no jQuery). For example: <div class="item"> <div class="divInside"></div> </div> <div class= ...

The function of the 'Class' attribute is not functioning properly

I am currently working on a search field with a drop-down menu that determines the type of data being searched. This, in turn, dictates the input type for the search field. For example, if I am searching by "name" or "ID number", the input type is set to t ...

Implementing dual pagination components in Vue JS for dynamic updates on click

Having two pagination components on a single page is convenient for users to navigate without scrolling too much. One component is placed at the top and the other at the bottom. The issue arises when I switch to page 2 using the top component, as the bott ...

Update angular table input values

I am currently facing an issue with ng-table while displaying my data. I noticed that when I enter data on the first page and then navigate to the second page, the values from the first page get cleared. Is there a way to retain the previously entered val ...

Utilizing ng-click within a tooltip

I've implemented Angular Bootstrap UI and successfully added a tooltip to my project. Snippet of HTML: <div ng-app="helloApp"> <div ng-controller="helloCtrl as hello"> <a tooltip-trigger="click" tooltip-placement="bottom" uib-t ...

Retrieving Information with the Fetch API in Node.js and Storing it in a MongoDB Database

I'm a newcomer to mongooseDB and am currently experimenting with inserting data from an API into the database. It successfully creates the Collection, but unfortunately it is not generating the documents. Any suggestions on what I might be doing incor ...

Access all areas with unlimited password possibilities on our sign-in page

I have set up a xamp-based web server and installed an attendance system. I have 10 users registered to log in individually and enter their attendance. However, the issue is that on the login page, any password entered is accepted without showing an error ...

Personalized style for text overflow property

The application is created using Angular. Within a component, we have a div containing some text: <div>abcdefghijklmnop<div> Depending on the screen size, the text should either be fully displayed or clipped. I discovered the property 'te ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...

Establishing specific categories for a universal element

I have been working on creating an input component that functions as a custom select for enums in my application. I have tried defining them for different types using concise one-liners but have run into various typing issues. Here is what I have so far: ...

Verify if the specified value is present in the dropdown using AngularJS

Utilizing AngularJS, I have implemented an input field with autocomplete functionality. The autocomplete feature pulls data from a JSON file and displays it in a dropdown table format. Users are able to filter the results and select a value from the dropdo ...

Arranging mat-checkboxes in a vertical stack inside a mat-grid-tile component of a mat-grid-list

I'm looking to create a grid list with 2 columns, each containing 2 checkboxes stacked vertically. While I found this helpful question, it still involves a lot of nested divs. Is there a cleaner way to achieve this layout? Here's how I currentl ...

Guide on implementing a looping settimeout function on a sliding page to dynamically load an HTML template within the Framework 7 framework

My current setup involves using Framework7 (framework7.io). The code below functions correctly on the main view page, utilizing a looping settimeout to refresh signups.html every second: <script type=“text/javascript” src=“code.jquery.com/jquery- ...

Exploring the Difference Between $onChanges and $onInit in Angular Components

What sets apart the use of Controller1 compared to Controller2? angular.module('app', []) .component('foo', { templateUrl: 'foo.html', bindings: { user: '<', }, controller: Controller1, ...

The AngularJS framework is failing to disable the autocomplete feature for the input field with a password type

I have attempted to disable auto-complete for the password input, but it doesn't seem to be working. Below is a sample of my code: <form name="testfrm" ng-submit="test(testfrm)" autocomplete="off"> <input type="password" id="passwor ...

Display the content of an md-dialog with a scroll bar

I am experiencing a problem with printing a long report created using md-list displayed in a md-dialog. When I attempt to print it, only the section that is currently visible on the screen gets printed instead of the entire length of the md-list. I have at ...

Perform a JSON POST request from an HTML script to a Node.JS application hosted on a different domain

In an attempt to send string data via a post json request using JavaScript within an .erb.html file, I am facing the challenge of sending it to a node.js app on another domain that uses express to handle incoming requests. After researching online, I have ...