20 Jan 2013

Adding Form Controls Dynamically with jQuery

Let's have a look at an example, where we use a link to add file upload controls to our form.
Initially, we can create our html form thus:
<form id="uploadform" method="post" action="anotherpage.php" enctype="multipart/form-data">
    <p><a href="#" id="addupload">Add another upload control</a></p>
    <label>Upload an image:</label> <input type="file" name="file[]" class="imageupload" /> <br />
    <input type="submit" value="Upload" name="submit" id="submit" />
</form>
The resulting form should look like this - note no CSS/styling so it looks horrible! Also using <br /> tags in forms isn't the best way to do it, but this is only an example.
If we now add a very simple piece of jQuery-javascript, we should be able to add controls easily:
<form id="uploadform" method="post" action="anotherpage.php" enctype="multipart/form-data">
    <p><a href="#" id="addupload">Add another upload control</a></p>
    <label>Upload an image:</label> <input type="file" name="file[]" class="imageupload" /><br />
    <input type="submit" value="Upload" name="submit" id="submit" />
</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(function(){
    $('#addupload').click(function(){
        var addControl = '<label>Upload an image:</label>';
        addControl += ' <input type="file" name="file[]" class="imageupload" /><br />';
        $('#submit').before(addControl); 
    });
});
</script>
You'll notice that the submit button (#submit) acts as a hook so we can use the .before() method.
If you click the link twice and browse for files, you should see something like the following:
NB: this is all well and good if you just need basic form functionality, but if you have javascript running off these controls, then the newly added controls will not function as expected. This is because they were created after the page was fully loaded. Don't fret, there is a way around this limitation. I will create another post looking at the .on() method.

4 comments: