user1170330 user1170330 - 6 months ago 7
Javascript Question

Duplicate contents of a TD

I have a table with the following structure:

<table>
<tr>
<td>
<input type="text" value="abc" />
</td>
<td>
<input type="text" value="def" />
</td>
<td>
<input type="text" value="ghi" />
</td>
</tr>
<tr>
<td>
<select>
<option>
123
</option>
<option selected="selected">
456
</option>
<option>
789
</option>
</select>
</td>
<td>
<select>
<option>
123
</option>
<option>
456
</option>
<option>
789
</option>
</select>
</td>
<td>
<select>
<option>
123
</option>
<option>
456
</option>
<option>
789
</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="radio" checked="checked" />
</td>
<td>
<input type="radio" />
</td>
<td>
<input type="radio" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" checked="checked" />
</td>
<td>
<input type="checkbox" />
</td>
<td>
<input type="checkbox" />
</td>
</tr>
</table>


All 3 columns have identically elements. I now want to copy the contents from the 1st td (all inputs made by the user) to the other 2 tds.

Unfortunately, I have no idea how to start.

Fiddle.

Answer

One way:

$("button").click(function() {
  copy();
});

function copy() {
  $('tr').each(function() {
    $(this).find('td :input:not(:first)').val($(this).find('td :input:first').val()).prop('checked', $(this).find('td :input:first').prop('checked'))
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="text" value="abc" />
    </td>
    <td>
      <input type="text" value="def" />
    </td>
    <td>
      <input type="text" value="ghi" />
    </td>
  </tr>
  <tr>
    <td>
      <select>
        <option>
          123
        </option>
        <option selected="selected">
          456
        </option>
        <option>
          789
        </option>
      </select>
    </td>
    <td>
      <select>
        <option>
          123
        </option>
        <option>
          456
        </option>
        <option>
          789
        </option>
      </select>
    </td>
    <td>
      <select>
        <option>
          123
        </option>
        <option>
          456
        </option>
        <option>
          789
        </option>
      </select>
    </td>
  </tr>
  <tr>
    <td>
      <input type="radio" />
    </td>
    <td>
      <input type="radio" />
    </td>
    <td>
      <input type="radio" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" checked="checked" />
    </td>
    <td>
      <input type="checkbox" />
    </td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>

<button>
  Copy
</button>