Reputation: 744
Does someone know how to change the value of an array if the user clicks a checkbox?
Basically I have 3 text fields (name,date,place) and a checkbox (favorite). If the user inserts something and clicks the button, you will see the data in the table bellow and the data will also saved in an array.
My question is: How can I change the value "true"(is checked) into "false" , so the user has the option of de- and activating an "person" as a favourite ?
Upvotes: 0
Views: 52
Reputation: 29683
Just add checked attribute
to your checkbox
based on your favorite
boolean
value. Read the comments in javascript
section
window.onload = function() {
var allArtists = [];
$('#submit').click(function() {
var $rowTemplate = $('<tr><td data-id="id"></td><td data-id="name"></td><td data-id="geburtsort"></td><td data-id="geburtsdatum"></td><td data-id="favorite"></td></tr>');
var artistName = $("#name").val();
var ort = $("#ort").val();
var datum = $("#datum").val();
var favourite = $("[name=Favorit]").is(':checked');
allArtists.push([artistName, ort, datum]);
var rowId = allArtists.length;
$rowTemplate.find('[data-id=id]').text(rowId);
$rowTemplate.find('[data-id=name]').text(artistName);
$rowTemplate.find('[data-id=geburtsort]').text(ort);
$rowTemplate.find('[data-id=geburtsdatum]').text(datum);
var checked = favourite ? "checked" : "";
//if favourite==true then add checked value to checked variable otherwise keep it empty
$rowTemplate.find('[data-id=favorite]').html('<div class="chkText">'+favourite+'</div>').append($('<input type="checkbox" id="fave" ' + checked + '>'));
//just assign it as property to your checkbox.
$("#table tbody").append($rowTemplate);
});
};
$("#table").on('change','input[type=checkbox]',function(){
$(this).prev('div').text($(this).is(":checked"));
});
.chkText{
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Künstler hinzufügen</h1>
<form id="send">
<label>Name des Künstlers</label>
<br>
<input id="name" type="text" placeholder="Name des Künstlers" />
<br>
<label>Ort</label>
<br>
<input id="ort" type="text" placeholder="Woher stammt der Künstler" />
<br>
<label>Geburtsdatum</label>
<br>
<input id="datum" type="text" placeholder="Wann ist der Künstler geboren?" />
<br>
</form>
<p>
<input type="checkbox" name="Favorit" value="Favorit">Favorit
<p>
<input type="button" id="submit" name="senden" value="Senden">
<table id="table">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Geburtsort</th>
<th>Geburtsdatum</th>
<th>Favorit</th>
</tr>
</tbody>
</table>
Please make a note that you are creating duplicate id
here in your dynamic html
generation, while adding rows
to table
where as it is not allowed to have duplicate id
in html
Upvotes: 1