Created
October 25, 2021 17:52
-
-
Save Da9el00/a0577b046b79d82c9a0d1663301bf3d8 to your computer and use it in GitHub Desktop.
Web Development: JQuery - add and remove components from list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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