Addy2311 Addy2311 - 1 year ago 53
HTML Question

How to de- and activate a checkbox in a table and also in the array

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 ?

Answer Source

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;

    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);

<script src=""></script>
<h1>Künstler hinzufügen</h1>
<form id="send">
  <label>Name des Künstlers</label>
  <input id="name" type="text" placeholder="Name des Künstlers" />

  <input id="ort" type="text" placeholder="Woher stammt der Künstler" />

  <input id="datum" type="text" placeholder="Wann ist der Künstler geboren?" />

  <input type="checkbox" name="Favorit" value="Favorit">Favorit

    <input type="button" id="submit" name="senden" value="Senden">
    <table id="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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download