Skip to content

Instantly share code, notes, and snippets.

@Da9el00
Created October 25, 2021 17:52
Show Gist options
  • Save Da9el00/a0577b046b79d82c9a0d1663301bf3d8 to your computer and use it in GitHub Desktop.
Save Da9el00/a0577b046b79d82c9a0d1663301bf3d8 to your computer and use it in GitHub Desktop.
Web Development: JQuery - add and remove components from list
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="list.js"></script>
<title>Document</title>
</head>
<body>
<div class="fruits">
<label>Fruits</label>
<div class="inputs">
<div class="fruit">
<input type="text" name="fruit" class="inputForm" />
<button class="remove" type="button" disabled="disabled">
Remove
</button>
</div>
</div>
<button type="button" class="add">Add</button>
</div>
</body>
</html>
$(document).ready(function () {
removefruitEvent();
addfruitEvent();
});
function addfruitEvent() {
$(".add").on('click', function() {
let fruit = $(".fruit").first().clone();
fruit.children("input").val('');
fruit.appendTo(".inputs");
toggleRemoveButton();
});
}
function removefruitEvent() {
$(".fruits").on('click', '.remove', function () {
$(this).parent().remove();
toggleRemoveButton();
});
}
function toggleRemoveButton(){
if($('.fruit').length > 1)
$('.fruit button').prop("disabled",false);
else
$('.fruit button').prop("disabled",true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment