TransWikia.com

Get value of editable tag through oninput function?

Stack Overflow Asked by Swarnabho Biswas Mac on December 16, 2021

<td contenteditable="true" class="name_of_child" oninput="set_text(this,'name_of_child_1')"></td>
<td contenteditable="true" class="date_of_birth" oninput="set_text(this,'date_of_birth_1')"></td>
<td contenteditable="true" class="living_or_deceased" oninput="set_text(this,'living_or_deceased_1')"></td>

I want to get the text through oninput function from table td element like this, but sadly this works with input fields but not with table td tags. Is there a way to get the td text using oninput or any other way?

3 Answers

Why not go more abstract?

const data = {}

const setup = () => {
    document.querySelectorAll('td').forEach(td => td.addEventListener('input', setText));
  
  const btn = document.querySelector('button');
  btn.addEventListener('click', (event) => console.log(data));
}

const updateObject = (key, value) => data[key] = value;

const setText = (event) => {
    const target = event.currentTarget;
  const key = target.dataset.var;
  const value = target.textContent;
  
  updateObject(key, value);
}

window.addEventListener('load', setup)
td {
  background: red;
  min-width: 5em;
}
<table>
  <tr>
    <td contenteditable="true" data-var="name_of_child"></td>
    <td contenteditable="true" data-var="date_of_birth"></td>
    <td contenteditable="true" data-var="living_or_deceased"></td>
  </tr>
</table>
<button>
Show Object
</button>

Answered by Jens Ingels on December 16, 2021

Read the innerHTML or textContent of the reference you pass in to get what the user typed.

function set_text(td, foo) {
   console.log(td.innerHTML);
}
table, tr { width: 100%;}
td { width: 33%;}
<table>
  <tr>
    <td contenteditable="true" class="name_of_child" oninput="set_text(this,'name_of_child_1')">x</td>
    <td contenteditable="true" class="date_of_birth" oninput="set_text(this,'date_of_birth_1')">y</td>
    <td contenteditable="true" class="living_or_deceased" oninput="set_text(this,'living_or_deceased_1')">z</td>
  </tr>
</table>

Answered by epascarello on December 16, 2021

You can give unique id to each td and then try to access the value by passing id into oninput function.

<td id="td1" contenteditable="true" class="name_of_child"oninput="set_text(this,'td1')"></td>
<td id="td2" contenteditable="true" class="date_of_birth" oninput="set_text(this,'td2')"></td>
<td id="td3" contenteditable="true" class="living_or_deceased" oninput="set_text(this,'td3')"></td>

set_text function:

function set_text(this, id) {
    var val = document.getElementById(id).textContent
}

Answered by Dhara Vihol on December 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP