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.