Duplicate CSS designed file upload buttons

I have used CSS to style an input type file. Whenever I click on a plus button, it duplicates the input field. However, this duplication only visually happens with an unstyled upload button.

Hint: To replace the standard button with a styled one, I hide input[type="file"] using display:none. If I comment out this line of code, the cloned buttons become visible but without any styles applied.

Is there a way to clone CSS-styled buttons?

Check out this Fiddle link

Answer №1

If you want to replicate the label along with the input, follow these steps:

This code snippet duplicates the initial label and ensures it remains associated with its corresponding input:

$('label').first()
  .clone(true)
  .attr('for','img'+addcounter)
  .insertBefore($('#add'));

Fiddle

Answer №2

Revamp your HTML and duplicate the label effortlessly

When organizing your form elements, consider nesting input within label elements (w3.org, 17.9.1 The LABEL element). This approach makes it simpler to clone both elements simultaneously.

In the example below, I demonstrate this technique by assigning the id attribute to the parent label for easier referencing:

<label id="img1" class="uploadbutton">Choose File
    <input type="file" name="img1"/>
</label>

Note: Alternatively, you could leave the id attribute on the input and retrieve the label using jQuery's .parent() method if preferred. There are multiple approaches to achieve the same outcome.

This script efficiently clones the label along with its child elements in a single statement. Take note of the use of .find(input) to set attributes specifically on the nested input:

Example:

var addcounter = 2;
$("#add").on('click', function (e) {
    
    //Create a new select box
    $('#img1')
        .clone()
        .attr({
            id: "img" + addcounter
        })
        .insertBefore($('#add'))
        .find("input")
        .attr({
            name: "img" + addcounter
        });
    addcounter++;
});
td {
    width: 100px;
}

input[type='file'] {
    display: none;
}

#img2 {
    color: red;
}

#img3 {
    color: blue;
}

.uploadbutton {
    margin-right: 25px;
    padding: 6px 15px 6px 15px;
    cursor: default;
    color: #000;
    font-size: 15px;
    text-align: center;
    border: 1px solid #000;
    border-radius: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<label id="img1" class="uploadbutton">Choose File
    <input type="file" name="img1"/>
</label>

<button id="add">+</button>

Update:

An added advantage of nesting input within label is that the positioning of the parent label will also apply to the child input by default.

This allows for easy relative or absolute positioning of the input within the label, simplifying the process compared to managing independent sibling positions or adding unnecessary container elements for alignment purposes.

While not necessary for this particular demo, utilizing this benefit can enhance code efficiency and organization overall.

Answer №3

The input is not being styled, only the label is being styled and then cloned along with the input. You might want to consider cloning the label as well.

Answer №4

Consider modifying this resource for using input fields with the attribute type="file"

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 touch functionality on mobile browsers for both Android and iPhone devices?

Recently, while developing a web application, I ran into an issue on mobile browsers where the :active pseudo class wasn't functioning properly. I am currently utilizing CSS sprites and looking for guidance on how to simulate clicks for mobile browser ...

Exploring BreakPoints using gridlisttiles

Can Grid List Tile components be configured to occupy the entire screen on small devices using sm={12} lg={6}, but only half of the screen on larger devices? If not, is there a way to adjust the grid list layout to display fewer tiles per row on smaller ...

Spin a sphere within a semicircle using html and css

I have been working on a project to animate a ball inside a crescent shape using HTML and CSS. You can check out my codepen here. However, I am facing an issue where the ball is currently stuck at the top of the crescent. I would greatly appreciate any as ...

JQuery's document.ready function triggers prematurely on dynamically loaded HTML content

When loading dynamic content, I use the following method: $('#my-div').load('my.html'); The code inside my.html looks like this: <html> <head> </head> <body> <script> $(fu ...

What methods can I employ to utilize the name attribute for POST requests instead of the ID attribute in TinyMCE?

My inline TinyMCE form sends content to qry.php with the key "edit_me". I prefer the default behavior of sending content using the name attribute instead. <script type="text/javascript"> tinymce.init({ selector: '#edit_me', ...

Is it necessary to have aria-checked attribute on a physical checkbox?

I've come across many instances of customized checkboxes that utilize the 'aria-checked' attribute. However, I am curious if it is necessary to include this attribute when using input type=checkbox? Will the checkbox still be accessible to s ...

The tooltip feature for icon buttons within Material UI list items is not functioning properly as anticipated

Just starting out with Material UI and React, I've encountered a strange UI problem that I can't quite figure out. Hopefully someone here can help me identify what I did wrong. My Approach: I have a List in my code where each list item has butto ...

Updating input value using v-model in Vue.js does not reflect changes

I'm struggling with formatting numbers that I input in an HTML text box. I have a function that is supposed to format the number when I click out of the input box, but the updated value is not reflected in the v-model. The function is working correct ...

Efficiently align a Modal in React without the need to rewrite any code

In my application, I have a class called InventoryView that is responsible for displaying a list of stock items. The class is structured as follows: class InventoryView extends Component { ... render() { ... { consumableItemsArray.map((ro ...

iOS 10's autofocus feature experiencing difficulties in focusing on input

While using an application on my desktop or Android device, I have noticed that the input focus works perfectly fine. However, when I try to run the same application on iOS 10 Safari, the input focus does not seem to be working. It is worth noting that I ...

Displaying React components using Bootstrap in the navigation bar

I'm feeling a little stuck here. I'm currently working with React Bootstrap and the Navigation component. One of the routes in my application is the dashboard, which is only accessible after logging in. When a user navigates to the dashboard, I ...

Sending numerous HTML forms using a sole submit button through AJAX

On my website, I have a page named publish.php where users can input details for each image they upload. Each image has its own form, but only one form is displayed at a time in a tabbed layout when the user clicks on the corresponding thumbnail. I want to ...

Replacing a div with another div can be achieved in a single swap

My goal is to swap one div with another div upon clicking using the provided code. It functions properly for a single instance. However, the issue arises when the class appears multiple times, causing all instances to change due to sharing the same class n ...

Finding strikeout text within <s> or <del> tags can be identified by closely examining the HTML codes

The issue arises with the text that reads as follows: 316.6.1 Structures. Structures shall not be constructed This is represented in HTML as: <b> <s> <span style='font-size:10.0pt'>316.6.1 Structures</span> ...

How float elements can affect z-index through opacity

While troubleshooting the alignment of my floated images, I came across an unexpected issue related to opacity: http://jsfiddle.net/tshwbnLo/ It appears that when an element has opacity, it does not adhere to the usual behavior and instead overlaps the f ...

Swap the content of one div with another div using client-side code only

Currently, I am in the process of developing my personal website. To enhance user experience, I have implemented a vertical navigation bar on the left side of the page. My goal is to replace the content of a specific div with content from other HTML files ...

Tips on utilizing jQuery to trim and manipulate the current URL

Suppose the current URL I am working with is: https://example.com/test?id=W2FiY11beHl6XVsxMjNd . The data following ?id is [abc][xyz][123] and it is base64 encoded. My objective is to manipulate the current URL in such a way that the content displayed on ...

The content loses functionality once I add an overlay color to the background image div

I'm facing an issue with a div that has a background image, text, and a button in the center. Whenever I add an overlay color on top of the background image, the text and button seem to be disabled or unclickable. My goal is to ensure that the Read M ...

Instructions for applying a border style to a dynamically generated table using jQuery

I'm currently working on adding CSS to a table that is generated dynamically when a button is clicked. The function that is triggered on the click event includes the following jQuery code to create the dynamic rows: $("#employeDetail").append('& ...

Ensuring a full height div using CSS

I have encountered an issue and created a fiddle to help illustrate it: http://jsfiddle.net/XJpGT/ The challenge I am facing is ensuring that the height of the green box always remains at 100%, while also making sure that the green and orange boxes do not ...