user299028 user299028 - 6 months ago 12
Javascript Question

extracting html table with filled in radio buttons

I have table which contains several radio buttons. After selecting a radio button and clicking a button, the html of the table (including the filled in radio button) should be stored in a variable. However, only the html table is stored in a variable (i.e. there is no checked property in the stored html code).

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>

<form>
<table id="satisfaction_table">
<tr>
<th>Nr</th>
<th>Question</th>
<th>1 (Unacceptable)</th>
<th>2 (Poor)</th>
<th>3 (Average)</th>
<th>4 (Good)</th>
<th>5 (Excellent)</th>
</tr>

<tr>
<td>1</td>
<td>Did you call more than once before your call was answered?</td>
<td><input type="radio"></td>
<td><input type="radio"></td>
<td><input type="radio"></td>
<td><input type="radio"></td>
<td><input type="radio"></td>
</tr>
</table>
</form>


<button type="button" onClick="extract_table()">Extract</button>

<script>
function extract_table()
{

// store html table
var table = $('form').html();
alert(table);

}

</script>

</body>
</html>

Answer

You can reflect the checked or other applied properties, if you loop the items and set as attributes before getting html().

function extract_table() {
  var table = $('form');
  $('form :radio').each(function() {
    $(this).attr('checked', this.checked);
  })
  alert(table.html());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
  <table id="satisfaction_table">
    <tr>
      <th>Nr</th>
      <th>Question</th>
      <th>1 (Unacceptable)</th>
      <th>2 (Poor)</th>
      <th>3 (Average)</th>
      <th>4 (Good)</th>
      <th>5 (Excellent)</th>
    </tr>

    <tr>
      <td>1</td>
      <td>Did you call more than once before your call was answered?</td>
      <td>
        <input type="radio">
      </td>
      <td>
        <input type="radio">
      </td>
      <td>
        <input type="radio">
      </td>
      <td>
        <input type="radio">
      </td>
      <td>
        <input type="radio">
      </td>
    </tr>
  </table>
</form>

<button type="button" onClick="extract_table()">Extract</button>