JSFiddle - React, Tailwind, and code Playground
by jeffreydev
HTML
<form class="cms-form" action="" method="post">
<table width="800">
<tr>
<td width="30%">Name:</td>
<td><input type="text" name="name" class="cms-input-text" maxlength="127" required="required" /></td>
</tr>
<tr>
<td width="30%">Something else:</td>
<td><input type="text" name="something" class="cms-input-text" maxlength="127" required="required" /></td>
</tr>
<tr>
<td>Image:</td>
<td>
<textarea name="icon" class="cms-input-file" data-file-resource="images" data-options="{"min":1,"max":3}" required="required">/location-to-image.png
</textarea>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
CSS
.cms-hide-element
{
width: 0px;
height: 0px;
}
JavaScript
$('.cms-input-file').each(function () {
var $element = $(this);
var options = $element.data('options');
$element.after('<ul class="cms-input-file-list"><li class="cms-input-file-add">Add</li></ul>');
var $list = $element.next();
var files = $element.val().split(/\n\r|\r|\n/);
// hide the actual element
$element.wrap('<div class="cms-hide-element"/>');
// for each file that is already in it create a list item
$(files).each(function () {
$list.prepend('<li class="cms-input-file-item">'+this+'</li>');
});
// hide the textarea inside a block element which has a height and width of 0px and overflow hidden.
$element.wrap('.cms-hide-element');
$list.on('update', function () {
var error = false;
if($(this).find('.cms-input-file-item').length < options.min)
{
$element.get(0).setCustomValidity('Minimum: '+options.min);
error = true;
}
if($(this).find('.cms-input-file-item').length > options.max)
{
$element.get(0).setCustomValidity('Maximum: '+options.max);
error = true;
}
if(!error)
{
$element.get(0).setCustomValidity('');
}
});
$list.trigger('update');
});
$('.cms-input-file-add').on('click', function () {
$(this)
.parent()
.prepend('<li class="cms-input-file-item">/location-to-new-file.jpg</li>')
.trigger('update');
// also add to textarea ($element) so data gets submitted on actual submit
});