JSFiddle - React, Tailwind, and code Playground
HTML
<div id="references"></div>
<div id="refs-sample" style="display: none;">
<button class="btn btn-warning btn-sm" rel="reference" data-ref-id="{ref_int}" style="margin-bottom: 25px;" title="{ref_url}">Source {ref_int}</button>
</div>
<div id="removeReference" style="display: none;"> <a href="{ref_int}" title="Remove Reference"><span class="glyphicon glyphicon-remove"></span></a>
</div>
<div class="col-sm-5">
<input type="text" name="reference" size="30" />
</div>
<div class="col-sm-7">
<button class="btn btn-primary btn-sm" id="addReference">Add Source</button>
</div>
<label>Type a Valid URL</label>
<input type="hidden" name="references" value="" />
JavaScript
(function ($) {
$.fn.extend({
references: function (options) {
var defaults = {
sample_div: '#sample-ref',
remove_button: '#removereference',
update_div: '#references',
add_button: '#addReference',
hidden_input: 'input[name="references"]'
};
options = $.extend(defaults, options);
var count = 0;
function addReference(e) {
var new_ref = $('[name="reference"]').val();
var existing = $(options.hidden_input).val();
if (new_ref.length > 0) {
existing = existing.split(',');
existing.push(new_ref);
var replacements = {
ref_int: existing.length,
ref_url: new_ref
};
var sample = $(options.sample_div).html();
$.each(replacements, function (index, value) {
sample = sample.replace(/{index}/g, value);
});
$(options.update_div).append(sample);
$('[name="reference"]').val('');
}
}
function init(element, options) {
console.log('refreences init called');
$(options.add_button).on('click', function (e) {
addReference(e);
e.preventDefault();
return false;
});
$('[rel="reference"]').hover(function () {
$(this).text($(options.remove_button).html());
});
}
return $(this).each(function () {
init(this, options);
});
}
});
})(jQuery);
$('#references').references({
sample_div: '#refs-sample',
remove_button: '#removeReference',
update_div: '#references',
...