I have a function that I want to use it more than once, but i use double code for that. How can I extend the function for other input fields. THe function is adding a field in a form till maximul of input fields is reached. I want to use to other input fields in the same app without copy paste the code. Here is my function and what I tried to do:
function addTFS (maxField, addButton, link, fieldHTML){
$(document).ready(function addt() {
// Input fields increment limitation
var maxField = 5;
// Add button selector
var addButton = $(".add_button");
// Input field wrapper
var link = $("#link_tbl");
// New input field html
var fieldHTML =
'<tr><td><label for="tfs_link"><i class="fas fa-minus-circle remove_button"></i></label><input type="url" name="tfs" required/></td></tr>';
// Initial field counter is 1
var x = 1;
// Once add button is clicked
$(addButton).click(function () {
// Check maximum number of input fields
if (x < maxField) {
// Increment field counter
x++;
// Add field html
$(link).append(fieldHTML);
}
});
// Once remove button is clicked
$(link).on("click", ".remove_button", function (e) {
e.preventDefault();
// Remove field html
$(this).closest("tr").remove();
// Decrement field counter
x--;
});
});
};
addTFS ();
I don't understand what you exactly mean by extending function. Do you want to add a decorator as we do in python?
But here is my approach to solving your problem, you can just call the base function into your wrapper like this:
//Base function
function square(input) {
return input * input;
}
//Extended function
function modify(input) {
return square(input) - 2;
}
console.log(modify(5));