implement a user input field within a div using JavaScript

I have created a lightbox in my HTML page with the following structure:

<div id="container">
    <input type="text" id="user_1" name="user_1" value="user_1"/><br>
    <input type="text" id="user_2" name="user_2" value="user_2"/><br>
    <input type="text" id="user_3" name="user_3" value="user_3"/><br>
    <label onclick="add_input();"><img alt="add_other" src="add.png"></label>
</div>

When the image inside the lightbox is clicked, I want to add and display a new input field. To achieve this, I have written the following JavaScript function:

function add_input(){
        var div = document.getElementById('container');
        var input = '<input style="width:300px;" type="text" id="user" name="user" value=""/>'
        div.innerHTML+= input;
    }

Although the input field gets added upon clicking the image, it appears outside the lightbox because the CSS of #container has set height to auto. Is there a different approach that can be used to keep the input field within the lightbox?

Answer №1

It seems like there may be a CSS issue with the input being placed inside the container, possibly due to a height restriction on an ancestor element.

Regarding your function, it's not recommended to use .innerHTML += "<input...>", as it can have destructive effects, especially with input elements.

Instead, consider creating DOM elements using creation methods like this:

function add_input(){
    var input = document.createElement("input")
    input.style="width:300px;" 
    input.id = input.name = "user";
    document.getElementById('container').appendChild(input);
}

If you prefer inserting HTML markup directly, you can do so without destroying and rebuilding existing content by using .insertAdjacentHTML():

function add_input(){
    var div = document.getElementById('container');
    var input = '<input style="width:300px;" type="text" id="user" name="user" value=""/>'
    div.insertAdjacentHTML("beforeend", input);
}

Just keep in mind that you may need a shim for old versions of Firefox.

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

Learn the process of utilizing signed URLs in conjunction with ReactJS to securely store files in AWS

I am currently working on a form where I need to attach images along with regular text inputs in order to submit data to my MongoDB. Here is the code for my post creation function: const [postData, setPostData] = useState({ text: '', i ...

Database query not appearing on node.js route

As a newcomer to javascript and nodejs, I have encountered an issue that I'm hoping to get some clarification on. I am currently working on a simple API and facing difficulties in understanding why a certain behavior is occurring in my code. app.get( ...

The error message "Multiple children error occurs when an empty link in Next.js

Is there a way to successfully implement a <Link /> element without any content inside it in my application? Surprisingly, when I don't provide any content, I encounter the multiple children error, even though the opposite seems to be happening. ...

creating a Vue app using Node results in an HTML page with no content due to syntax errors

After creating a VueJs page using the CLI, I wanted to share it with others who might not have Vue CLI or Node installed. Just like opening .html files in a browser, I tried to open the index.html file after building it. However, when I opened the file, a ...

What is the best method in Selenium IDE for tracking an element based on its value?

While testing a website with Selenium IDE, I encountered an issue with the way elements are identified. The site utilizes something called "wickets" that change the ID of elements randomly, making it difficult for Selenium to record actions on certain elem ...

Retrieving a nested sub collection within each object of a Firebase collection in a React application

I'm working on a React app that retrieves elements from Firebase and displays them in a grid. I want to show a list of subcollection elements for each grid line, but I'm unsure how to achieve this. Here's where I currently stand: export defa ...

I have experimented with both POST and GET methods in Node.js, exploring a variety

After creating a login page with a GET form, the server code includes: app.use(express.static(path.join(__dirname, 'public'))); I am facing an issue trying to implement a POST request. When I use "POST", it gives me a "CANNOT / PO ...

The functionality of the TURF booleanwithin feature is malfunctioning and not producing the

Currently, I am working on validating whether a polygon is completely within another polygon. However, there are cases where more complex polygons should return false, but turf interprets them as valid. If you'd like to see the sandbox, click here: ...

What is the process of extracting a utility function from a helper file on a node.js server?

I'm facing a challenge with my node/express server where I need to access a function from a helper file in my app.js. The function in the helper file looks like this: CC.CURRENT.unpack = function(value) { var valuesArray = value.split("~"); ...

How to define an index signature in Typescript that includes both mandatory and optional keys

I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional. Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution. At present, my construc ...

Hey there everyone, I was wondering how to send both single and multiple values to a database using JavaScript and JSON endpoints with a Spring Web API

{ "id": 178, "stockin_date": "2022-11-15T08:18:54.252+00:00", "effective_date": null, "expired_date": null, "create_date": null, "update_date&q ...

Verify if the input field is devoid of any content or not

I am planning to create a validation form using Vanilla JavaScript. However, I have encountered an issue. Specifically, I want to validate the 'entername' field first. If the user does not enter any letters in it, I would like to display the mess ...

How would you utilize jQuery to access the "option" array of a select control with the attribute of multiple=true by utilizing the find() method?

When using jquery, I am attempting to access selected items from a select control that has multiple=true. My goal is to reference them by name criteria and then iterate through the list. Below is my current code snippet: var currentRow = $(this); // sele ...

Tips for stopping variables from leaking in JavaScript

I'm currently working on a JavaScript code for my task manager website. Each page has its own JS file, but I've noticed that the data saved in one file seems to leak over to the others. How can I contain these variables so that tasks don't s ...

Having trouble retrieving data from getters in the Vue store while inside a template

Within my component, I have set up computed properties that are supposed to display text for blopp and blipp. However, while blopp is working fine, blipp is not showing anything. The end goal is to have blipp generate a list of strings from the store state ...

Utilize text-to-speech technology to convert the output results into

Looking for a way to live stream a text to speech message triggered by a button press on your website? Unsure how to accomplish this with Node.js and generate the file after the button press? Let's explore some solutions together. ...

Finding distinct values in a multidimensional array using JavaScript

When working with JavaScript, I created a multidimensional array using the following code: result.each(function(i, element){ init.push({ label : $(this).data('label'), value : $(this).val(), }); }); The resulting array in ...

The next and previous buttons on the JQuery UI datepicker are related to only one ancestor. When using $(e.target).parents(), it will only return a

Unfortunately, my reputation isn't high enough to post my own answer just yet. However, I wanted to share it before wasting more people's time: I finally figured out why I was not getting all the expected ancestors: The JQuery datepicker actuall ...

An insightful guide on effectively binding form controls in Angular using reactive forms, exploring the nuances of formControlName and ngModel

Here is the code snippet: list.component.html <form nz-form [formGroup]="taskFormGroup" (submit)="saveFormData()"> <div nz-row *ngFor="let remark of checklist> <div nz-col nzXXl="12" *ngFor="let task of remark.tasks" styl ...

Hold on for the completion of Angular's DOM update

I am facing an issue where I need to connect the bootstrap datepicker to an input field generated by AngularJS. The typical approach of using jQuery to attach the datepicker doesn't work as expected because the element is not yet available: $(functi ...