Reputation: 311
I am new to Javascrip html and css. Well I wanted to practice a bit. So I created a button. When I clicked on it a new small card appeared on the screen. That works totally fine. Well now I am trying to do a function that when I click on a created card it opens two input fields with a save button and a cancel button. I know how to programm the save and cancel button but I don't know how I can make them in a created card by clicking on the created card. Does somebody of you know how I can do this with Js? I really got no idea how I can do it with js. This is my Code:
<button class="plus">
<div class="item">
<p>+</p>
</div>
<form name="theform">
<input class="input-feld" type="text"><br>
<input class="input-feld "type="text"><br>
<input type="button" onClick="new Person()" value="Speichern">
<input type="button" onClick="new Person()" value="Abbrechen">
</form>
</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Js:
$(document).ready(function () {
$("button.plus").on("click", function () {
$("div:last").after("<div class=item><p>Title</p></div>");
});
});
Upvotes: 0
Views: 3002
Reputation: 19007
Your current code looks messed up because you have the form html inside the button tag, Separate the button html, your card html.
Below is a working example.
Idea is
Have a card prototype which you can clone
and add to body to create new cards
Have a hidden form inside each card which is shown only when you click on the card
Event Delegation
to trigger click events on dynamically added cards.$(document).ready(function () {
$("button.plus").on("click", function () {
var newCard = $('#cardPrototype').clone(true); // clone the card html
$(newCard).css('display','block').removeAttr('id');
$('#newCardHolder').append(newCard);
});
$('body').on('click','.card',function(){ // event delegation syntax
$(this).find('form').show();
});
});
.card{
background-color:yellow;
padding:5px;
width:200px;
margin-bottom:20px;
height:150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="plus">
<div class="item">
<p>+</p>
</div>
</button>
<div id="newCardHolder">
</div>
<div id="cardPrototype" class="card" style="display:none;">
<span> This is a Random Card</span>
<form name="theform" style="display:none;">
<input class="input-feld" type="text">
<br>
<input class="input-feld " type="text">
<br>
<input type="button" onClick="new Person()" value="Speichern">
<input type="button" onClick="new Person()" value="Abbrechen">
</form>
</div>
Hope this is useful.
Upvotes: 1